Programs & Examples On #Contracts

Error: Unexpected value 'undefined' imported by the module

I had this issue, it is true that the error on the console ain't descriptive. But if you look at the angular-cli output:

You will see a WARNING, pointing to the circular dependency

WARNING in Circular dependency detected:
module1 -> module2
module2 -> module1

So the solution is to remove one import from one of the Modules.

Is there a way to create interfaces in ES6 / Node 4?

In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):

http://loredanacirstea.github.io/es6-design-patterns/

Design patterns book in javascript may also be useful for you:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Design pattern = classes + interface or multiple inheritance

An example of the factory pattern in ES6 JS (to run: node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

How to break long string to multiple lines

You cannot use the VB line-continuation character inside of a string.

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value &  _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

Using stored procedure output parameters in C#

Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:

DECLARE @NewId int
EXEC    @return_value = [dbo].[usp_InsertContract]
            N'Gary',
            @NewId OUTPUT
SELECT  @NewId

See what it returns. This may give you some hints of why your out param is not filled.

How to make a <svg> element expand or contract to its parent container?

Suppose I have an SVG which looks like this: pic1

And I want to put it in a div and make it fill the div responsively. My way of doing it is as follows:

First I open the SVG file in an application like inkscape. In File->Document Properties I set the width of the document to 800px and and the height to 600px (you can choose other sizes). Then I fit the SVG into this document.

pic2

Then I save this file as a new SVG file and get the path data from this file. Now in HTML the code that does the magic is as follows:

<div id="containerId">    
    <svg
    id="svgId" 
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    x="0"
    y="0"
    width="100%"
    height="100%"
    viewBox="0 0 800 600"
    preserveAspectRatio="none">
       <path d="m0 0v600h800v-600h-75.07031l-431 597.9707-292.445315-223.99609 269.548825-373.97461h-271.0332z" fill="#f00"/>
    </svg>
</div>

Note that width and height of SVG are both set to 100%, since we want it to fill the container vertically and horizontally ,but width and height of the viewBox are the same as the width and height of the document in inkscape which is 800px X 600px. The next thing you need to do is set the preserveAspectRatio to "none". If you need to have more information on this attribute here's a good link. And that's all there is to it.

One more thing is that this code works on almost all the major browsers even the old ones but on some versions of android and ios you need to use some javascrip/jQuery code to keep it consistent. I use the following in document ready and resize functions:

$('#svgId').css({
    'width': $('#containerId').width() + 'px',
    'height': $('#containerId').height() + 'px'
});

Hope it helps!

This could be due to the service endpoint binding not using the HTTP protocol

I had this problem "This could be due to the service endpoint binding not using the HTTP protocol" and the WCF service would shut down (in a development machine)

I figured out: in my case, the problem was because of Enums,

I solved using this

    [DataContract]
    [Flags]
    public enum Fruits
    {
        [EnumMember]
        APPLE = 1,
        [EnumMember]
        BALL = 2,
        [EnumMember]
        ORANGE = 3 

    }

I had to decorate my Enums with DataContract, Flags and all each of the enum member with EnumMember attributes.

I solved this after looking at this msdn Reference:

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

what's going on is that you're trying to access the service using wsHttpBind, which use secured encrypted messages by default (secured Messages). On other hand the netTcpBind uses Secured encrypted channels. (Secured Transport)... BUT basicHttpBind, doesn't require any security at all, and can access anonymous

SO. at the Server side, Add\Change this into your configuration.

<bindings>
    <wsHttpBinding>
     <binding name="wsbind"> 
         <security mode="Message">
             <transport clientCredentialType="Windows" proxyCredentialType="None" />
             <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" establishSecurityContext="true" />
         </security>
     </binding>
    </wsHttpBinding>
</bindings>

then add change your endpoint to

<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsbind" name="wshttpbind" contract="WCFService.IService" > 

That should do it.

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

In my case I had to enable SchUseStrongCrypto for .Net This forces the server to make connection by using TLS 1.0, 1.1 or 1.2. Without SchUseStrongCrypto enabled the connection was trying to use SSL 3.0, which was disabled at my remote endpoint.

Registry keys to enable use of strong crypto:

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

How can I ignore a property when serializing using the DataContractSerializer?

Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.

So, it depends on how you've decorated your class as to how to keep a member from serializing:

  • If you used [DataContract], then remove the [DataMember] for the property.
  • If you used [Serializable], then add [NonSerialized] in front of the field for the property.
  • If you haven't decorated your class, then you should add [IgnoreDataMember] to the property.

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I would suggest using System.Runtime.Serialization.Json that is part of .NET 4.5.

[DataContract]
public class Foo
{
   [DataMember(Name = "data")]
   public Dictionary<string,string> Data { get; set; }
}

Then use it like this:

var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));

var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);

How do I solve this error, "error while trying to deserialize parameter"

I found the actual solution...There is a problem in invoking your service from the client.. check the following things.

  1. Make sure all [datacontract], [datamember] attribute are placed properly i.e. make sure WCF is error free

  2. The WCF client, either web.config or any window app config, make sure config entries are properly pointing to the right ones.. binding info, url of the service..etc..etc

Then above problem : tempuri issue is resolved.. it has nothing to do with namespace.. though you are sure you lived with default,

Hope it saves your number of hours!

What's the best way to convert a number to a string in JavaScript?

It seems similar results when using node.js. I ran this script:

let bar;
let foo = ["45","foo"];

console.time('string concat testing');
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo;
}
console.timeEnd('string concat testing');


console.time("string obj testing");
for (let i = 0; i < 10000000; i++) {
    bar = String(foo);
}
console.timeEnd("string obj testing");

console.time("string both");
for (let i = 0; i < 10000000; i++) {
    bar = "" + foo + "";
}
console.timeEnd("string both");

and got the following results:

? node testing.js
string concat testing: 2802.542ms
string obj testing: 3374.530ms
string both: 2660.023ms

Similar times each time I ran it.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

Suppose you have less data, I suggest to try 70%, 80% and 90% and test which is giving better result. In case of 90% there are chances that for 10% test you get poor accuracy.

TCPDF Save file to folder?

You may try;

$this->Output(/path/to/file);

So for you, it will be like;

$this->Output(/kuitit/);  //or try ("/kuitit/")

How to scroll page in flutter

You can use this one and it's best practice.

SingleChildScrollView(
  child: Column(
    children: <Widget>[
      //Your Widgets
      //Your Widgets,
      //Your Widgets
    ],
  ),
);

What should I do when 'svn cleanup' fails?

I did sudo chmod 777 -R . to be able to change the permissions. Without sudo, it wouldn't work, giving me the same error as running other commands.

Now you can do svn update or whatever, without having to scrap your entire directory and recreating it. This is especially helpful, since your IDE or text editor may already have certain tabs open, or have syncing problems. You don't need to scrap and replace your working directory with this method.

How to clear all input fields in a specific div with jQuery?

Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!

let resetFormObject = (elementID)=> {
        document.getElementById(elementID).getElementsByTagName('input').forEach((input)=>{
            switch(input.type) {
                case 'password':
                case 'text':
                case 'textarea':
                case 'file':
                case 'select-one':
                case 'select-multiple':
                case 'date':
                case 'number':
                case 'tel':
                case 'email':
                    input.value = '';
                    break;
                case 'checkbox':
                case 'radio':
                    input.checked = false;
                    break;
            }
        }); 
    }

Is there any use for unique_ptr with array?

In a nutshell: it's by far the most memory-efficient.

A std::string comes with a pointer, a length, and a "short-string-optimization" buffer. But my situation is I need to store a string that is almost always empty, in a structure that I have hundreds of thousands of. In C, I would just use char *, and it would be null most of the time. Which works for C++, too, except that a char * has no destructor, and doesn't know to delete itself. By contrast, a std::unique_ptr<char[]> will delete itself when it goes out of scope. An empty std::string takes up 32 bytes, but an empty std::unique_ptr<char[]> takes up 8 bytes, that is, exactly the size of its pointer.

The biggest downside is, every time I want to know the length of the string, I have to call strlen on it.

How To: Execute command line in C#, get STD OUT results

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Code is from MSDN.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How to control font sizes in pgf/tikz graphics in latex?

\begin{tikzpicture}

    \tikzstyle{every node}=[font=\small]

\end{tikzpicture}

will give you font size control on every node.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I checked all my settings according to this list: http://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx#feedback . It is helpful to me and for my situation, I find out that Link Dependency of projects' properties has double-quote, which should not be there.

Get a particular cell value from HTML table using JavaScript

Just simply.. #sometime when larger table we can't add the id to each tr

     <table>
        <tr>
            <td>some text</td>
            <td>something</td>
        </tr>
        <tr>
            <td>Hello</td>
            <td>Hel</td>
        </tr>
    </table>

    <script>
        var cell = document.getElementsByTagName("td"); 
        var i = 0;
        while(cell[i] != undefined){
            alert(cell[i].innerHTML); //do some alert for test
            i++;
            }//end while
    </script>

Passing arguments to C# generic new() of templated type

Object initializer

If your constructor with the parameter isn't doing anything besides setting a property, you can do this in C# 3 or better using an object initializer rather than calling a constructor (which is impossible, as has been mentioned):

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       tabListItems.Add(new T() { YourPropertyName = listItem } ); // Now using object initializer
   } 
   ...
}

Using this, you can always put any constructor logic in the default (empty) constructor, too.

Activator.CreateInstance()

Alternatively, you could call Activator.CreateInstance() like so:

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
        object[] args = new object[] { listItem };
        tabListItems.Add((T)Activator.CreateInstance(typeof(T), args)); // Now using Activator.CreateInstance
   } 
   ...
}

Note that Activator.CreateInstance can have some performance overhead that you may want to avoid if execution speed is a top priority and another option is maintainable to you.

How to get current local date and time in Kotlin

Try this :

 val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
 val currentDate = sdf.format(Date())
 System.out.println(" C DATE is  "+currentDate)

Re-sign IPA (iPhone)

If your APP is built using Flutter tools, please examine the codesign info for all pod extensions:

codesign -d --verbose=4 Runner.app/Frameworks/xxx.framework |& grep 'Authority='

The result should be the name of your team.

Run the shell script below to codesign all extensions:

IDENTITY=<prefix of Team ID number>
ENTITLEMENTS=<entitlements.plist>
find Payload/Runner.app -type d -name '*framework' | xargs -I '{}' codesign -s $IDENTITY -f --entitlements $ENTITLEMENTS {} 

And finally don't forget to codesign the Runner.app itself

Testing socket connection in Python

You can use the function connect_ex. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as errno in C):

s =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
    print "problem with socket!"
else:
    print "everything it's ok!"

How can I increase the size of a bootstrap button?

Use block level buttons, those that span the full width of a parent You can achieve this by adding btn-block class your button element.

Documentation here

What is the OR operator in an IF statement

See C# Operators for C# operators including OR which is ||

Reading/writing an INI file

This article on CodeProject "An INI file handling class using C#" should help.

The author created a C# class "Ini" which exposes two functions from KERNEL32.dll. These functions are: WritePrivateProfileString and GetPrivateProfileString. You will need two namespaces: System.Runtime.InteropServices and System.Text.

Steps to use the Ini class

In your project namespace definition add

using INI;

Create a INIFile like this

INIFile ini = new INIFile("C:\\test.ini");

Use IniWriteValue to write a new value to a specific key in a section or use IniReadValue to read a value FROM a key in a specific Section.

Note: if you're beginning from scratch, you could read this MSDN article: How to: Add Application Configuration Files to C# Projects. It's a better way for configuring your application.

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

How do I print colored output to the terminal in Python?

Color_Console library is comparatively easier to use. Install this library and the following code would help you.

from Color_Console import *
ctext("This will be printed" , "white" , "blue")
The first argument is the string to be printed, The second argument is the color of 
the text and the last one is the background color.

The latest version of Color_Console allows you to pass a list or dictionary of colors which would change after a specified delay time.

Also, they have good documentation on all of their functions.

Visit https://pypi.org/project/Color-Console/ to know more.

What is the memory consumption of an object in Java?

No, registering an object takes a bit of memory too. 100 objects with 1 attribute will take up more memory.

How do I calculate a point on a circle’s circumference?

The parametric equation for a circle is

x = cx + r * cos(a)
y = cy + r * sin(a)

Where r is the radius, cx,cy the origin, and a the angle.

That's pretty easy to adapt into any language with basic trig functions. Note that most languages will use radians for the angle in trig functions, so rather than cycling through 0..360 degrees, you're cycling through 0..2PI radians.

Make absolute positioned div expand parent div height

I had a similar problem. To solve this (instead of calculate the iframe's height using the body, document or window) I created a div that wraps the whole page content (a div with an id="page" for example) and then I used its height.

How to Split Image Into Multiple Pieces in Python

Here is a concise, pure-python solution that works in both python 3 and 2:

from PIL import Image

infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
chopsize = 300

img = Image.open(infile)
width, height = img.size

# Save Chops of original image
for x0 in range(0, width, chopsize):
   for y0 in range(0, height, chopsize):
      box = (x0, y0,
             x0+chopsize if x0+chopsize <  width else  width - 1,
             y0+chopsize if y0+chopsize < height else height - 1)
      print('%s %s' % (infile, box))
      img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))

Notes:

  • The crops that go over the right and bottom of the original image are adjusted to the original image limit and contain only the original pixels.
  • It's easy to choose a different chopsize for w and h by using two chopsize vars and replacing chopsize as appropriate in the code above.

  • socket.error:[errno 99] cannot assign requested address and namespace in python

    Stripping things down to basics this is what you would want to test with:

    import socket
    server = socket.socket() 
    server.bind(("10.0.0.1", 6677)) 
    server.listen(4) 
    client_socket, client_address = server.accept()
    print(client_address, "has connected")
    while 1==1:
        recvieved_data = client_socket.recv(1024)
        print(recvieved_data)
    

    This works assuming a few things:

    1. Your local IP address (on the server) is 10.0.0.1 (This video shows you how)
    2. No other software is listening on port 6677

    Also note the basic concept of IP addresses:

    Try the following, open the start menu, in the "search" field type cmd and press enter. Once the black console opens up type ping www.google.com and this should give you and IP address for google. This address is googles local IP and they bind to that and obviously you can not bind to an IP address owned by google.

    With that in mind, you own your own set of IP addresses. First you have the local IP of the server, but then you have the local IP of your house. In the below picture 192.168.1.50 is the local IP of the server which you can bind to. You still own 83.55.102.40 but the problem is that it's owned by the Router and not your server. So even if you visit http://whatsmyip.com and that tells you that your IP is 83.55.102.40 that is not the case because it can only see where you're coming from.. and you're accessing your internet from a router.

    enter image description here

    In order for your friends to access your server (which is bound to 192.168.1.50) you need to forward port 6677 to 192.168.1.50 and this is done in your router. Assuming you are behind one.

    If you're in school there's other dilemmas and routers in the way most likely.

    XML element with attribute and content using JAXB

    Here is working solution:

    Output:

    public class XmlTest {
    
        private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
    
        @Test
        public void createDefaultBook() throws JAXBException {
            JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
    
            StringWriter writer = new StringWriter();
            marshaller.marshal(new Book(), writer);
    
            log.debug("Book xml:\n {}", writer.toString());
        }
    
    
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlRootElement(name = "book")
        public static class Book {
    
            @XmlElementRef(name = "price")
            private Price price = new Price();
    
    
        }
    
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlRootElement(name = "price")
        public static class Price {
            @XmlAttribute(name = "drawable")
            private Boolean drawable = true; //you may want to set default value here
    
            @XmlValue
            private int priceValue = 1234;
    
            public Boolean getDrawable() {
                return drawable;
            }
    
            public void setDrawable(Boolean drawable) {
                this.drawable = drawable;
            }
    
            public int getPriceValue() {
                return priceValue;
            }
    
            public void setPriceValue(int priceValue) {
                this.priceValue = priceValue;
            }
        }
    }
    

    Output:

    22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <book>
        <price drawable="true">1234</price>
    </book>
    

    Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

    https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

    The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:

    SET autocommit=0;
    LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
    COMMIT;
    UNLOCK TABLES;
    

    Handle Guzzle exception and get HTTP body

    if put 'http_errors' => false in guzzle request options, then it would stop throw exception while get 4xx or 5xx error, like this: $client->get(url, ['http_errors' => false]). then you parse the response, not matter it's ok or error, it would be in the response for more info

    How to set IntelliJ IDEA Project SDK

    For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure enter image description here Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 enter image description here Now Just go Project under Project settings and select the project SDK. enter image description here

    How to center HTML5 Videos?

    Try this:

    video {
    display:block;
    margin:0 auto;
    }
    

    How to get attribute of element from Selenium?

    You are probably looking for get_attribute(). An example is shown here as well

    def test_chart_renders_from_url(self):
        url = 'http://localhost:8000/analyse/'
        self.browser.get(url)
        org = driver.find_element_by_id('org')
        # Find the value of org?
        val = org.get_attribute("attribute name")
    

    Responsive bootstrap 3 timepicker?

    Was someone able to have a timepicker working with Bootstrap 3.4?

    Why call git branch --unset-upstream to fixup?

    Issue: Your branch is based on 'origin/master', but the upstream is gone.

    Solution: git branch --unset-upstream

    Angular 2: How to access an HTTP response body?

    The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

      this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      .map(res => res.json())
      .subscribe(data => {
        console.log(data);
      })
    

    https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

    NGinx Default public www location?

    If you need to find out nginx public root folder that was defined at compile time you can just check your access.log file.

    1. Open nginx.conf
    2. Find the log_format directive
    3. The value of the log_format is a template string that is used to write information to the access.log file. You can add $document_root variable to this template string to log default www root location to a file.

    Here is an example from the http section of nginx.conf with modified log_format directive, $document_root is added at the beginning of the string:

        http {
            include       /etc/nginx/mime.types;
            default_type  application/octet-stream;
    
                      ## ADD $document_root HERE ##
            log_format  main  '$document_root $remote_addr - $remote_user [$time_local] "$request" '
                              '$status $body_bytes_sent "$http_referer" '
                              '"$http_user_agent" "$http_x_forwarded_for"';
    
            access_log  /var/log/nginx/access.log  main;
    
            etc. .......
    
    1. Then backup all configuration files *.conf in conf.d directory and create there configuration file, test.conf with the following lines:

      server{
          listen 80;
          server_name localhost;
      }
      
      1. Add following line to /etc/hosts file: 127.0.0.1 localhost

      2. Reload nginx configuration: nginx -s reload

      3. Send GET request to http://localhost: curl http://localhost

      4. Check the last string of access.log:tail -n 1 /var/log/nginx/access.log

    Here is the sample output of this command, where /etc/nginx/html is the default document root defined at compile time :

        /etc/nginx/html 127.0.0.1 - - [15/Mar/2017:17:12:25 +0200] "GET / HTTP/1.1" 404 169 "-" "curl/7.35.0" "-"
    

    What are enums and why are they useful?

    In my opinion, all the answers you got up to now are valid, but in my experience, I would express it in a few words:

    Use enums if you want the compiler to check the validity of the value of an identifier.

    Otherwise, you can use strings as you always did (probably you defined some "conventions" for your application) and you will be very flexible... but you will not get 100% security against typos on your strings and you will realize them only in runtime.

    Regex for allowing alphanumeric,-,_ and space

    For me I wanted a regex which supports a strings as preceding. Basically, the motive is to support some foreign countries postal format as it should be an alphanumeric with spaces allowed.

    1. ABC123
    2. ABC 123
    3. ABC123(space)
    4. ABC 123 (space)

    So I ended up by writing custom regex as below.

    /^([a-z]+[\s]*[0-9]+[\s]*)+$/i
    

    enter image description here

    Here, I gave * in [\s]* as it is not mandatory to have a space. A postal code may or may not contains space in my case.

    VSCode Change Default Terminal

    I just type following keywords in the opened terminal;

    1. powershell
    2. bash
    3. cmd
    4. node
    5. python (or python3)

    See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

    It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

    Converting int to bytes in Python 3

    The behaviour comes from the fact that in Python prior to version 3 bytes was just an alias for str. In Python3.x bytes is an immutable version of bytearray - completely new type, not backwards compatible.

    PHP Try and Catch for SQL Insert

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    

    I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
    I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

    Converting Long to Date in Java returns 1970

    Those are probably timestamps in seconds and not in milliseconds which is required for the java new Date(long) constructor. Just multiply them by 1000 and you should be allright.

    How to check if string contains Latin characters only?

    All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:

    if (!str.match(/^[\d]+$/)) {
        //contains other characters as well
    }
    

    getting the table row values with jquery

    Give something like this a try:

    $(document).ready(function(){
        $("#thisTable tr").click(function(){
            $(this).find("td").each(function(){
                alert($(this).html());
            });
        });
    });?
    

    Here is a fiddle of the code in action: http://jsfiddle.net/YhZsW/

    How can I get query parameters from a URL in Vue.js?

    Try this code

     var vm = new Vue({
         created()
         {
           let urlParams = new URLSearchParams(window.location.search);
               console.log(urlParams.has('yourParam')); // true
               console.log(urlParams.get('yourParam')); // "MyParam"
         },
    

    error: Error parsing XML: not well-formed (invalid token) ...?

    Problem is that you are doing something wrong in XML layout file

    android:text=" <- Go Back" // this creates error
    android:text="Go Back" // correct way
    

    T-SQL: Export to new Excel file

    Use PowerShell:

    $Server = "TestServer"
    $Database = "TestDatabase"
    $Query = "select * from TestTable"
    $FilePath = "C:\OutputFile.csv"
    
    # This will overwrite the file if it already exists.
    Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath
    

    In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

    Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

    In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.

        import {NgModule } from '@angular/core';
        import { BrowserModule } from '@angular/platform-browser';
        import {EventListComponent} from './EventList.Component';
        import {EventThumbnailComponent} from './EventThumbnail.Component';
        import { EventService } from './shared/Event.Service'
        import {ToastrService} from '../shared/toastr.service';
        import {EventDetailsComponent} from './event-details/event.details.component';
        import { RouterModule } from "@angular/router";
        @NgModule({
          imports:[BrowserModule,RouterModule],
          declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
          exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
           providers: [EventService,ToastrService]
        })
        export class EventModule {
            
         }
    

    How to search a specific value in all tables (PostgreSQL)?

    And if someone think it could help. Here is @Daniel Vérité's function, with another param that accept names of columns that can be used in search. This way it decrease the time of processing. At least in my test it reduced a lot.

    CREATE OR REPLACE FUNCTION search_columns(
        needle text,
        haystack_columns name[] default '{}',
        haystack_tables name[] default '{}',
        haystack_schema name[] default '{public}'
    )
    RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
    AS $$
    begin
      FOR schemaname,tablename,columnname IN
          SELECT c.table_schema,c.table_name,c.column_name
          FROM information_schema.columns c
          JOIN information_schema.tables t ON
            (t.table_name=c.table_name AND t.table_schema=c.table_schema)
          WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
            AND c.table_schema=ANY(haystack_schema)
            AND (c.column_name=ANY(haystack_columns) OR haystack_columns='{}')
            AND t.table_type='BASE TABLE'
      LOOP
        EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
           schemaname,
           tablename,
           columnname,
           needle
        ) INTO rowctid;
        IF rowctid is not null THEN
          RETURN NEXT;
        END IF;
     END LOOP;
    END;
    $$ language plpgsql;
    

    Bellow is an example of usage of the search_function created above.

    SELECT * FROM search_columns('86192700'
        , array(SELECT DISTINCT a.column_name::name FROM information_schema.columns AS a
                INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
            WHERE 
                a.column_name iLIKE '%cep%' 
                AND b.table_type = 'BASE TABLE'
                AND b.table_schema = 'public'
        )
    
        , array(SELECT b.table_name::name FROM information_schema.columns AS a
                INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)
            WHERE 
                a.column_name iLIKE '%cep%' 
                AND b.table_type = 'BASE TABLE'
                AND b.table_schema = 'public')
    );
    

    Pandas group-by and sum

    If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

    df.groupby(['Fruit','Name'])['Number'].sum().reset_index()
    
    Fruit   Name       Number
    Apples  Bob        16
    Apples  Mike        9
    Apples  Steve      10
    Grapes  Bob        35
    Grapes  Tom        87
    Grapes  Tony       15
    Oranges Bob        67
    Oranges Mike       57
    Oranges Tom        15
    Oranges Tony        1
    

    As seen in the other answers:

    df.groupby(['Fruit','Name'])['Number'].sum()
    
                   Number
    Fruit   Name         
    Apples  Bob        16
            Mike        9
            Steve      10
    Grapes  Bob        35
            Tom        87
            Tony       15
    Oranges Bob        67
            Mike       57
            Tom        15
            Tony        1
    

    Calling jQuery method from onClick attribute in HTML

    I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:

    _x000D_
    _x000D_
    $(document).ready(function() {_x000D_
      $button = $('<input id="1" type="button" value="ahaha" />');_x000D_
      $('body').append($button);_x000D_
      $button.click(function() {_x000D_
        console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
      });_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    _x000D_
    <p>And here is my HTML page:</p>_x000D_
    _x000D_
    <div class="Title">Welcome!</div>
    _x000D_
    _x000D_
    _x000D_

    Convert seconds into days, hours, minutes and seconds

    foreach ($email as $temp => $value) {
        $dat = strtotime($value['subscription_expiration']); //$value come from mysql database
    //$email is an array from mysqli_query()
        $date = strtotime(date('Y-m-d'));
    
        $_SESSION['expiry'] = (((($dat - $date)/60)/60)/24)." Days Left";
    //you will get the difference from current date in days.
    }
    

    $value come from Database. This code is in Codeigniter. $SESSION is used for storing user subscriptions. it is mandatory. I used it in my case, you can use whatever you want.

    How to hide Android soft keyboard on EditText

    My test result:

    with setInputType:

    editText.setInputType(InputType.TYPE_NULL);
    

    the soft keyboard disappears, but the cursor will also disappear.

    with setShowSoftInputOnFocus:

    editText.setShowSoftInputOnFocus(false)
    

    It works as expected.

    Space between two divs

    If you don't require support for IE6:

    h1 {margin-bottom:20px;}
    div + div {margin-top:10px;}
    

    The second line adds spacing between divs, but will not add any before the first div or after the last one.

    What is the syntax meaning of RAISERROR()

    16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

    BEGIN TRY
        -- RAISERROR with severity 11-19 will cause execution to 
        -- jump to the CATCH block.
        RAISERROR ('Error raised in TRY block.', -- Message text.
                   16, -- Severity.
                   1 -- State.
                   );
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMessage NVARCHAR(4000);
        DECLARE @ErrorSeverity INT;
        DECLARE @ErrorState INT;
    
        SELECT 
            @ErrorMessage = ERROR_MESSAGE(),
            @ErrorSeverity = ERROR_SEVERITY(),
            @ErrorState = ERROR_STATE();
    
        -- Use RAISERROR inside the CATCH block to return error
        -- information about the original error that caused
        -- execution to jump to the CATCH block.
        RAISERROR (@ErrorMessage, -- Message text.
                   @ErrorSeverity, -- Severity.
                   @ErrorState -- State.
                   );
    END CATCH;
    

    You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

    Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

    If you have not changed the defaults of Spring Boot (meaning you are using @EnableAutoConfiguration or @SpringBootApplication and have not changed any Property Source handling), then it will look for properties with the following order (highest overrides lowest):

    1. A /config subdir of the current directory
    2. The current directory
    3. A classpath /config package
    4. The classpath root

    The list above is mentioned in this part of the documentation

    What that means is that if a property is found for example application.properties under src/resources is will be overridden by a property with the same name found in application.properties in the /config directory that is "next" to the packaged jar.

    This default order used by Spring Boot allows for very easy configuration externalization which in turn makes applications easy to configure in multiple environments (dev, staging, production, cloud etc)

    To see the whole set of features provided by Spring Boot for property reading (hint: there is a lot more available than reading from application.properties) check out this part of the documentation.

    As one can see from my short description above or from the full documentation, Spring Boot apps are very DevOps friendly!

    Live video streaming using Java?

    JMF was abandoned. VLC is more up to date and it reads everything. https://stackoverflow.com/a/5160010

    I think vlc beats every other software out there yet, or at least the ones that I know...

    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.

    Making RGB color in Xcode

    Color picker plugin for Interface Builder

    There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

    Xcode plugin

    This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

    Objective-C

    UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];
    

    Swift

    let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)
    

    Pods and libraries

    There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

    What's the difference between JPA and Hibernate?

    JPA is an API, one which Hibernate implements.Hibernate predates JPA. Before JPA, you write native hibernate code to do your ORM. JPA is just the interface, so now you write JPA code and you need to find an implementation. Hibernate happens to be an implementation.

    So your choices are this: hibernate, toplink, etc...

    The advantage to JPA is that it allows you to swap out your implementation if need be. The disadvantage is that the native hibernate/toplink/etc... API may offer functionality that the JPA specification doesn't support.

    Position Absolute + Scrolling

    So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

    and the relevant code:

    html:

    <div class="container">
      <div class="inner">
        Lorem ipsum ...
      </div>
      <div class="full-height"></div>
    </div>
    

    css:

    .container{
      height: 256px;
      position: relative;
    }
    .inner{
      height: 100%;
      overflow: scroll;
    }
    .full-height{
      position: absolute;
      left: 0;
      width: 20%;
      top: 0;
      height: 100%;
    }
    

    Why does 2 mod 4 = 2?

    The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:

    23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
    50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
    9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)
    

    Accessing elements by type in javascript

    In plain-old JavaScript you can do this:

    var inputs = document.getElementsByTagName('input');
    
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].type.toLowerCase() == 'text') {
            alert(inputs[i].value);
        }
    }
    

    In jQuery, you would just do:

    // select all inputs of type 'text' on the page
    $("input:text")
    
    // hide all text inputs which are descendants of div class="foo"
    $("div.foo input:text").hide();
    

    Understanding repr( ) function in Python

    The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

    Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?

    I'm not sure what you're asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr.

    Also note that the eval(repr(x)) == x analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr output.

    Google Maps Android API v2 Authorization failure

    YOUR ECLIPSE MAYBE CHANGED SHA1 KEY, so you must regen your google key with new SHA1 key in here: https://console.developers.google.com/project/watchful-net-796/apiui/credential After that, copy new key into manifest and reload this google page some times, and your key will be updated, rebuild your project, it will work. P/S: For my error, I deleted .android folder so eclipse regen SHA1.

    Complexities of binary tree traversals

    Depth first traversal of a binary tree is of order O(n).

    Algo -- <b>
        PreOrderTrav():-----------------T(n)<b>
        if root is null---------------O(1)<b>
          return null-----------------O(1)<b>
        else:-------------------------O(1)<b>
          print(root)-----------------O(1)<b>
          PreOrderTrav(root.left)-----T(n/2)<b>
          PreOrderTrav(root.right)----T(n/2)<b>
    

    If the time complexity of the algo is T(n) then it can be written as T(n) = 2*T(n/2) + O(1). If we apply back substitution we will get T(n) = O(n).

    How can I initialize a MySQL database with schema in a Docker container?

    Below is the Dockerfile I used successfully to install xampp, create a MariaDB with scheme and pre populated with the info used on local server(usrs,pics orders,etc..)

    FROM ubuntu:14.04
    
    COPY Ecommerce.sql /root
    
    RUN apt-get update \
     && apt-get install wget -yq \
     && apt-get install nano \
     && wget https://www.apachefriends.org/xampp-files/7.1.11/xampp-linux-x64-7.1.11-0-installer.run \
     && mv xampp-linux-x64-7.1.11-0-installer.run /opt/ \
     && cd /opt/ \
     && chmod +x xampp-linux-x64-7.1.11-0-installer.run \
     && printf 'y\n\y\n\r\n\y\n\r\n' | ./xampp-linux-x64-7.1.11-0-installer.run \
     && cd /opt/lampp/bin \
     && /opt/lampp/lampp start \
     && sleep 5s \
    
     && ./mysql -uroot -e "CREATE DATABASE Ecommerce" \
     && ./mysql -uroot -D Ecommerce < /root/Ecommerce.sql \
     && cd / \
     && /opt/lampp/lampp reload \
     && mkdir opt/lampp/htdocs/Ecommerce
    
    COPY /Ecommerce /opt/lampp/htdocs/Ecommerce
    
    EXPOSE 80
    

    Force HTML5 youtube video

    Inline tag is used to add another src of document to the current html element.

    In your case an video of a youtube and we need to specify the html type(4 or 5) to the browser externally to the link

    so add ?html=5 to the end of the link.. :)

    How can I get dict from sqlite query?

    Similar like before-mentioned solutions, but most compact:

    db.row_factory = lambda C, R: { c[0]: R[i] for i, c in enumerate(C.description) }
    

    How can I check if a string represents an int, without using try/except?

    I have one possibility that doesn't use int at all, and should not raise an exception unless the string does not represent a number

    float(number)==float(number)//1
    

    It should work for any kind of string that float accepts, positive, negative, engineering notation...

    How to stop INFO messages displaying on spark console?

    Thanks @AkhlD and @Sachin Janani for suggesting changes in .conf file.

    Following code solved my issue:

    1) Added import org.apache.log4j.{Level, Logger} in import section

    2) Added following line after creation of spark context object i.e. after val sc = new SparkContext(conf):

    val rootLogger = Logger.getRootLogger()
    rootLogger.setLevel(Level.ERROR)
    

    JavaScript sleep/wait before continuing

    JS does not have a sleep function, it has setTimeout() or setInterval() functions.

    If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

    //code before the pause
    setTimeout(function(){
        //do what you need here
    }, 2000);
    

    see example here : http://jsfiddle.net/9LZQp/

    This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

    console.log("HELLO");
    setTimeout(function(){
        console.log("THIS IS");
    }, 2000);
    console.log("DOG");
    

    will print this in the console:

    HELLO
    DOG
    THIS IS
    

    (note that DOG is printed before THIS IS)


    You can use the following code to simulate a sleep for short periods of time:

    function sleep(milliseconds) {
      var start = new Date().getTime();
      for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
          break;
        }
      }
    }
    

    now, if you want to sleep for 1 second, just use:

    sleep(1000);
    

    example: http://jsfiddle.net/HrJku/1/

    please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

    Declare and Initialize String Array in VBA

    Dim myStringArray() As String
    *code*
    redim myStringArray(size_of_your_array)
    

    Then you can do something static like this:

    myStringArray = { item_1, item_2, ... }
    

    Or something iterative like this:

    Dim x
    For x = 0 To size_of_your_array
        myStringArray(x) = data_source(x).Name
    Next x
    

    Codeigniter's `where` and `or_where`

    You can change your code to this:

    $where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
    $this->db
        ->select('*')
        ->from('library')
        ->where('library.rating >=', $form['slider'])
        ->where('library.votes >=', '1000')
        ->where('library.language !=', 'German')
        ->where($where_au)
        ->where('library.release_year >=', $year_start)
        ->where('library.release_year <=', $year_end)
        ->join('rating_repo', 'library.id = rating_repo.id');
    

    Tip: to watch the generated query you can use

    echo $this->db->last_query(); die();
    

    Start script missing error when running npm start

    I got this error because I wasn't in the right directory in terminal.

    App with the scripts was in folder B. Folder B was in folder A. I open folder A in vscode and enter "npm run start" into the built in terminal and got the error. try "cd folder B", opening folder B in the ide, or organizing your stuff better than I did in the first place.

    python .replace() regex

    You can use the re module for regexes, but regexes are probably overkill for what you want. I might try something like

    z.write(article[:article.index("</html>") + 7]
    

    This is much cleaner, and should be much faster than a regex based solution.

    Regex to extract substring, returning 2 results for some reason

    match returns an array.

    The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

    var tesst = "afskfsd33j"
    var test = tesst.match(/a(.*)j/);
    alert (test[1]);
    

    What is the reason for the error message "System cannot find the path specified"?

    There is not only 1 %SystemRoot%\System32 on Windows x64. There are 2 such directories.

    The real %SystemRoot%\System32 directory is for 64-bit applications. This directory contains a 64-bit cmd.exe.

    But there is also %SystemRoot%\SysWOW64 for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32. It contains a 32-bit cmd.exe.

    32-bit applications can access %SystemRoot%\System32 for 64-bit applications by using the alias %SystemRoot%\Sysnative in path.

    For more details see the Microsoft documentation about File System Redirector.

    So the subdirectory run was created either in %SystemRoot%\System32 for 64-bit applications and 32-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\SysWOW64 which is %SystemRoot%\System32 for 32-bit cmd.exe or the subdirectory run was created in %SystemRoot%\System32 for 32-bit applications and 64-bit cmd is run for which this directory does not exist because there is no subdirectory run in %SystemRoot%\System32 as this subdirectory exists only in %SystemRoot%\SysWOW64.

    The following code could be used at top of the batch file in case of subdirectory run is in %SystemRoot%\System32 for 64-bit applications:

    @echo off
    set "SystemPath=%SystemRoot%\System32"
    if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
    

    Every console application in System32\run directory must be executed with %SystemPath% in the batch file, for example %SystemPath%\run\YourApp.exe.

    How it works?

    There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32 as defined at top.

    But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative. In this case the batch file is processed currently by 32-bit cmd.exe and only in this case %SystemRoot%\Sysnative needs to be used at all. Otherwise %SystemRoot%\System32 can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe, this is the directory containing the 64-bit console applications (and the subdirectory run).

    Note: %SystemRoot%\Sysnative is not a directory! It is not possible to cd to %SystemRoot%\Sysnative or use if exist %SystemRoot%\Sysnative or if exist %SystemRoot%\Sysnative\. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe or more general if exist %SystemRoot%\Sysnative\*.

    How can you get the Manifest Version number from the App's (Layout) XML variables?

    Easiest solution is to use BuildConfig.

    I use BuildConfig.VERSION_NAME in my application.

    You can also use BuildConfig.VERSION_CODE to get version code.

    POI setting Cell Background to a Custom Color

    See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

    Custom colors

    HSSF:

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    HSSFRow row = sheet.createRow((short) 0);
    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue("Default Palette");
    
    //apply some colors from the standard palette,
    // as in the previous examples.
    //we'll use red text on a lime background
    
    HSSFCellStyle style = wb.createCellStyle();
    style.setFillForegroundColor(HSSFColor.LIME.index);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    
    HSSFFont font = wb.createFont();
    font.setColor(HSSFColor.RED.index);
    style.setFont(font);
    
    cell.setCellStyle(style);
    
    //save with the default palette
    FileOutputStream out = new FileOutputStream("default_palette.xls");
    wb.write(out);
    out.close();
    
    //now, let's replace RED and LIME in the palette
    // with a more attractive combination
    // (lovingly borrowed from freebsd.org)
    
    cell.setCellValue("Modified Palette");
    
    //creating a custom palette for the workbook
    HSSFPalette palette = wb.getCustomPalette();
    
    //replacing the standard red with freebsd.org red
    palette.setColorAtIndex(HSSFColor.RED.index,
            (byte) 153,  //RGB red (0-255)
            (byte) 0,    //RGB green
            (byte) 0     //RGB blue
    );
    //replacing lime with freebsd.org gold
    palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
    
    //save with the modified palette
    // note that wherever we have previously used RED or LIME, the
    // new colors magically appear
    out = new FileOutputStream("modified_palette.xls");
    wb.write(out);
    out.close();
    

    XSSF:

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell( 0);
    cell.setCellValue("custom XSSF colors");
    
    XSSFCellStyle style1 = wb.createCellStyle();
    style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
    style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
    

    How do I create a constant in Python?

    Python dictionaries are mutable, so they don't seem like a good way to declare constants:

    >>> constants = {"foo":1, "bar":2}
    >>> print constants
    {'foo': 1, 'bar': 2}
    >>> constants["bar"] = 3
    >>> print constants
    {'foo': 1, 'bar': 3}
    

    How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }
    

    decorate your model like this. can use a bootstrap date time picker I used this one. https://github.com/Eonasdan/bootstrap-datetimepicker/

    I suppose you already have bundles for bootstrap css and js

    Your date picker bundle entries

     bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
               "~/Scripts/moment.min.js",
               "~/Scripts/bootstrap-datetimepicker.min.js"));
    
            bundles.Add(new StyleBundle("~/Content/datepicker").Include(
                     "~/Content/bootstrap-datetimepicker.min.css"));
    

    Render bundles on your Layout View

    @Styles.Render("~/Content/datepicker")
    @Scripts.Render("~/bundles/datePicker")
    

    Your HTML in view

    <div class="form-group">
            @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
                @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
            </div>
    </div>
    

    At the end of your view add this.

    <script>
        $(document).ready(function () {
            $('.datetimepicker').datetimepicker({
                format: 'lll'
            });
        });
    </script>
    

    What is the difference between ng-if and ng-show/ng-hide

    Fact, that ng-if directive, unlike ng-show, creates its own scope, leads to interesting practical difference:

    _x000D_
    _x000D_
    angular.module('app', []).controller('ctrl', function($scope){_x000D_
      $scope.delete = function(array, item){_x000D_
        array.splice(array.indexOf(item), 1);_x000D_
      }_x000D_
    })
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    _x000D_
    <div ng-app='app' ng-controller='ctrl'>_x000D_
       <h4>ng-if:</h4>_x000D_
       <ul ng-init='arr1 = [1,2,3]'>_x000D_
          <li ng-repeat='x in arr1'>_x000D_
            {{show}}_x000D_
            <button ng-if='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
            <button ng-if='show' ng-click='delete(arr1, x)'>Yes {{show}}</button>_x000D_
            <button ng-if='show' ng-click='show=!show'>No</button>_x000D_
          </li>_x000D_
       </ul>_x000D_
       _x000D_
       <h4>ng-show:</h4>_x000D_
       <ul ng-init='arr2 = [1,2,3]'>_x000D_
          <li ng-repeat='x in arr2'>_x000D_
            {{show}}_x000D_
            <button ng-show='!show' ng-click='show=!show'>Delete {{show}}</button>_x000D_
            <button ng-show='show' ng-click='delete(arr2, x)'>Yes {{show}}</button>_x000D_
            <button ng-show='show' ng-click='show=!show'>No</button>_x000D_
          </li>_x000D_
       </ul>_x000D_
       _x000D_
       <h4>ng-if with $parent:</h4>_x000D_
        <ul ng-init='arr3 = [1,2,3]'>_x000D_
          <li ng-repeat='item in arr3'>_x000D_
            {{show}}_x000D_
            <button ng-if='!show' ng-click='$parent.show=!$parent.show'>Delete {{$parent.show}}</button>_x000D_
            <button ng-if='show' ng-click='delete(arr3, x)'>Yes {{$parent.show}}</button>_x000D_
            <button ng-if='show' ng-click='$parent.show=!$parent.show'>No</button>_x000D_
          </li>_x000D_
       </ul>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    At first list, on-click event, show variable, from innner/own scope, is changed, but ng-if is watching on another variable from outer scope with same name, so solution not works. At case of ng-show we have the only one show variable, that is why it works. To fix first attempt, we should reference to show from parent/outer scope via $parent.show.

    How to cut first n and last n columns?

    To use AWK to cut off the first and last fields:

    awk '{$1 = ""; $NF = ""; print}' inputfile
    

    Unfortunately, that leaves the field separators, so

    aaa bbb ccc
    

    becomes

    [space]bbb[space]
    

    To do this using kurumi's answer which won't leave extra spaces, but in a way that's specific to your requirements:

    awk '{delim = ""; for (i=2;i<=NF-1;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile
    

    This also fixes a couple of problems in that answer.

    To generalize that:

    awk -v skipstart=1 -v skipend=1 '{delim = ""; for (i=skipstart+1;i<=NF-skipend;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile
    

    Then you can change the number of fields to skip at the beginning or end by changing the variable assignments at the beginning of the command.

    Paging with Oracle

    Ask Tom on pagination and very, very useful analytic functions.

    This is excerpt from that page:

    select * from (
        select /*+ first_rows(25) */
         object_id,object_name,
         row_number() over
        (order by object_id) rn
        from all_objects
    )
    where rn between :n and :m
    order by rn;
    

    Is there a limit on number of tcp/ip connections between machines on linux?

    Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux

    How to save a dictionary to a file?

    I'm not sure what your first question is, but if you want to save a dictionary to file you should use the json library. Look up the documentation of the loads and puts functions.

    How to install an apk on the emulator in Android Studio?

    Start your Emulator from Android Studio Tools->Android-> AVD Manager then select an emulator image and start it.

    After emulator is started just drag and drop the APK Very simple.

    Why should a Java class implement comparable?

    Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".

    Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?

    TreeSet<Integer> m = new TreeSet<Integer>(); 
    m.add(1);
    m.add(3);
    m.add(2);
    for (Integer i : m)
    ... // values will be sorted
    

    But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:

    public class District {
      String zipcode; 
      Double populationDensity;
    }
    

    Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:

    public class District implements Comparable<District>{
      String zipcode; 
      Double populationDensity;
      public int compareTo(District other)
      {
        return populationDensity.compareTo(other.populationDensity);
      }
    }
    

    Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.

    Basically the ordering logic has to exist somewhere. That can be -

    • in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)

    • supplied in an external comparator, as in the example above.

    Adding a caption to an equation in LaTeX

    The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

    \begin{figure}
    \[ E = m c^2 \]
    \caption{A famous equation}
    \end{figure}
    

    The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

    \[ E = m c^2 \]
    \captionof{figure}{A famous equation}
    

    This will also produce an entry for the \listoffigures, if your document has one.

    To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

    How can I change a button's color on hover?

    a.button a:hover means "a link that's being hovered over that is a child of a link with the class button".

    Go instead for a.button:hover.

    Check if Nullable Guid is empty in c#

    You should use the HasValue property:

    SomeProperty.HasValue

    For example:

    if (SomeProperty.HasValue)
    {
        // Do Something
    }
    else
    {
        // Do Something Else
    }
    

    FYI

    public Nullable<System.Guid> SomeProperty { get; set; }
    

    is equivalent to:

    public System.Guid? SomeProperty { get; set; }
    

    The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx

    How to set the maxAllowedContentLength to 500MB while running on IIS7?

    IIS v10 (but this should be the same also for IIS 7.x)

    Quick addition for people which are looking for respective max values

    Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

    Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

    web.config

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.web>
        <!-- ~ 2GB -->
        <httpRuntime maxRequestLength="2147483647" />
      </system.web>
      <system.webServer>
        <security>
          <requestFiltering>
            <!-- ~ 4GB -->
            <requestLimits maxAllowedContentLength="4294967295" />
          </requestFiltering>
        </security>
      </system.webServer>
    </configuration>
    

    npm check and update package if needed

    npm outdated will identify packages that should be updated, and npm update <package name> can be used to update each package. But prior to [email protected], npm update <package name> will not update the versions in your package.json which is an issue.

    The best workflow is to:

    1. Identify out of date packages
    2. Update the versions in your package.json
    3. Run npm update to install the latest versions of each package

    Check out npm-check-updates to help with this workflow.

    • Install npm-check-updates
    • Run npm-check-updates to list what packages are out of date (basically the same thing as running npm outdated)
    • Run npm-check-updates -u to update all the versions in your package.json (this is the magic sauce)
    • Run npm update as usual to install the new versions of your packages based on the updated package.json

    Cannot hide status bar in iOS7

    In Info Plist file Add a row for following property

    Property Name : View controller-based status bar appearance

    Value : NO

    What is the difference between static func and class func in Swift?

    Is it simply that static is for static functions of structs and enums, and class for classes and protocols?

    That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.

    Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.

    From Chris Lattner on this topic:

    We considered unifying the syntax (e.g. using "type" as the keyword), but that doesn't actually simply things. The keywords "class" and "static" are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose "class"), but on balance it is the right tradeoff.

    And here's a snippet that shows some of the override behavior of class functions:

    class MyClass {
        class func myFunc() {
            println("myClass")
        }
    }
    
    class MyOtherClass: MyClass {
        override class func myFunc() {
            println("myOtherClass")
        }
    }
    
    var x: MyClass = MyOtherClass()
    x.dynamicType.myFunc() //myOtherClass
    x = MyClass()
    x.dynamicType.myFunc() //myClass
    

    Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

    From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

    The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

    If this issue is causing serious problems, here are a few things I would suggest:

    • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

    • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

    • Try the JDK early releases as they come out. One of them might fix your problem.

    Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

    Use css gradient over background image

    _x000D_
    _x000D_
    #multiple-background{_x000D_
     box-sizing: border-box;_x000D_
     width: 123px;_x000D_
     height: 30px;_x000D_
     font-size: 12pt;_x000D_
     border-radius: 7px;  _x000D_
     background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
     background-repeat: no-repeat, repeat;_x000D_
     background-position: 5px center, 0px 0px;_x000D_
        background-size: 18px 18px, 100% 100%;_x000D_
     color: white; _x000D_
     border: 1px solid #e4f6df;_x000D_
     box-shadow: .25px .25px .5px .5px black;_x000D_
     padding: 3px 10px 0px 5px;_x000D_
     text-align: right;_x000D_
     }
    _x000D_
    <div id="multiple-background"> Completed </div>
    _x000D_
    _x000D_
    _x000D_

    Android Studio Stuck at Gradle Download on create new project

    What worked for me:

    1. Create a dummy project, when it gets stuck on the Build screen, kill the studio process.
    2. Open the android studio and open the project, the projet will be broken
    3. Create a new project with the dummy project already opened it will create the project without problems
    4. Close the dummy project and have fun

    Where do you include the jQuery library from? Google JSAPI? CDN?

    I just include the latest version from the jQuery site: http://code.jquery.com/jquery-latest.pack.js It suits my needs and I never have to worry about updating.

    EDIT:For a major web app, certainly control it; download it and serve it yourself. But for my personal site, I could not care less. Things don't magically disappear, they are usually deprecated first. I keep up with it enough to know what to change for future releases.

    How to set ChartJS Y axis title?

    Consider using a the transform: rotate(-90deg) style on an element. See http://www.w3schools.com/cssref/css3_pr_transform.asp

    Example, In your css

    .verticaltext_content {
      position: relative;
      transform: rotate(-90deg);
      right:90px;   //These three positions need adjusting
      bottom:150px; //based on your actual chart size
      width:200px;
    }
    

    Add a space fudge factor to the Y Axis scale so the text has room to render in your javascript.

    scaleLabel: "      <%=value%>"
    

    Then in your html after your chart canvas put something like...

    <div class="text-center verticaltext_content">Y Axis Label</div>
    

    It is not the most elegant solution, but worked well when I had a few layers between the html and the chart code (using angular-chart and not wanting to change any source code).

    How to load GIF image in Swift?

    You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to

    import JellyGif
    
    let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    
    //Animates Gif from the main bundle
    imageView.startGif(with: .name("Gif name"))
    
    //Animates Gif with a local path
    let url = URL(string: "Gif path")!
    imageView.startGif(with: .localPath(url))
    
    //Animates Gif with data
    imageView.startGif(with: .data(Data))
    

    For more information you can look at its README

    What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

    use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.

    <%
    String contextPath = request.getContextPath();
    %>
    out.println(contextPath);
    

    output: willPrintMyProjectcontextPath

    Get first day of week in SQL Server

    I don't have any issues with any of the answers given here, however I do think mine is a lot simpler to implement, and understand. I have not run any performance tests on it, but it should be neglegable.

    So I derived my answer from the fact that dates are stored in SQL server as integers, (I am talking about the date component only). If you don't believe me, try this SELECT CONVERT(INT, GETDATE()), and vice versa.

    Now knowing this, you can do some cool math equations. You might be able to come up with a better one, but here is mine.

    /*
    TAKEN FROM http://msdn.microsoft.com/en-us/library/ms181598.aspx
    First day of the week is
    1 -- Monday
    2 -- Tuesday
    3 -- Wednesday
    4 -- Thursday
    5 -- Friday
    6 -- Saturday
    7 (default, U.S. English) -- Sunday
    */
    
    --Offset is required to compensate for the fact that my @@DATEFIRST setting is 7, the default. 
    DECLARE @offSet int, @testDate datetime
    SELECT @offSet = 1, @testDate = GETDATE()
    
    SELECT CONVERT(DATETIME, CONVERT(INT, @testDate) - (DATEPART(WEEKDAY, @testDate) - @offSet))
    

    document.all vs. document.getElementById

    document.querySelectorAll (and its document.querySelector() variant that returns the first found element) is much, much more powerful. You can easily:

    • get an entire collection with document.querySelectorAll("*"), effectively emulating non-standard document.all property;
    • use document.querySelector("#your-id"), effectively emulating document.getElementById() function;
    • use document.querySelectorAll(".your-class"), effectively emulating document.getElementsByClassName() function;
    • use document.querySelectorAll("form") instead of document.forms, and document.querySelectorAll("a") instead of document.links;
    • and perform any much more complex DOM querying (using any available CSS selector) that just cannot be covered with other document builtins.

    Unified querying API is the way to go. Even if document.all would be in the standard, it's just inconvenient.

    How can I keep my branch up to date with master with git?

    If your branch is local only and hasn't been pushed to the server, use

    git rebase master
    

    Otherwise, use

    git merge master
    

    Import a file from a subdirectory?

    You can try inserting it in sys.path:

    sys.path.insert(0, './lib')
    import BoxTime
    

    Multiple try codes in one block

    You could try a for loop

    
    for func,args,kwargs in zip([a,b,c,d], 
                                [args_a,args_b,args_c,args_d],
                                [kw_a,kw_b,kw_c,kw_d]):
        try:
           func(*args, **kwargs)
           break
        except:
           pass
    

    This way you can loop as many functions as you want without making the code look ugly

    How to format current time using a yyyyMMddHHmmss format?

    Use

    fmt.Println(t.Format("20060102150405"))
    

    as Go uses following constants to format date,refer here

    const (
        stdLongMonth      = "January"
        stdMonth          = "Jan"
        stdNumMonth       = "1"
        stdZeroMonth      = "01"
        stdLongWeekDay    = "Monday"
        stdWeekDay        = "Mon"
        stdDay            = "2"
        stdUnderDay       = "_2"
        stdZeroDay        = "02"
        stdHour           = "15"
        stdHour12         = "3"
        stdZeroHour12     = "03"
        stdMinute         = "4"
        stdZeroMinute     = "04"
        stdSecond         = "5"
        stdZeroSecond     = "05"
        stdLongYear       = "2006"
        stdYear           = "06"
        stdPM             = "PM"
        stdpm             = "pm"
        stdTZ             = "MST"
        stdISO8601TZ      = "Z0700"  // prints Z for UTC
        stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
        stdNumTZ          = "-0700"  // always numeric
        stdNumShortTZ     = "-07"    // always numeric
        stdNumColonTZ     = "-07:00" // always numeric
    )
    

    Escape string for use in Javascript regex

    Short 'n Sweet

    function escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
    }
    

    Example

    escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
    
    >>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
    

    (NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

    Install

    Available on npm as escape-string-regexp

    npm install --save escape-string-regexp
    

    Note

    See MDN: Javascript Guide: Regular Expressions

    Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

    .

    .

    .

    .

    Test Case: A typical url

    escapeRegExp("/path/to/resource.html?search=query");
    
    >>> "\/path\/to\/resource\.html\?search=query"
    

    The Long Answer

    If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

    var escapeRegExp;
    
    (function () {
      // Referring to the table here:
      // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
      // these characters should be escaped
      // \ ^ $ * + ? . ( ) | { } [ ]
      // These characters only have special meaning inside of brackets
      // they do not need to be escaped, but they MAY be escaped
      // without any adverse effects (to the best of my knowledge and casual testing)
      // : ! , = 
      // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
    
      var specials = [
            // order matters for these
              "-"
            , "["
            , "]"
            // order doesn't matter for any of these
            , "/"
            , "{"
            , "}"
            , "("
            , ")"
            , "*"
            , "+"
            , "?"
            , "."
            , "\\"
            , "^"
            , "$"
            , "|"
          ]
    
          // I choose to escape every character with '\'
          // even though only some strictly require it when inside of []
        , regex = RegExp('[' + specials.join('\\') + ']', 'g')
        ;
    
      escapeRegExp = function (str) {
        return str.replace(regex, "\\$&");
      };
    
      // test escapeRegExp("/path/to/res?search=this.that")
    }());
    

    How to log in to phpMyAdmin with WAMP, what is the username and password?

    I installed Bitnami WAMP Stack 7.1.29-0 and it asked for a password during installation. In this case it was

    username: root
    password: <password set by you during install>
    

    Open File in Another Directory (Python)

    from pathlib import Path
    
    data_folder = Path("source_data/text_files/")
    file_to_open = data_folder / "raw_data.txt"
    
    f = open(file_to_open)
    print(f.read())
    

    how to always round up to the next integer

    This will also work:

    c = (count - 1) / 10 + 1;
    

    File Upload without Form

    You can use FormData to submit your data by a POST request. Here is a simple example:

    var myFormData = new FormData();
    myFormData.append('pictureFile', pictureInput.files[0]);
    
    $.ajax({
      url: 'upload.php',
      type: 'POST',
      processData: false, // important
      contentType: false, // important
      dataType : 'json',
      data: myFormData
    });
    

    You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).

    find if an integer exists in a list of integers

    The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

    List<int> ints = new List<int>( new[] {1,5,7}); // 1
    

    List<int> intlist=new List<int>() { 0,2,3,4,1}; // 2
    

    var i = 5;
    var x = ints.Contains(i);   // return true or false
    

    Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

    I did it by passing the cookie through the HttpContext:

    HttpContext localContext = new BasicHttpContext();
    
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    response = client.execute(httppost, localContext);
    

    How can I reverse a NSArray in Objective-C?

    As for me, have you considered how the array was populated in the first place? I was in the process of adding MANY objects to an array, and decided to insert each one at the beginning, pushing any existing objects up by one. Requires a mutable array, in this case.

    NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
    [myMutableArray insertObject:aNewObject atIndex:0];
    

    IIS - can't access page by ip address instead of localhost

    Try with disabling Windows Firewall, it worked for me, but in my case, I was able to access IIS through 127.0.0.1

    How do you convert a DataTable into a generic list?

    DataTable dt;   // datatable should contains datacolumns with Id,Name
    
    List<Employee> employeeList=new List<Employee>();  // Employee should contain  EmployeeId, EmployeeName as properties
    
    foreach (DataRow dr in dt.Rows)
    {
        employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});
    }
    

    jQuery How to Get Element's Margin and Padding?

    This works for me:

    var tP = $("img").css("padding").split(" ");
    var Padding = {
        Top: tP[0] != null ? parseInt(tP[0]) : 0,
        Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
        Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
        Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
    };
    

    Result example:

    Object {Top: 5, Right: 8, Bottom: 5, Left: 8}
    

    To make a total:

    var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
    

    How do I convert this list of dictionaries to a csv file?

    import csv
    toCSV = [{'name':'bob','age':25,'weight':200},
             {'name':'jim','age':31,'weight':180}]
    keys = toCSV[0].keys()
    with open('people.csv', 'w', newline='')  as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()
        dict_writer.writerows(toCSV)
    

    EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

    How to generate a Dockerfile from an image?

    Update Dec 2018 to BMW's answer

    chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

    docker pull chenzj/dfimage
    alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
    dfimage IMAGE_ID > Dockerfile
    

    Vue equivalent of setTimeout?

    Arrow Function

    The best and simplest way to solve this problem is by using an arrow function () => {}:

        addToBasket() {
            var item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            // now 'this' is referencing the Vue object and not the 'setTimeout' scope
            setTimeout(() => this.basketAddSuccess = false, 2000);
        }
    

    This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

    Argument Passing

    Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

        addToBasket() {
            item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            //Add scope argument to func, pass this after delay in setTimeout
            setTimeout(function(scope) {
                 scope.basketAddSuccess = false;
            }, 2000, this);
        }
    

    (It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

    Local Variable

    Another possible, but less eloquent and less encouraged, way is to bind this to a var outside of setTimeout:

        addToBasket() {
            item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            //Declare self, which is accessible inside setTimeout func
            var self = this;
            setTimeout(function() {
                 self.basketAddSuccess = false;
            }, 2000);
        }
    

    Using an arrow function would eliminate the need for this extra variable entirely however, and really should be used unless something else is preventing its use.

    What is "pass-through authentication" in IIS 7?

    Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

    With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

    If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

    The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

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

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

    Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

    If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

    Dictionary<string, ArrayList> result = target.GetComponents()
                                          .ToDictionary(x => x.Key, x => x.Value);
    

    There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

    Create a new txt file using VB.NET

    Here is a single line that will create (or overwrite) the file:

    File.Create("C:\my files\2010\SomeFileName.txt").Dispose()
    

    Note: calling Dispose() ensures that the reference to the file is closed.

    PHP convert date format dd/mm/yyyy => yyyy-mm-dd

    Do this:

    date('Y-m-d', strtotime('dd/mm/yyyy'));
    

    But make sure 'dd/mm/yyyy' is the actual date.

    PLS-00201 - identifier must be declared

    The procedure name should be in caps while creating procedure in database. You may use small letters for your procedure name while calling from Java class like:

    String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";
    

    In database the name of procedure should be:

    GETDBUSERBYUSERID    -- (all letters in caps only)
    

    This serves as one of the solutions for this problem.

    String's Maximum length in Java - calling length() method

    Since arrays must be indexed with integers, the maximum length of an array is Integer.MAX_INT (231-1, or 2 147 483 647). This is assuming you have enough memory to hold an array of that size, of course.

    Laravel migration default value

    Might be a little too late to the party, but hope this helps someone with similar issue.

    The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

    Let me illustrate with an example.

    This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

    $book = new Book();
    

    Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

    $book->author = 'Test'
    $book->title = 'Test'
    

    This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

    $book->save();
    

    And thus, the default value will not pop up before you save it to the database.

    But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

    So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

    Book::find($book->id);
    

    Or, a more sophisticated way by refreshing the instance

    $book->refresh();
    

    And then, the next time you try to access the object, it will be filled with the default values.

    Convert string to List<string> in one line?

    string given="Welcome To Programming";
    List<string> listItem= given.Split(' ').ToList();//Split according to space in the string and added into the list
    

    output:

    Welcome
    
    To 
    
    Programming
    

    Loop through checkboxes and count each one checked or unchecked

    Using Selectors

    You can get all checked checkboxes like this:

    var boxes = $(":checkbox:checked");
    

    And all non-checked like this:

    var nboxes = $(":checkbox:not(:checked)");
    

    You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

    Serialize

    jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

    single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2
    

    This will enable you to keep the information for which elements were checked as well.

    Radio/checkbox alignment in HTML/CSS

    I think I have finally solved the problem. One commonly recommended solution is to use vertical-align: middle:

    <input type="radio" style="vertical-align: middle"> Label
    

    The problem, however, is that this still produces visible misalignments even though it should theoretically work. The CSS2 specification says that:

    vertical-align: middle: Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

    So it should be in the perfect centre (the x-height is the height of the character x). However, the problem seems to be caused by the fact browsers commonly add some random uneven margins to radio buttons and checkboxes. One can check, for instance in Firefox using Firebug, that the default checkbox margin in Firefox is 3px 3px 0px 5px. I'm not sure where it comes from, but the other browsers seem to have similar margins as well. So to get a perfect alignment, one needs to get rid of these margins:

    <input type="radio" style="vertical-align: middle; margin: 0px;"> Label
    

    It is still interesting to note that in the table based solution the margins are somehow eaten and everything aligns nicely.

    load json into variable

    code bit should read:

    var my_json;
    $.getJSON(my_url, function(json) {
      my_json = json;
    });
    

    Running code after Spring Boot starts

    Try this one and it will run your code when the application context has fully started.

     @Component
    public class OnStartServer implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent arg0) {
                    // EXECUTE YOUR CODE HERE 
        }
    }
    

    What are 'get' and 'set' in Swift?

    You should look at Computed Properties

    In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

    When you use that property like this:

    var cp = myClass.perimeter
    

    you are invoking the code contained in the get code block, and when you use it like this:

    myClass.perimeter = 5.0
    

    you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

    Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

    How to upgrade scikit-learn package in anaconda

    Following Worked for me for scikit-learn on Anaconda-Jupyter Notebook.

    Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

    Run the following commands in the terminal:

    First, check existing available packages with versions by using:

    conda list    
    

    It will show different packages and their installed versions in the output. Here check for scikit-learn. e.g. for me, the output was:

    scikit-learn              0.19.1           py36hedc7406_0  
    

    Now I want to Upgrade to 0.19.2 July 2018 release i.e. latest available version.

    conda config --append channels conda-forge
    conda install scikit-learn=0.19.2
    

    As you are trying to upgrade to 0.17 version try the following command:

    conda install scikit-learn=0.17
    

    Now check the required version of the scikit-learn is installed correctly or not by using:

    conda list 
    

    For me the Output was:

    scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge
    

    Note: Don't use pip command if you are using Anaconda or Miniconda

    I tried following commands:

    !conda update conda 
    !pip install -U scikit-learn
    

    It will install the required packages also will show in the conda list but if you try to import that package it will not work.

    On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

    How to configure PHP to send e-mail?

    Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

    Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

    Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer

    How to compare arrays in JavaScript?

    Even though this has a lot of answers, one that I believe to be of help:

    const newArray = [ ...new Set( [...arr1, ...arr2] ) ]
    

    It is not stated in the question how the structure of the array is going to look like, so If you know for sure that you won't have nested arrays nor objects in you array (it happened to me, that's why I came to this answer) the above code will work.

    What happens is that we use spread operator ( ... ) to concat both arrays, then we use Set to eliminate any duplicates. Once you have that you can compare their sizes, if all three arrays have the same size you are good to go.

    This answer also ignores the order of elements, as I said, the exact situation happened to me, so maybe someone in the same situation might end up here (as I did).


    Edit1.

    Answering Dmitry Grinko's question: "Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work"

    Consider this code:

    const arr1 = [ 'a', 'b' ]
    const arr2 = [ 'a', 'b', 'c' ]
    const newArray = [ new Set( [...arr1, ...arr2] ) ]
    console.log(newArray)
    

    You'll get

    [ Set { 'a', 'b', 'c' } ]
    

    In order to work with that value you'd need to use some Set properties (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). On the other hand, when you use this code:

    const arr1 = [ 'a', 'b' ]
    const arr2 = [ 'a', 'b', 'c' ]
    const newArray = [ ...new Set( [...arr1, ...arr2] ) ]
    console.log(newArray)
    

    You'll get

    [ 'a', 'b', 'c' ]
    

    That's the difference, the former would give me a Set, it would work too as I could get the size of that Set, but the latter gives me the array I need, what's more direct to the resolution.

    Why is there no ForEach extension method on IEnumerable?

    No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.

    Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.

    1 = false and 0 = true?

    I'm not sure if I'm answering the question right, but here's a familiar example:

    The return type of GetLastError() in Windows is nonzero if there was an error, or zero otherwise. The reverse is usually true of the return value of the function you called.

    Responsive design with media query : screen size?

    Take a look at this... http://getbootstrap.com/

    For big websites I use Bootstrap and sometimes (for simple websites) I create all the style with some @mediaqueries. It's very simple, just think all the code in percentage.

    .container {
    max-width: 1200px;
    width: 100%;
    margin: 0 auto;
    }
    

    Inside the container, your structure must have widths in percentage like this...

    .col-1 {
    width: 40%;
    float: left;
    }
    
    .col-2 {
    width: 60%;
    float: left;
    }
    
    @media screen and (max-width: 320px) {
    .col-1, .col-2 { width: 100%; }
    }
    

    In some simple interfaces, if you start to develop the project in this way, you will have great chances to have a fully responsive site using break points only to adjust the flow of objects.

    .NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

    .NET data structures:

    More to conversation about why ArrayList and List are actually different

    Arrays

    As one user states, Arrays are the "old school" collection (yes, arrays are considered a collection though not part of System.Collections). But, what is "old school" about arrays in comparison to other collections, i.e the ones you have listed in your title (here, ArrayList and List(Of T))? Let's start with the basics by looking at Arrays.

    To start, Arrays in Microsoft .NET are, "mechanisms that allow you to treat several [logically-related] items as a single collection," (see linked article). What does that mean? Arrays store individual members (elements) sequentially, one after the other in memory with a starting address. By using the array, we can easily access the sequentially stored elements beginning at that address.

    Beyond that and contrary to programming 101 common conceptions, Arrays really can be quite complex:

    Arrays can be single dimension, multidimensional, or jadded (jagged arrays are worth reading about). Arrays themselves are not dynamic: once initialized, an array of n size reserves enough space to hold n number of objects. The number of elements in the array cannot grow or shrink. Dim _array As Int32() = New Int32(100) reserves enough space on the memory block for the array to contain 100 Int32 primitive type objects (in this case, the array is initialized to contain 0s). The address of this block is returned to _array.

    According to the article, Common Language Specification (CLS) requires that all arrays be zero-based. Arrays in .NET support non-zero-based arrays; however, this is less common. As a result of the "common-ness" of zero-based arrays, Microsoft has spent a lot of time optimizing their performance; therefore, single dimension, zero-based (SZs) arrays are "special" - and really the best implementation of an array (as opposed to multidimensional, etc.) - because SZs have specific intermediary language instructions for manipulating them.

    Arrays are always passed by reference (as a memory address) - an important piece of the Array puzzle to know. While they do bounds checking (will throw an error), bounds checking can also be disabled on arrays.

    Again, the biggest hindrance to arrays is that they are not re-sizable. They have a "fixed" capacity. Introducing ArrayList and List(Of T) to our history:

    ArrayList - non-generic list

    The ArrayList (along with List(Of T) - though there are some critical differences, here, explained later) - is perhaps best thought of as the next addition to collections (in the broad sense). ArrayList inherit from the IList (a descendant of 'ICollection') interface. ArrayLists, themselves, are bulkier - requiring more overhead - than Lists.

    IList does enable the implementation to treat ArrayLists as fixed-sized lists (like Arrays); however, beyond the additional functionallity added by ArrayLists, there are no real advantages to using ArrayLists that are fixed size as ArrayLists (over Arrays) in this case are markedly slower.

    From my reading, ArrayLists cannot be jagged: "Using multidimensional arrays as elements... is not supported". Again, another nail in the coffin of ArrayLists. ArrayLists are also not "typed" - meaning that, underneath everything, an ArrayList is simply a dynamic Array of Objects: Object[]. This requires a lot of boxing (implicit) and unboxing (explicit) when implementing ArrayLists, again adding to their overhead.

    Unsubstantiated thought: I think I remember either reading or having heard from one of my professors that ArrayLists are sort of the bastard conceptual child of the attempt to move from Arrays to List-type Collections, i.e. while once having been a great improvement to Arrays, they are no longer the best option as further development has been done with respect to collections

    List(Of T): What ArrayList became (and hoped to be)

    The difference in memory usage is significant enough to where a List(Of Int32) consumed 56% less memory than an ArrayList containing the same primitive type (8 MB vs. 19 MB in the above gentleman's linked demonstration: again, linked here) - though this is a result compounded by the 64-bit machine. This difference really demonstrates two things: first (1), a boxed Int32-type "object" (ArrayList) is much bigger than a pure Int32 primitive type (List); second (2), the difference is exponential as a result of the inner-workings of a 64-bit machine.

    So, what's the difference and what is a List(Of T)? MSDN defines a List(Of T) as, "... a strongly typed list of objects that can be accessed by index." The importance here is the "strongly typed" bit: a List(Of T) 'recognizes' types and stores the objects as their type. So, an Int32 is stored as an Int32 and not an Object type. This eliminates the issues caused by boxing and unboxing.

    MSDN specifies this difference only comes into play when storing primitive types and not reference types. Too, the difference really occurs on a large scale: over 500 elements. What's more interesting is that the MSDN documentation reads, "It is to your advantage to use the type-specific implementation of the List(Of T) class instead of using the ArrayList class...."

    Essentially, List(Of T) is ArrayList, but better. It is the "generic equivalent" of ArrayList. Like ArrayList, it is not guaranteed to be sorted until sorted (go figure). List(Of T) also has some added functionality.

    The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

    This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:

    xmlns:tx="http://www.springframework.org/schema/tx"
    

    xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

    , by mistake wrong configuration which others may have

    xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
    

    i.e., extra "/spring-tx-3.1.xsd"

    xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

    in other words what is there in xmlns(namespace) should have proper mapping in schemaLocation (namespace vs schema).

    namespace here is : http://www.springframework.org/schema/tx

    schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

    this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config

    How to float 3 divs side by side using CSS?

    <style>
    .left-column
    {
    float:left;
    width:30%;
    background-color:red;
    }
    .right-column
    {
    float:right;
    width:30%;
    background-color:green;
    }
    .center-column
    {
    margin:auto;
    width:30%;
    background-color:blue;
    }
    </style>
    
    <div id="container">
    <section class="left-column">THIS IS COLUMN 1 LEFT</section>
    <section class="right-column">THIS IS COLUMN 3 RIGHT</section>
    <section class="center-column">THIS IS COLUMN 2 CENTER</section>
    </div>
    

    the advantage of this way is you can set each column width independant of the other as long as you keep it under 100%, if you use 3 x 30% the remaining 10% is split as a 5% divider space between the collumns

    Creating an empty list in Python

    Here is how you can test which piece of code is faster:

    % python -mtimeit  "l=[]"
    10000000 loops, best of 3: 0.0711 usec per loop
    
    % python -mtimeit  "l=list()"
    1000000 loops, best of 3: 0.297 usec per loop
    

    However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.

    Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.

    Passing string parameter in JavaScript function

    The question has been answered, but for your future coding reference you might like to consider this.

    In your HTML, add the name as an attribute to the button and remove the onclick reference.

    <button id="button" data-name="Mathew" type="button">click</button>
    

    In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.

    var button = document.getElementById('button');
    
    button.onclick = myfunction;
    
    function myfunction() {
      var name = this.getAttribute('data-name');
      alert(name);
    }
    

    DEMO

    'System.OutOfMemoryException' was thrown when there is still plenty of memory free

    You may want to read this: "“Out Of Memory” Does Not Refer to Physical Memory" by Eric Lippert.

    In short, and very simplified, "Out of memory" does not really mean that the amount of available memory is too small. The most common reason is that within the current address space, there is no contiguous portion of memory that is large enough to serve the wanted allocation. If you have 100 blocks, each 4 MB large, that is not going to help you when you need one 5 MB block.

    Key Points:

    • the data storage that we call “process memory” is in my opinion best visualized as a massive file on disk.
    • RAM can be seen as merely a performance optimization
    • Total amount of virtual memory your program consumes is really not hugely relevant to its performance
    • "running out of RAM" seldom results in an “out of memory” error. Instead of an error, it results in bad performance because the full cost of the fact that storage is actually on disk suddenly becomes relevant.

    How to trigger a click on a link using jQuery

    Well you have to setup the click event first then you can trigger it and see what happens:

    //good habits first let's cache our selector
    var $myLink = $('#titleee').find('a');
    $myLink.click(function (evt) {
      evt.preventDefault();
      alert($(this).attr('href'));
    });
    
    // now the manual trigger
    $myLink.trigger('click');
    

    How are people unit testing with Entity Framework 6, should you bother?

    It is important to test what you are expecting entity framework to do (i.e. validate your expectations). One way to do this that I have used successfully, is using moq as shown in this example (to long to copy into this answer):

    https://docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking

    However be careful... A SQL context is not guaranteed to return things in a specific order unless you have an appropriate "OrderBy" in your linq query, so its possible to write things that pass when you test using an in-memory list (linq-to-entities) but fail in your uat / live environment when (linq-to-sql) gets used.

    What is the difference between match_parent and fill_parent?

    fill_parent: The view should be as big as its parent.

    now this content fill_parent is deprecated and replaced by match_parent.

    Remove a child with a specific attribute, in SimpleXML for PHP

    If you extend the base SimpleXMLElement class, you can use this method:

    class MyXML extends SimpleXMLElement {
    
        public function find($xpath) {
            $tmp = $this->xpath($xpath);
            return isset($tmp[0])? $tmp[0]: null;
        }
    
        public function remove() {
            $dom = dom_import_simplexml($this);
            return $dom->parentNode->removeChild($dom);
        }
    
    }
    
    // Example: removing the <bar> element with id = 1
    $foo = new MyXML('<foo><bar id="1"/><bar id="2"/></foo>');
    $foo->find('//bar[@id="1"]')->remove();
    print $foo->asXML(); // <foo><bar id="2"/></foo>
    

    TypeError: Converting circular structure to JSON in nodejs

    Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account

    https://www.npmjs.com/package/circular-json

    You can stringify your circular structure by doing:

    const str = CircularJSON.stringify(obj);
    

    then you can convert it onto JSON using JSON parser

    JSON.parse(str)
    

    How to properly assert that an exception gets raised in pytest?

    Better practice will be using a class that inherit unittest.TestCase and running self.assertRaises.

    For example:

    import unittest
    
    
    def whatever():
        return 9/0
    
    
    class TestWhatEver(unittest.TestCase):
    
        def test_whatever():
            with self.assertRaises(ZeroDivisionError):
                whatever()
    

    Then you would execute it by running:

    pytest -vs test_path
    

    How to add scroll bar to the Relative Layout?

    You want to enclose it with a scrollView.

    How can I show and hide elements based on selected option with jQuery?

    To show the div while selecting one value and hide while selecting another value from dropdown box: -

     $('#yourselectorid').bind('change', function(event) {
    
               var i= $('#yourselectorid').val();
    
                if(i=="sometext") // equal to a selection option
                 {
                     $('#divid').show();
                 }
               elseif(i=="othertext")
                 {
                   $('#divid').hide(); // hide the first one
                   $('#divid2').show(); // show the other one
    
                  }
    });
    

    Checking length of dictionary object

    This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

    Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.

    I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

    Edit #1: Why can't you just do this?

    list = [ {name:'john'}, {name:'bob'} ];
    

    Then iterate over list? The length is already set.

    How to reset a timer in C#?

    Other alternative way to reset the windows.timer is using the counter, as follows:

    int timerCtr = 0;
    Timer mTimer;
    
    private void ResetTimer() => timerCtr = 0;
    private void mTimer_Tick()
    {
        timerCtr++;
        // Perform task
    }  
    

    So if you intend to repeat every 1 second, you can set the timer interval at 100ms, and test the counter to 10 cycles.

    This is suitable if the timer should wait for some processes those may be ended at the different time span.

    Scrolling to element using webdriver?

    There is another option to scroll page to required element if element has "id" attribute

    If you want to navigate to page and scroll down to element with @id, it can be done automatically by adding #element_id to URL...

    Example

    Let's say we need to navigate to Selenium Waits documentation and scroll page down to "Implicit Wait" section. We can do

    driver.get('https://selenium-python.readthedocs.io/waits.html')
    

    and add code for scrolling...OR use

    driver.get('https://selenium-python.readthedocs.io/waits.html#implicit-waits')
    

    to navigate to page AND scroll page automatically to element with id="implicit-waits" (<div class="section" id="implicit-waits">...</div>)

    How to coerce a list object to type 'double'

    You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.

    as.numeric(a[[1]])

    LISTAGG in Oracle to return distinct values

    One annoying aspect with LISTAGG is that if the total length of concatenated string exceeds 4000 characters( limit for VARCHAR2 in SQL ), the below error is thrown, which is difficult to manage in Oracle versions upto 12.1

    ORA-01489: result of string concatenation is too long

    A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

    SELECT pid, LISTAGG(Desc, ' ' on overflow truncate) WITHIN GROUP (ORDER BY seq) AS desc
    FROM B GROUP BY pid;
    

    The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

    These are some of the additional options of ON OVERFLOW clause:

    • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
    • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
    • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
    • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

    How to select first and last TD in a row?

    If the row contains some leading (or trailing) th tags before the td you should use the :first-of-type and the :last-of-type selectors. Otherwise the first td won't be selected if it's not the first element of the row.

    This gives:

    td:first-of-type, td:last-of-type {
        /* styles */
    }
    

    Parse error: syntax error, unexpected [

    Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

    How to hide a mobile browser's address bar?

    In my case problem was in css and html layout. Layout was something like html - body - root - ... html and body was overflow: hidden, and root was position: fixed, height: 100vh.

    Whith this layout browser tabs on mobile doesnt hide. For solve this I delete overflow: hidden from html and body and delete position: fixed, height: 100vh from root.

    Getting an Embedded YouTube Video to Auto Play and Loop

    Playlist hack didn't work for me either. Working workaround for September 2018 (bonus: set width and height by CSS for #yt-wrap instead of hard-coding it in JS):

    <div id="yt-wrap">
        <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="ytplayer"></div>
    </div>
    
    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubePlayerAPIReady() {
        player = new YT.Player('ytplayer', {
          width: '100%',
          height: '100%',
          videoId: 'VIDEO_ID',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
    
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
        player.mute(); // comment out if you don't want the auto played video muted
      }
    
      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.ENDED) {
          player.seekTo(0);
          player.playVideo();
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
    

    Plot two histograms on single chart with matplotlib

    Plotting two overlapping histograms (or more) can lead to a rather cluttered plot. I find that using step histograms (aka hollow histograms) improves the readability quite a bit. The only downside is that in matplotlib the default legend for a step histogram is not properly formatted, so it can be edited like in the following example:

    import numpy as np                   # v 1.19.2
    import matplotlib.pyplot as plt      # v 3.3.2
    from matplotlib.lines import Line2D
    
    rng = np.random.default_rng(seed=123)
    
    # Create two normally distributed random variables of different sizes
    # and with different shapes
    data1 = rng.normal(loc=30, scale=10, size=500)
    data2 = rng.normal(loc=50, scale=10, size=1000)
    
    # Create figure with 'step' type of histogram to improve plot readability
    fig, ax = plt.subplots(figsize=(9,5))
    ax.hist([data1, data2], bins=15, histtype='step', linewidth=2,
            alpha=0.7, label=['data1','data2'])
    
    # Edit legend to get lines as legend keys instead of the default polygons
    # and sort the legend entries in alphanumeric order
    handles, labels = ax.get_legend_handles_labels()
    leg_entries = {}
    for h, label in zip(handles, labels):
        leg_entries[label] = Line2D([0], [0], color=h.get_facecolor()[:-1],
                                    alpha=h.get_alpha(), lw=h.get_linewidth())
    labels_sorted, lines = zip(*sorted(leg_entries.items()))
    ax.legend(lines, labels_sorted, frameon=False)
    
    # Remove spines
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    
    # Add annotations
    plt.ylabel('Frequency', labelpad=15)
    plt.title('Matplotlib step histogram', fontsize=14, pad=20)
    plt.show()
    

    step_hist

    As you can see, the result looks quite clean. This is especially useful when overlapping even more than two histograms. Depending on how the variables are distributed, this can work for up to around 5 overlapping distributions. More than that would require the use of another type of plot, such as one of those presented here.

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

    If you're concerned the number of rows that meet the condition may change in the few milliseconds since execution of the query and retrieval of results, you could/should execute the queries inside a transaction:

    BEGIN TRAN bogus
    
    SELECT COUNT( my_table.my_col ) AS row_count
    FROM my_table
    WHERE my_table.foo = 'bar'
    
    SELECT my_table.my_col
    FROM my_table
    WHERE my_table.foo = 'bar'
    ROLLBACK TRAN bogus
    

    This would return the correct values, always.

    Furthermore, if you're using SQL Server, you can use @@ROWCOUNT to get the number of rows affected by last statement, and redirect the output of real query to a temp table or table variable, so you can return everything altogether, and no need of a transaction:

    DECLARE @dummy INT
    
    SELECT my_table.my_col
    INTO #temp_table
    FROM my_table
    WHERE my_table.foo = 'bar'
    
    SET @dummy=@@ROWCOUNT
    SELECT @dummy, * FROM #temp_table
    

    How to make a movie out of images in python

    Here is a minimal example using moviepy. For me this was the easiest solution.

    import os
    import moviepy.video.io.ImageSequenceClip
    image_folder='folder_with_images'
    fps=1
    
    image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
    clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
    clip.write_videofile('my_video.mp4')
    

    How to get First and Last record from a sql query?

    SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME) 
    UNION
    SELECT <rows> FROM TABLE_NAME WHERE ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)
    

    or

    SELECT * FROM TABLE_NAME WHERE ROWID=(SELECT MIN(ROWID) FROM TABLE_NAME) 
                                OR ROWID=(SELECT MAX(ROWID) FROM TABLE_NAME)
    

    How to hide a <option> in a <select> menu with CSS?

    You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the <option> in a <span> with display: none. FF won't do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.

    EDIT: Oh yeah, I already implemented this in jQuery:

    jQuery.fn.toggleOption = function( show ) {
        jQuery( this ).toggle( show );
        if( show ) {
            if( jQuery( this ).parent( 'span.toggleOption' ).length )
                jQuery( this ).unwrap( );
        } else {
            if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
                jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
        }
    };
    

    EDIT 2: Here's how you would use this function:

    jQuery(selector).toggleOption(true); // show option
    jQuery(selector).toggleOption(false); // hide option
    

    EDIT 3: Added extra check suggested by @user1521986

    How do I check if a list is empty?

    print('not empty' if a else 'empty')
    

    a little more practical:

    a.pop() if a else None
    

    and shertest version:

    if a: a.pop() 
    

    Deciding between HttpClient and WebClient

    I have benchmark between HttpClient, WebClient, HttpWebResponse then call Rest Web Api

    and result Call Rest Web Api Benchmark

    ---------------------Stage 1  ---- 10 Request
    
    {00:00:17.2232544} ====>HttpClinet
    {00:00:04.3108986} ====>WebRequest
    {00:00:04.5436889} ====>WebClient
    
    ---------------------Stage 1  ---- 10 Request--Small Size
    {00:00:17.2232544}====>HttpClinet
    {00:00:04.3108986}====>WebRequest
    {00:00:04.5436889}====>WebClient
    
    ---------------------Stage 3  ---- 10 sync Request--Small Size
    {00:00:15.3047502}====>HttpClinet
    {00:00:03.5505249}====>WebRequest
    {00:00:04.0761359}====>WebClient
    
    ---------------------Stage 4  ---- 100 sync Request--Small Size
    {00:03:23.6268086}====>HttpClinet
    {00:00:47.1406632}====>WebRequest
    {00:01:01.2319499}====>WebClient
    
    ---------------------Stage 5  ---- 10 sync Request--Max Size
    
    {00:00:58.1804677}====>HttpClinet    
    {00:00:58.0710444}====>WebRequest    
    {00:00:38.4170938}====>WebClient
        
    ---------------------Stage 6  ---- 10 sync Request--Max Size
    
    {00:01:04.9964278}====>HttpClinet    
    {00:00:59.1429764}====>WebRequest    
    {00:00:32.0584836}====>WebClient
    

    _____ WebClient Is faster ()

    var stopWatch = new Stopwatch();
            stopWatch.Start();
            for (var i = 0; i < 10; ++i)
            {
                CallGetHttpClient();
                CallPostHttpClient();
            }
    
            stopWatch.Stop();
    
            var httpClientValue = stopWatch.Elapsed;
    
            stopWatch = new Stopwatch();
    
            stopWatch.Start();
            for (var i = 0; i < 10; ++i)
            {
                CallGetWebRequest();
                CallPostWebRequest();
            }
    
            stopWatch.Stop();
    
            var webRequesttValue = stopWatch.Elapsed;
    
    
            stopWatch = new Stopwatch();
    
            stopWatch.Start();
            for (var i = 0; i < 10; ++i)
            {
    
                CallGetWebClient();
                CallPostWebClient();
    
            }
    
            stopWatch.Stop();
    
            var webClientValue = stopWatch.Elapsed;
    

    //-------------------------Functions

    private void CallPostHttpClient()
        {
            var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
            var responseTask = httpClient.PostAsync("PostJson", null);
            responseTask.Wait();
    
            var result = responseTask.Result;
            var readTask = result.Content.ReadAsStringAsync().Result;
    
        }
        private void CallGetHttpClient()
        {
            var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
            var responseTask = httpClient.GetAsync("getjson");
            responseTask.Wait();
    
            var result = responseTask.Result;
            var readTask = result.Content.ReadAsStringAsync().Result;
    
        }
        private string CallGetWebRequest()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://localhost:44354/api/test/getjson");
    
            request.Method = "GET";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    
            var content = string.Empty;
    
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
            }
    
            return content;
        }
        private string CallPostWebRequest()
        {
    
            var apiUrl = "https://localhost:44354/api/test/PostJson";
    
    
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl));
            httpRequest.ContentType = "application/json";
            httpRequest.Method = "POST";
            httpRequest.ContentLength = 0;
    
            using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
            {
                using (Stream stream = httpResponse.GetResponseStream())
                {
                    var json = new StreamReader(stream).ReadToEnd();
                    return json;
                }
            }
    
            return "";
        }
    
        private string CallGetWebClient()
        {
            string apiUrl = "https://localhost:44354/api/test/getjson";
    
    
            var client = new WebClient();
    
            client.Headers["Content-type"] = "application/json";
    
            client.Encoding = Encoding.UTF8;
    
            var json = client.DownloadString(apiUrl);
    
    
            return json;
        }
    
        private string CallPostWebClient()
        {
            string apiUrl = "https://localhost:44354/api/test/PostJson";
    
    
            var client = new WebClient();
    
            client.Headers["Content-type"] = "application/json";
    
            client.Encoding = Encoding.UTF8;
    
            var json = client.UploadString(apiUrl, "");
    
    
            return json;
        }
    

    Get and Set a Single Cookie with Node.js HTTP Server

    You can use the "cookies" npm module, which has a comprehensive set of features.

    Documentation and examples at:
    https://github.com/jed/cookies

    How do I create and read a value from cookie?

    For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.

    cookie = {
    
        set: function (name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else
                var expires = "";
            document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
        },
    
        get : function(name){
            var nameEQ = name + "=",
                ca = document.cookie.split(';');
    
            for(var i=0;i < ca.length;i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) 
                  return  JSON.parse(c.substring(nameEQ.length,c.length));
            }
    
            return null;
        }
    
    }
    

    So, now you can do things like this:

    cookie.set('cookie_key', {foo: 'bar'}, 30);
    
    cookie.get('cookie_key'); // {foo: 'bar'}
    
    cookie.set('cookie_key', 'baz', 30);
    
    cookie.get('cookie_key'); // 'baz'
    

    Jupyter notebook not running code. Stuck on In [*]

    I had the same issue. I found that ipython must be running for jupyter notebook to execute. Do the following:

    • Go to the folder where you have your ipython notebook(.ipynb)
    • Press shift and right click on the empty space then select "open command window here". This will open a command prompt window.
    • Type ipython. This will start ipython.
    • Open another command prompt window and open jupyter notebook.
    • Open your file again and go to cell>>>run cell.

    This should work. It worked for me. Cheers!

    How to programmatically set the SSLContext of a JAX-WS client?

    By combining Radek and l0co's answers you can access the WSDL behind https:

    SSLContext sc = SSLContext.getInstance("TLS");
    
    KeyManagerFactory kmf = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(getClass().getResourceAsStream(keystore),
            password.toCharArray());
    
    kmf.init(ks, password.toCharArray());
    
    sc.init(kmf.getKeyManagers(), null, null);
    
    HttpsURLConnection
            .setDefaultSSLSocketFactory(sc.getSocketFactory());
    
    yourService = new YourService(url); //Handshake should succeed
    

    Loop through an array php

    Using foreach loop without key

    foreach($array as $item) {
        echo $item['filename'];
        echo $item['filepath'];
    
        // to know what's in $item
        echo '<pre>'; var_dump($item);
    }
    

    Using foreach loop with key

    foreach($array as $i => $item) {
        echo $item[$i]['filename'];
        echo $item[$i]['filepath'];
    
        // $array[$i] is same as $item
    }
    

    Using for loop

    for ($i = 0; $i < count($array); $i++) {
        echo $array[$i]['filename'];
        echo $array[$i]['filepath'];
    }
    

    var_dump is a really useful function to get a snapshot of an array or object.

    Open Form2 from Form1, close Form1 from Form2

    if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1

    for example you could add a

    public class Form2 : Form
    {
        Form2(Form1 parentForm):base()
        {
            this.parentForm = parentForm;
        }
    
        Form1 parentForm;
        .....
    }
    

    field and constructor to Form2

    if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2

    How do I generate random numbers in Dart?

    For me the easiest way is to do:

    import 'dart:math';
    Random rnd = new Random();
    r = min + rnd.nextInt(max - min);
    //where min and max should be specified.
    

    Thanks to @adam-singer explanation in here.

    Difference between @Mock and @InjectMocks

    @Mock is used to declare/mock the references of the dependent beans, while @InjectMocks is used to mock the bean for which test is being created.

    For example:

    public class A{
    
       public class B b;
    
       public void doSomething(){
    
       }
    
    }
    

    test for class A:

    public class TestClassA{
    
       @Mocks
       public class B b;
    
       @InjectMocks
       public class A a;
    
       @Test
       public testDoSomething(){
    
       }
    
    }
    

    How to write LDAP query to test if user is member of a group?

    I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

    MySQL Trigger: Delete From Table AFTER DELETE

    create trigger doct_trigger
    after delete on doctor
    for each row
    delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
    

    How to close an iframe within iframe itself

    "Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.

    In IFrame:

    parent.closeIFrame();
    

    In parent:

    function closeIFrame(){
         $('#youriframeid').remove();
    }
    

    How do I supply an initial value to a text field?

    You don't have to define a separate variable in the widget scope, just do it inline:

    TextField(
      controller: TextEditingController()..text = 'Your initial value',
      onChanged: (text) => {},
    )
    

    How to update parent's state in React?

    This the way I do it.

    type ParentProps = {}
    type ParentState = { someValue: number }
    class Parent extends React.Component<ParentProps, ParentState> {
        constructor(props: ParentProps) {
            super(props)
            this.state = { someValue: 0 }
    
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(value: number) {
            this.setState({...this.state, someValue: value})
        }
    
        render() {
            return <div>
                <Child changeFunction={this.handleChange} defaultValue={this.state.someValue} />
                <p>Value: {this.state.someValue}</p>
            </div>
        }
    }
    
    type ChildProps = { defaultValue: number, changeFunction: (value: number) => void}
    type ChildState = { anotherValue: number }
    class Child extends React.Component<ChildProps, ChildState> {
        constructor(props: ChildProps) {
            super(props)
            this.state = { anotherValue: this.props.defaultValue }
    
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(value: number) {
            this.setState({...this.state, anotherValue: value})
            this.props.changeFunction(value)
        }
    
        render() {
            return <div>
                <input onChange={event => this.handleChange(Number(event.target.value))} type='number' value={this.state.anotherValue}/>
            </div>
        }
    }
    

    estimating of testing effort as a percentage of development time

    Are you talking about automated unit/integration tests or manual tests?

    For the former, my rule of thumb (based on measurements) is 40-50% added to development time i.e. if developing a use case takes 10 days (before an QA and serious bugfixing happens), writing good tests takes another 4 to 5 days - though this should best happen before and during development, not afterwards.

    What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

    If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like

    http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6
    

    but as it is two pieces of data I would store them in separate fields

    Sleeping in a batch file

    You could use the Windows cscript WSH layer and this wait.js JavaScript file:

    if (WScript.Arguments.Count() == 1)
        WScript.Sleep(WScript.Arguments(0)*1000);
    else
        WScript.Echo("Usage: cscript wait.js seconds");
    

    What is the difference between npm install and npm run build?

    NPM in 2019

    npm build no longer exists. You must call npm run build now. More info below.

    TLDR;

    npm install: installs dependencies, then calls the install from the package.json scripts field.

    npm run build: runs the build field from the package.json scripts field.


    NPM Scripts Field

    https://docs.npmjs.com/misc/scripts

    There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


    To Complicate Things

    • npm install is not the same as npm run install
    • npm install installs package.json dependencies, then runs the package.json scripts.install
      • (Essentially calls npm run install after dependencies are installed.
    • npm run install only runs the package.json scripts.install, it will not install dependencies.
    • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

    Extra Notes

    There are still two top level commands that will run scripts, they are:

    • npm start which is the same as npm run start
    • npm test ==> npm run test

    How to center absolute div horizontally using CSS?

    You can't use margin:auto; on position:absolute; elements, just remove it if you don't need it, however, if you do, you could use left:30%; ((100%-40%)/2) and media queries for the max and min values:

    .container {
        position: absolute;
        top: 15px;
        left: 30%;
        z-index: 2;
        width:40%;
        height: 60px;
        overflow: hidden;
        background: #fff;
    }
    
    @media all and (min-width:960px) {
    
        .container {
            left: 50%;
            margin-left:-480px;
            width: 960px;
        }
    
    }
    
    @media all and (max-width:600px) {
    
        .container {
            left: 50%;
            margin-left:-300px;
            width: 600px;
        }
    
    }
    

    Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

    I figured it out. The problem was that there were still some pages in the project that hadn't been converted to use "namespaces" as needed in a web application project. I guess I thought that it wouldn't compile if there were still any of those pages around, but if the page didn't reference anything from outside itself it didn't appear to squawk. So when it was saying that it didn't inherit from "System.Web.UI.Page" that was because it couldn't actually find the class "BasePage" at run time because the page itself was not in the WebApplication namespace. I went through all my pages one by one and made sure that they were properly added to the WebApplication namespace and now it not only compiles without issue, it also displays normally. yay!

    what a trial converting from website to web application project can be!

    Can Console.Clear be used to only clear a line instead of whole console?

    To clear from the current position to the end of the current line, do this:

        public static void ClearToEndOfCurrentLine()
        {
            int currentLeft = Console.CursorLeft;
            int currentTop = Console.CursorTop;
            Console.Write(new String(' ', Console.WindowWidth - currentLeft));
            Console.SetCursorPosition(currentLeft, currentTop);
        }
    

    Get the number of rows in a HTML table

    Well it depends on what you have in your table.

    its one of the following If you have only one table

    var count = $('#gvPerformanceResult tr').length;
    

    If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

    var count = $('#gvPerformanceResult>tr').length;
    

    Where by this will work (but is quite frankly overkill.)

    var count = $('#gvPerformanceResult>tbody>tr').length;
    

    jQuery AJAX submit form

    You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.

    AjaxForm:

    $("#theForm").ajaxForm({url: 'server.php', type: 'post'})
    

    or

    $("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
    

    ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.

    Serialize:

    $.get('server.php?' + $('#theForm').serialize())
    
    $.post('server.php', $('#theForm').serialize())
    

    AJAX serialization documentation is here.

    How can I get useful error messages in PHP?

    Errors and warnings usually appear in ....\logs\php_error.log or ....\logs\apache_error.log depending on your php.ini settings.

    Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.

    So "tail -f" your log files and when you get a blank screen use IEs "view" -> "source" menu options to view the raw output.

    Entity Framework - Code First - Can't Store List<String>

    EF Core 2.1+ :

    Property:

    public string[] Strings { get; set; }
    

    OnModelCreating:

    modelBuilder.Entity<YourEntity>()
                .Property(e => e.Strings)
                .HasConversion(
                    v => string.Join(',', v),
                    v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
    

    Update (2021-02-14)

    The PostgreSQL has an array data type and the Npgsql EF Core provider does support that. So it will map your C# arrays and lists to the PostgreSQL array data type automatically and no extra config is required. Also you can operate on the array and the operation will be translated to SQL.

    More information on this page.

    How to get position of a certain element in strings vector, to use it as an index in ints vector?

    I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

    int main(){
    vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
    string req_name;
    cout<<"Enter search name: "<<'\n';
    cin>>req_name;
        for(int i=0; i<=names.size()-1; ++i) {
            if(names[i]==req_name){
                cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
                return 0;
            }
            else if(names[i]!=req_name && i==names.size()-1) {
                cout<<"That name is not an element in this vector"<<'\n';
            } else {
                continue;
            }
        }
    

    Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

    In my case, my get_context_data in one of my views was returning return render(self.request, 'es_connection_error.html', {'error':error}); in a try/catch block instead of returning context