Programs & Examples On #Scenarios

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

*ngIf and *ngFor on same element causing error

<div *ngFor="let thing of show ? stuff : []">
  {{log(thing)}}
  <span>{{thing.name}}</span>
</div>

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid on the parent, grid-area: 1/1/1/1; on the children, and justify-self for positioning of those children.

_x000D_
_x000D_
<div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I find an array item with TypeScript? (a modern, easier way)

If you need some es6 improvements not supported by Typescript, you can target es6 in your tsconfig and use Babel to convert your files in es5.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

This error seems to occur mostly if there is a space before or after your secret key

Use of PUT vs PATCH methods in REST API real life scenarios

To conclude the discussion on the idempotency, I should note that one can define idempotency in the REST context in two ways. Let's first formalize a few things:

A resource is a function with its codomain being the class of strings. In other words, a resource is a subset of String × Any, where all the keys are unique. Let's call the class of the resources Res.

A REST operation on resources, is a function f(x: Res, y: Res): Res. Two examples of REST operations are:

  • PUT(x: Res, y: Res): Res = x, and
  • PATCH(x: Res, y: Res): Res, which works like PATCH({a: 2}, {a: 1, b: 3}) == {a: 2, b: 3}.

(This definition is specifically designed to argue about PUT and POST, and e.g. doesn't make much sense on GET and POST, as it doesn't care about persistence).

Now, by fixing x: Res (informatically speaking, using currying), PUT(x: Res) and PATCH(x: Res) are univariate functions of type Res ? Res.

  1. A function g: Res ? Res is called globally idempotent, when g ? g == g, i.e. for any y: Res, g(g(y)) = g(y).

  2. Let x: Res a resource, and k = x.keys. A function g = f(x) is called left idempotent, when for each y: Res, we have g(g(y))|? == g(y)|?. It basically means that the result should be same, if we look at the applied keys.

So, PATCH(x) is not globally idempotent, but is left idempotent. And left idempotency is the thing that matters here: if we patch a few keys of the resource, we want those keys to be same if we patch it again, and we don't care about the rest of the resource.

And when RFC is talking about PATCH not being idempotent, it is talking about global idempotency. Well, it's good that it's not globally idempotent, otherwise it would have been a broken operation.


Now, Jason Hoetger's answer is trying to demonstrate that PATCH is not even left idempotent, but it's breaking too many things to do so:

  • First of all, PATCH is used on a set, although PATCH is defined to work on maps / dictionaries / key-value objects.
  • If someone really wants to apply PATCH to sets, then there is a natural translation that should be used: t: Set<T> ? Map<T, Boolean>, defined with x in A iff t(A)(x) == True. Using this definition, patching is left idempotent.
  • In the example, this translation was not used, instead, the PATCH works like a POST. First of all, why is an ID generated for the object? And when is it generated? If the object is first compared to the elements of the set, and if no matching object is found, then the ID is generated, then again the program should work differently ({id: 1, email: "[email protected]"} must match with {email: "[email protected]"}, otherwise the program is always broken and the PATCH cannot possibly patch). If the ID is generated before checking against the set, again the program is broken.

One can make examples of PUT being non-idempotent with breaking half of the things that are broken in this example:

  • An example with generated additional features would be versioning. One may keep record of the number of changes on a single object. In this case, PUT is not idempotent: PUT /user/12 {email: "[email protected]"} results in {email: "...", version: 1} the first time, and {email: "...", version: 2} the second time.
  • Messing with the IDs, one may generate a new ID every time the object is updated, resulting in a non-idempotent PUT.

All the above examples are natural examples that one may encounter.


My final point is, that PATCH should not be globally idempotent, otherwise won't give you the desired effect. You want to change the email address of your user, without touching the rest of the information, and you don't want to overwrite the changes of another party accessing the same resource.

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

Using Accept header is really easy to get the format json or xml from the REST service.

This is my Controller, take a look produces section.

@RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
    public UIProperty getProperties() {
        return uiProperty;
    }

In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or MediaType.APPLICATION_XML_VALUE

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", header);

HttpEntity entity = new HttpEntity(headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
return response.getBody();

Edit 01:

In order to work with application/xml, add this dependency

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I faced the same problem and solved it by adding:

System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");

before openConnection method.

How does Java resolve a relative path in new File()?

I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.

Simply edit "AXLAPIService.java" and change

url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");

to

url = new URL("file:./schema/current/AXLAPI.wsdl");

or where ever you want to store it.

You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.

Flexbox Not Centering Vertically in IE

i have updated both fiddles. i hope it will make your work done.

centering

    html, body
{
    height: 100%;
    width: 100%;
}

body
{
    margin: 0;
}

.outer
{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inner
{
    width: 80%;
    margin: 0 auto;
}

center and scroll

html, body
    {
        height: 100%;
        width: 100%;
    }

    body
    {
        margin: 0;
        display:flex;
    }

    .outer
    {
        min-width: 100%;  
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .inner
    {
        width: 80%;
    margin-top:40px;
    margin: 0 auto;
    }

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

How to escape special characters in building a JSON string?

Most of these answers either does not answer the question or is unnecessarily long in the explanation.

OK so JSON only uses double quotation marks, we get that!

I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:

var d = {
    name: 'whatever',
    address: 'whatever',
    DOB: '01/01/2001'
}
$.ajax({
    type: "POST",
    url: 'some/url',
    dataType: 'json',
    data: JSON.stringify(d),
    ...
}

This will escape the characters for you.

This was also suggested by Mark Amery, Great answer BTW

Hope this helps someone.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

This is the way I solved my problem:

  1. Right click the folder that has uncommitted changes on your local
  2. Click Team > Advanced > Assume Unchanged
  3. Pull from master.

UPDATE:

As Hugo Zuleta rightly pointed out, you should be careful while applying this. He says that it might end up saying the branch is up to date, but the changes aren't shown, resulting in desync from the branch.

JavaScript null check

Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.

Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

A: Correct. Note that the following tests are equivalent:

data != null
data != undefined
data !== null && data !== undefined

See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.

400 vs 422 response to POST of data

There is no correct answer, since it depends on what the definition of "syntax" is for your request. The most important thing is that you:

  1. Use the response code(s) consistently
  2. Include as much additional information in the response body as you can to help the developer(s) using your API figure out what's going on.=

Before everyone jumps all over me for saying that there is no right or wrong answer here, let me explain a bit about how I came to the conclusion.

In this specific example, the OP's question is about a JSON request that contains a different key than expected. Now, the key name received is very similar, from a natural language standpoint, to the expected key, but it is, strictly, different, and hence not (usually) recognized by a machine as being equivalent.

As I said above, the deciding factor is what is meant by syntax. If the request was sent with a Content Type of application/json, then yes, the request is syntactically valid because it's valid JSON syntax, but not semantically valid, since it doesn't match what's expected. (assuming a strict definition of what makes the request in question semantically valid or not).

If, on the other hand, the request was sent with a more specific custom Content Type like application/vnd.mycorp.mydatatype+json that, perhaps, specifies exactly what fields are expected, then I would say that the request could easily be syntactically invalid, hence the 400 response.

In the case in question, since the key was wrong, not the value, there was a syntax error if there was a specification for what valid keys are. If there was no specification for valid keys, or the error was with a value, then it would be a semantic error.

jQuery append() vs appendChild()

The main difference is that appendChild is a DOM method and append is a jQuery method. The second one uses the first as you can see on jQuery source code

append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
            this.appendChild( elem );
        }
    });
},

If you're using jQuery library on your project, you'll be safe always using append when adding elements to the page.

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

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

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

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

Controller's Action Method

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

Jquery GET

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

Person class

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

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

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

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

For more information check Posting JSON Data to MVC Controllers Here

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

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

View

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

Action Method

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

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

Suitable for when you need to Get data from database

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

I hope this will help to you.

How to mock static methods in c# using MOQ framework?

Another option to transform the static method into a static Func or Action. For instance.

Original code:

    class Math
    {
        public static int Add(int x, int y)
        {
            return x + y;
        }

You want to "mock" the Add method, but you can't. Change the above code to this:

        public static Func<int, int, int> Add = (x, y) =>
        {
            return x + y;
        };

Existing client code doesn't have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

    [TestMethod]
    public static void MyTest()
    {
        Math.Add = (x, y) =>
        {
            return 11;
        };

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

[edit] I suggest that you add the following Cleanup code to your Unit Test class:

    [TestCleanup]
    public void Cleanup()
    {
        typeof(Math).TypeInitializer.Invoke(null, null);
    }

Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.

async/await - when to return a Task vs void?

I got clear idea from this statements.

  1. Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext(SynchronizationContext represents a location "where" code might be executed. ) that was active when the async void method started

Exceptions from an Async Void Method Can’t Be Caught with Catch

private async void ThrowExceptionAsync()
{
  throw new InvalidOperationException();
}
public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
  try
  {
    ThrowExceptionAsync();
  }
  catch (Exception)
  {
    // The exception is never caught here!
    throw;
  }
}

These exceptions can be observed using AppDomain.UnhandledException or a similar catch-all event for GUI/ASP.NET applications, but using those events for regular exception handling is a recipe for unmaintainability(it crashes the application).

  1. Async void methods have different composing semantics. Async methods returning Task or Task can be easily composed using await, Task.WhenAny, Task.WhenAll and so on. Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed. It’s easy to start several async void methods, but it’s not easy to determine when they’ve finished. Async void methods will notify their SynchronizationContext when they start and finish, but a custom SynchronizationContext is a complex solution for regular application code.

  2. Async Void method useful when using synchronous event handler because they raise their exceptions directly on the SynchronizationContext, which is similar to how synchronous event handlers behave

For more details check this link https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Convert Java Date to UTC String

tl;dr

You asked:

I was looking for a one-liner like:

Ask and ye shall receive. Convert from terrible legacy class Date to its modern replacement, Instant.

myJavaUtilDate.toInstant().toString()

2020-05-05T19:46:12.912Z

java.time

In Java 8 and later we have the new java.time package built in (Tutorial). Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The best solution is to sort your date-time objects rather than strings. But if you must work in strings, read on.

An Instant represents a moment on the timeline, basically in UTC (see class doc for precise details). The toString implementation uses the DateTimeFormatter.ISO_INSTANT format by default. This format includes zero, three, six or nine digits digits as needed to display fraction of a second up to nanosecond precision.

String output = Instant.now().toString(); // Example: '2015-12-03T10:15:30.120Z'

If you must interoperate with the old Date class, convert to/from java.time via new methods added to the old classes. Example: Date::toInstant.

myJavaUtilDate.toInstant().toString()

You may want to use an alternate formatter if you need a consistent number of digits in the fractional second or if you need no fractional second.

Another route if you want to truncate fractions of a second is to use ZonedDateTime instead of Instant, calling its method to change the fraction to zero.

Note that we must specify a time zone for ZonedDateTime (thus the name). In our case that means UTC. The subclass of ZoneID, ZoneOffset, holds a convenient constant for UTC. If we omit the time zone, the JVM’s current default time zone is implicitly applied.

String output = ZonedDateTime.now( ZoneOffset.UTC ).withNano( 0 ).toString();  // Example: 2015-08-27T19:28:58Z

Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

UPDATE: The Joda -Time project is now in maintenance mode, with the team advising migration to the java.time classes.

I was looking for a one-liner

Easy if using the Joda-Time 2.3 library. ISO 8601 is the default formatting.

Time Zone

In the code example below, note that I am specifying a time zone rather than depending on the default time zone. In this case, I'm specifying UTC per your question. The Z on the end, spoken as "Zulu", means no time zone offset from UTC.

Example Code

// import org.joda.time.*;

String output = new DateTime( DateTimeZone.UTC );

Output…

2013-12-12T18:29:50.588Z

What is the difference between for and foreach?

for loop:

 1) need to specify the loop bounds( minimum or maximum).

  2) executes a statement or a block of statements repeatedly 
    until a specified expression evaluates to false.

Ex1:-

int K = 0;

for (int x = 1; x <= 9; x++){
        k = k + x ;
}

foreach statement:

1)do not need to specify the loop bounds minimum or maximum.

2)repeats a group of embedded statements for 
     a)each element in an array 
  or b) an object collection.       

Ex2:-

int k = 0;

int[] tempArr = new int[] { 0, 2, 3, 8, 17 };

foreach (int i in tempArr){
    k = k + i ;
}

What is the significance of load factor in HashMap?

What is load factor ?

The amount of capacity which is to be exhausted for the HashMap to increase its capacity ?

Why load factor ?

Load factor is by default 0.75 of the initial capacity (16) therefore 25% of the buckets will be free before there is an increase in the capacity & this makes many new buckets with new hashcodes pointing to them to exist just after the increase in the number of buckets.

Now why should you keep many free buckets & what is the impact of keeping free buckets on the performance ?

If you set the loading factor to say 1.0 then something very interesting might happen.

Say you are adding an object x to your hashmap whose hashCode is 888 & in your hashmap the bucket representing the hashcode is free , so the object x gets added to the bucket, but now again say if you are adding another object y whose hashCode is also 888 then your object y will get added for sure BUT at the end of the bucket (because the buckets are nothing but linkedList implementation storing key,value & next) now this has a performance impact ! Since your object y is no longer present in the head of the bucket if you perform a lookup the time taken is not going to be O(1) this time it depends on how many items are there in the same bucket. This is called hash collision by the way & this even happens when your loading factor is less than 1.

Correlation between performance , hash collision & loading factor ?

Lower load factor = more free buckets = less chances of collision = high performance = high space requirement.

Correct me if i am wrong somewhere.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

I need to learn Web Services in Java. What are the different types in it?

Q1) Here are couple things to read or google more :

Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest

It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.

Q2) Here are couple of good tutorials for soap (I had them bookmarked) :

http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226

http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/

http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html

Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.

SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.

Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).

Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.

If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development. It's fantastic, not hard to read and not too big either (win win).

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

WebSockets is definitely the future.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.

Comparison:

of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia

Advantages:

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).

P.S.

Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

What does it mean by select 1 from table?

This is just used for convenience with IF EXISTS(). Otherwise you can go with

select * from [table_name]

Image In the case of 'IF EXISTS', we just need know that any row with specified condition exists or not doesn't matter what is content of row.

select 1 from Users

above example code, returns no. of rows equals to no. of users with 1 in single column

Generics/templates in python?

The other answers are totally fine:

  • One does not need a special syntax to support generics in Python
  • Python uses duck typing as pointed out by André.

However, if you still want a typed variant, there is a built-in solution since Python 3.5.

Generic classes:

from typing import TypeVar, Generic

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        # Create an empty list with items of type T
        self.items: List[T] = []

    def push(self, item: T) -> None:
        self.items.append(item)

    def pop(self) -> T:
        return self.items.pop()

    def empty(self) -> bool:
        return not self.items
# Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x')        # Type error

Generic functions:

from typing import TypeVar, Sequence

T = TypeVar('T')      # Declare type variable

def first(seq: Sequence[T]) -> T:
    return seq[0]

def last(seq: Sequence[T]) -> T:
    return seq[-1]


n = first([1, 2, 3])  # n has type int.

Reference: mypy documentation about generics.

Testing whether a value is odd or even

Note: there are also negative numbers.

function isOddInteger(n)
{
   return isInteger(n) && (n % 2 !== 0);
}

where

function isInteger(n)
{
   return n === parseInt(n, 10);
}

REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

Why does viewWillAppear not get called when an app comes back from the background?

Use Notification Center in the viewDidLoad: method of your ViewController to call a method and from there do what you were supposed to do in your viewWillAppear: method. Calling viewWillAppear: directly is not a good option.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationIsActive:) 
        name:UIApplicationDidBecomeActiveNotification 
        object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self 
        selector:@selector(applicationEnteredForeground:) 
        name:UIApplicationWillEnterForegroundNotification
        object:nil];
}

- (void)applicationIsActive:(NSNotification *)notification {
    NSLog(@"Application Did Become Active");
}

- (void)applicationEnteredForeground:(NSNotification *)notification {
    NSLog(@"Application Entered Foreground");
}

What is the use of ByteBuffer in Java?

The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:

  • Absolute and relative get and put methods that read and write single bytes;

  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;

  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;

  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;

  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and

  • Methods for compacting, duplicating, and slicing a byte buffer.

Example code : Putting Bytes into a buffer.

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put(int, byte).
    // This method does not affect the position.
    bbuf.put(0, (byte)0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put(byte)
    bbuf.put((byte)0xFF);

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

Storing sex (gender) in database

An Int (or TinyInt) aligned to an Enum field would be my methodology.

First, if you have a single bit field in a database, the row will still use a full byte, so as far as space savings, it only pays off if you have multiple bit fields.

Second, strings/chars have a "magic value" feel to them, regardless of how obvious they may seem at design time. Not to mention, it lets people store just about any value they would not necessarily map to anything obvious.

Third, a numeric value is much easier (and better practice) to create a lookup table for, in order to enforce referential integrity, and can correlate 1-to-1 with an enum, so there is parity in storing the value in memory within the application or in the database.

Understanding the difference between Object.create() and new SomeFunction()

The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.

In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".

In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.

Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.

See this link for a comparison of the two ways.

Java : Comparable vs Comparator

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Handling InterruptedException in Java

To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.

In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.

So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.

So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.

Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.

Entity Framework and Connection Pooling

Accoriding to EF6 (4,5 also) documentation: https://msdn.microsoft.com/en-us/data/hh949853#9

9.3 Context per request

Entity Framework’s contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience. Contexts are expected to be short lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible. In web scenarios it’s important to keep this in mind and not have a context for more than the duration of a single request. Similarly, in non-web scenarios, context should be discarded based on your understanding of the different levels of caching in the Entity Framework. Generally speaking, one should avoid having a context instance throughout the life of the application, as well as contexts per thread and static contexts.

jQuery addClass onClick

$('#button').click(function(){
    $(this).addClass('active');
});

In Python, when to use a Dictionary, List or Set?

  • Do you just need an ordered sequence of items? Go for a list.
  • Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
  • Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.

When does a process get SIGABRT (signal 6)?

SIGABRT is commonly used by libc and other libraries to abort the program in case of critical errors. For example, glibc sends an SIGABRT in case of a detected double-free or other heap corruptions.

Also, most assert implementations make use of SIGABRT in case of a failed assert.

Furthermore, SIGABRT can be sent from any other process like any other signal. Of course, the sending process needs to run as same user or root.

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

C# How to determine if a number is a multiple of another?

I don't get that part about the string stuff, but why don't you use the modulo operator (%) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.

It goes like that:

   int a = 10; int b = 5;

   // is a a multiple of b 
   if ( a % b == 0 )  ....

C# Form.Close vs Form.Dispose

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

Can we have multiple <tbody> in same <table>?

I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.

HTML

<div>
        <table class="table table-hover table-condensed table-striped">
            <thead>
                <tr>
                    <th>Store ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Cost</th>
                    <th>Sales</th>
                    <th>Revenue</th>
                    <th>Employees</th>
                    <th>Employees H-sum</th>
                </tr>
            </thead>
            <tbody data-ng-repeat="storedata in storeDataModel.storedata">
                <tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
                    <td>{{storedata.store.storeId}}</td>
                    <td>{{storedata.store.storeName}}</td>
                    <td>{{storedata.store.storeAddress}}</td>
                    <td>{{storedata.store.storeCity}}</td>
                    <td>{{storedata.data.costTotal}}</td>
                    <td>{{storedata.data.salesTotal}}</td>
                    <td>{{storedata.data.revenueTotal}}</td>
                    <td>{{storedata.data.averageEmployees}}</td>
                    <td>{{storedata.data.averageEmployeesHours}}</td>
                </tr>
                <tr data-ng-show="dayDataCollapse[$index]">
                    <td colspan="2">&nbsp;</td>
                    <td colspan="7">
                        <div>
                            <div class="pull-right">
                                <table class="table table-hover table-condensed table-striped">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Date [YYYY-MM-dd]</th>
                                            <th>Cost</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Employees</th>
                                            <th>Employees H-sum</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
                                            <td class="pullright">
                                                <button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
                                                </button>
                                            </td>
                                            <td>{{dayData.date}}</td>
                                            <td>{{dayData.cost}}</td>
                                            <td>{{dayData.sales}}</td>
                                            <td>{{dayData.revenue}}</td>
                                            <td>{{dayData.employees}}</td>
                                            <td>{{dayData.employeesHoursSum}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

Multi-statement Table Valued Function vs Inline Table Valued Function

In researching Matt's comment, I have revised my original statement. He is correct, there will be a difference in performance between an inline table valued function (ITVF) and a multi-statement table valued function (MSTVF) even if they both simply execute a SELECT statement. SQL Server will treat an ITVF somewhat like a VIEW in that it will calculate an execution plan using the latest statistics on the tables in question. A MSTVF is equivalent to stuffing the entire contents of your SELECT statement into a table variable and then joining to that. Thus, the compiler cannot use any table statistics on the tables in the MSTVF. So, all things being equal, (which they rarely are), the ITVF will perform better than the MSTVF. In my tests, the performance difference in completion time was negligible however from a statistics standpoint, it was noticeable.

In your case, the two functions are not functionally equivalent. The MSTV function does an extra query each time it is called and, most importantly, filters on the customer id. In a large query, the optimizer would not be able to take advantage of other types of joins as it would need to call the function for each customerId passed. However, if you re-wrote your MSTV function like so:

CREATE FUNCTION MyNS.GetLastShipped()
RETURNS @CustomerOrder TABLE
    (
    SaleOrderID    INT         NOT NULL,
    CustomerID      INT         NOT NULL,
    OrderDate       DATETIME    NOT NULL,
    OrderQty        INT         NOT NULL
    )
AS
BEGIN
    INSERT @CustomerOrder
    SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
    FROM Sales.SalesOrderHeader a 
        INNER JOIN Sales.SalesOrderHeader b
            ON a.SalesOrderID = b.SalesOrderID
        INNER JOIN Production.Product c 
            ON b.ProductID = c.ProductID
    WHERE a.OrderDate = (
                        Select Max(SH1.OrderDate)
                        FROM Sales.SalesOrderHeader As SH1
                        WHERE SH1.CustomerID = A.CustomerId
                        )
    RETURN
END
GO

In a query, the optimizer would be able to call that function once and build a better execution plan but it still would not be better than an equivalent, non-parameterized ITVS or a VIEW.

ITVFs should be preferred over a MSTVFs when feasible because the datatypes, nullability and collation from the columns in the table whereas you declare those properties in a multi-statement table valued function and, importantly, you will get better execution plans from the ITVF. In my experience, I have not found many circumstances where an ITVF was a better option than a VIEW but mileage may vary.

Thanks to Matt.

Addition

Since I saw this come up recently, here is an excellent analysis done by Wayne Sheffield comparing the performance difference between Inline Table Valued functions and Multi-Statement functions.

His original blog post.

Copy on SQL Server Central

REST, HTTP DELETE and parameters

It's an old question, but here are some comments...

  1. In SQL, the DELETE command accepts a parameter "CASCADE", which allows you to specify that dependent objects should also be deleted. This is an example of a DELETE parameter that makes sense, but 'man rm' could provide others. How would these cases possibly be implemented in REST/HTTP without a parameter?
  2. @Jan, it seems to be a well-established convention that the path part of the URL identifies a resource, whereas the querystring does not (at least not necessarily). Examples abound: getting the same resource but in a different format, getting specific fields of a resource, etc. If we consider the querystring as part of the resource identifier, it is impossible to have a concept of "different views of the same resource" without turning to non-RESTful mechanisms such as HTTP content negotiation (which can be undesirable for many reasons).

Daylight saving time and time zone best practices

One other thing, make sure the servers have the up to date daylight savings patch applied.

We had a situation last year where our times were consistently out by one hour for a three-week period for North American users, even though we were using a UTC based system.

It turns out in the end it was the servers. They just needed an up-to-date patch applied (Windows Server 2003).

What are the best practices for SQLite on Android?

My understanding of SQLiteDatabase APIs is that in case you have a multi threaded application, you cannot afford to have more than a 1 SQLiteDatabase object pointing to a single database.

The object definitely can be created but the inserts/updates fail if different threads/processes (too) start using different SQLiteDatabase objects (like how we use in JDBC Connection).

The only solution here is to stick with 1 SQLiteDatabase objects and whenever a startTransaction() is used in more than 1 thread, Android manages the locking across different threads and allows only 1 thread at a time to have exclusive update access.

Also you can do "Reads" from the database and use the same SQLiteDatabase object in a different thread (while another thread writes) and there would never be database corruption i.e "read thread" wouldn't read the data from the database till the "write thread" commits the data although both use the same SQLiteDatabase object.

This is different from how connection object is in JDBC where if you pass around (use the same) the connection object between read and write threads then we would likely be printing uncommitted data too.

In my enterprise application, I try to use conditional checks so that the UI Thread never have to wait, while the BG thread holds the SQLiteDatabase object (exclusively). I try to predict UI Actions and defer BG thread from running for 'x' seconds. Also one can maintain PriorityQueue to manage handing out SQLiteDatabase Connection objects so that the UI Thread gets it first.

Best practice for partial updates in a RESTful service

Check out http://www.odata.org/

It defines the MERGE method, so in your case it would be something like this:

MERGE /customer/123

<customer>
   <status>DISABLED</status>
</customer>

Only the status property is updated and the other values are preserved.

Creating a generic method in C#

What if you specified the default value to return, instead of using default(T)?

public static T GetQueryString<T>(string key, T defaultValue) {...}

It makes calling it easier too:

var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified

The downside being you need magic values to denote invalid/missing querystring values.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

To clarify the problem with @@Identity:

For instance, if you insert a table and that table has triggers doing inserts, @@Identity will return the id from the insert in the trigger (a log_id or something), while scope_identity() will return the id from the insert in the original table.

So if you don't have any triggers, scope_identity() and @@identity will return the same value. If you have triggers, you need to think about what value you'd like.

Improve INSERT-per-second performance of SQLite

I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;

SQL : BETWEEN vs <= and >=

I have a slight preference for BETWEEN because it makes it instantly clear to the reader that you are checking one field for a range. This is especially true if you have similar field names in your table.

If, say, our table has both a transactiondate and a transitiondate, if I read

transactiondate between ...

I know immediately that both ends of the test are against this one field.

If I read

transactiondate>='2009-04-17' and transactiondate<='2009-04-22'

I have to take an extra moment to make sure the two fields are the same.

Also, as a query gets edited over time, a sloppy programmer might separate the two fields. I've seen plenty of queries that say something like

where transactiondate>='2009-04-17'
  and salestype='A'
  and customernumber=customer.idnumber
  and transactiondate<='2009-04-22'

If they try this with a BETWEEN, of course, it will be a syntax error and promptly fixed.

What does elementFormDefault do in XSD?

New, detailed answer and explanation to an old, frequently asked question...

Short answer: If you don't add elementFormDefault="qualified" to xsd:schema, then the default unqualified value means that locally declared elements are in no namespace.

There's a lot of confusion regarding what elementFormDefault does, but this can be quickly clarified with a short example...

Streamlined version of your XSD:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:target="http://www.levijackson.net/web340/ns"
        targetNamespace="http://www.levijackson.net/web340/ns">
  <element name="assignments">
    <complexType>
      <sequence>
        <element name="assignment" type="target:assignmentInfo" 
                 minOccurs="1" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>
  <complexType name="assignmentInfo">
    <sequence>
      <element name="name" type="string"/>
    </sequence>
    <attribute name="id" type="string" use="required"/>
  </complexType>
</schema>

Key points:

  • The assignment element is locally defined.
  • Elements locally defined in XSD are in no namespace by default.
    • This is because the default value for elementFormDefault is unqualified.
    • This arguably is a design mistake by the creators of XSD.
    • Standard practice is to always use elementFormDefault="qualified" so that assignment is in the target namespace as one would expect.
  • It is a rarely used form attribute on xs:element declarations for which elementFormDefault establishes default values.

Seemingly Valid XML

This XML looks like it should be valid according to the above XSD:

<assignments xmlns="http://www.levijackson.net/web340/ns"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
  <assignment id="a1">
    <name>John</name>
  </assignment>
</assignments>

Notice:

  • The default namespace on assignments places assignments and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns).

Perplexing Validation Error

Despite looking valid, the above XML yields the following confusing validation error:

[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.

Notes:

  • You would not be the first developer to curse this diagnostic that seems to say that the content is invalid because it expected to find an assignment element but it actually found an assignment element. (WTF)
  • What this really means: The { and } around assignment means that validation was expecting assignment in no namespace here. Unfortunately, when it says that it found an assignment element, it doesn't mention that it found it in a default namespace which differs from no namespace.

Solution

  • Vast majority of the time: Add elementFormDefault="qualified" to the xsd:schema element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.
  • Tiny minority of the time: Change the XML to comply with the XSD's requirement that assignment be in no namespace. This can be achieved, for example, by adding xmlns="" to the assignment element.

Credits: Thanks to Michael Kay for helpful feedback on this answer.

Which concurrent Queue implementation should I use in Java?

Your question title mentions Blocking Queues. However, ConcurrentLinkedQueue is not a blocking queue.

The BlockingQueues are ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, PriorityBlockingQueue, and SynchronousQueue.

Some of these are clearly not fit for your purpose (DelayQueue, PriorityBlockingQueue, and SynchronousQueue). LinkedBlockingQueue and LinkedBlockingDeque are identical, except that the latter is a double-ended Queue (it implements the Deque interface).

Since ArrayBlockingQueue is only useful if you want to limit the number of elements, I'd stick to LinkedBlockingQueue.

Network tools that simulate slow network connection

I love Charles.

The free version works fine for me.

Throttling, rerwiting, breakpoints are all awesome features.

Algorithm for Determining Tic Tac Toe Game Over

Constant time solution, runs in O(8).

Store the state of the board as a binary number. The smallest bit (2^0) is the top left row of the board. Then it goes rightwards, then downwards.

I.E.

+-----------------+
| 2^0 | 2^1 | 2^2 |
|-----------------|
| 2^3 | 2^4 | 2^5 |
|-----------------|
| 2^6 | 2^7 | 2^8 |
+-----------------+

Each player has their own binary number to represent the state (because tic-tac-toe) has 3 states (X, O & blank) so a single binary number won't work to represent the state of the board for multiple players.

For example, a board like:

+-----------+
| X | O | X |
|-----------|
| O | X |   |
|-----------|
|   | O |   |
+-----------+

   0 1 2 3 4 5 6 7 8
X: 1 0 1 0 1 0 0 0 0
O: 0 1 0 1 0 0 0 1 0

Notice that the bits for player X are disjoint from the bits for player O, this is obvious because X can't put a piece where O has a piece and vice versa.

To check whether a player has won, we need to compare all the positions covered by that player to a position we know is a win-position. In this case, the easiest way to do that would be by AND-gating the player-position and the win-position and seeing if the two are equal.

boolean isWinner(short X) {
    for (int i = 0; i < 8; i++)
        if ((X & winCombinations[i]) == winCombinations[i])
            return true;
    return false;
}

eg.

X: 111001010
W: 111000000 // win position, all same across first row.
------------
&: 111000000

Note: X & W = W, so X is in a win state.

This is a constant time solution, it depends only on the number of win-positions, because applying AND-gate is a constant time operation and the number of win-positions is finite.

It also simplifies the task of enumerating all valid board states, their just all the numbers representable by 9 bits. But of course you need an extra condition to guarantee a number is a valid board state (eg. 0b111111111 is a valid 9-bit number, but it isn't a valid board state because X has just taken all the turns).

The number of possible win positions can be generated on the fly, but here they are anyways.

short[] winCombinations = new short[] {
  // each row
  0b000000111,
  0b000111000,
  0b111000000,
  // each column
  0b100100100,
  0b010010010,
  0b001001001,
  // each diagonal
  0b100010001,
  0b001010100
};

To enumerate all board positions, you can run the following loop. Although I'll leave determining whether a number is a valid board state upto someone else.

NOTE: (2**9 - 1) = (2**8) + (2**7) + (2**6) + ... (2**1) + (2**0)

for (short X = 0; X < (Math.pow(2,9) - 1); X++)
   System.out.println(isWinner(X));

What is the difference between SQL, PL-SQL and T-SQL?

1. SQL or Structured Query Language was developed by IBM for their product "System R".

Later ANSI made it as a Standard on which all Query Languages are based upon and have extended this to create their own DataBase Query Language suits. The first standard was SQL-86 and latest being SQL:2016

2. T-SQL or Transact-SQL was developed by Sybase and later co-owned by Microsoft SQL Server.

3. PL/SQL or Procedural Language/SQL was Oracle Database, known as "Relation Software" that time.

I've documented this in my blog post.

Edit and Continue: "Changes are not allowed when..."

I'm adding my answer because the thing that solved it for me isn't clearly mentioned yet. Actually what helped me was this article:

http://www.rubencanton.com/blog/2012/02/how-to-fix-error-changes-are-not-allowed-while-code-is-running-in-net.html

and here is a short description of the solution:

  1. Stop running your app.
  2. Go to Tools > Options > Debugging > Edit and Continue
  3. Disable “Enable Edit and Continue”

Note how counter-intuitive this is: I had to disable (uncheck) "Enable Edit and Continue".

This will then allow you to change code in your editor without getting that message "Changes are not allowed while code is running".

Note however that the code changes you make will NOT be reflected in your running program - for that you need to stop and restart your program (off the top of my head I think that template/ASPX changes do get reflected, but not VB/C# changes, i.e. "code behind" code).

What are the benefits of using C# vs F# or F# vs C#?

  • F# Has Better Performance than C# in Math
  • You could use F# projects in the same solution with C# (and call from one to another)
  • F# is really good for complex algorithmic programming, financial and scientific applications
  • F# logically is really good for the parallel execution (it is easier to make F# code execute on parallel cores, than C#)

What is the proper way to re-attach detached objects in Hibernate?

calling first merge() (to update persistent instance), then lock(LockMode.NONE) (to attach the current instance, not the one returned by merge()) seems to work for some use cases.

How to convert SecureString to System.String?

Dang. right after posting this I found the answer deep in this article. But if anyone knows how to access the IntPtr unmanaged, unencrypted buffer that this method exposes, one byte at a time so that I don't have to create a managed string object out of it to keep my security high, please add an answer. :)

static String SecureStringToString(SecureString value)
{
    IntPtr bstr = Marshal.SecureStringToBSTR(value);

    try
    {
        return Marshal.PtrToStringBSTR(bstr);
    }
    finally
    {
        Marshal.FreeBSTR(bstr);
    }
}

When to use reinterpret_cast?

Here is a variant of Avi Ginsburg's program which clearly illustrates the property of reinterpret_cast mentioned by Chris Luengo, flodin, and cmdLP: that the compiler treats the pointed-to memory location as if it were an object of the new type:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

class A
{
public:
    int i;
};

class B : public A
{
public:
    virtual void f() {}
};

int main()
{
    string s;
    B b;
    b.i = 0;
    A* as = static_cast<A*>(&b);
    A* ar = reinterpret_cast<A*>(&b);
    B* c = reinterpret_cast<B*>(ar);
    
    cout << "as->i = " << hex << setfill('0')  << as->i << "\n";
    cout << "ar->i = " << ar->i << "\n";
    cout << "b.i   = " << b.i << "\n";
    cout << "c->i  = " << c->i << "\n";
    cout << "\n";
    cout << "&(as->i) = " << &(as->i) << "\n";
    cout << "&(ar->i) = " << &(ar->i) << "\n";
    cout << "&(b.i) = " << &(b.i) << "\n";
    cout << "&(c->i) = " << &(c->i) << "\n";
    cout << "\n";
    cout << "&b = " << &b << "\n";
    cout << "as = " << as << "\n";
    cout << "ar = " << ar << "\n";
    cout << "c  = " << c  << "\n";
    
    cout << "Press ENTER to exit.\n";
    getline(cin,s);
}

Which results in output like this:

as->i = 0
ar->i = 50ee64
b.i   = 0
c->i  = 0

&(as->i) = 00EFF978
&(ar->i) = 00EFF974
&(b.i)   = 00EFF978
&(c->i)  = 00EFF978

&b = 00EFF974
as = 00EFF978
ar = 00EFF974
c  = 00EFF974
Press ENTER to exit.

It can be seen that the B object is built in memory as B-specific data first, followed by the embedded A object. The static_cast correctly returns the address of the embedded A object, and the pointer created by static_cast correctly gives the value of the data field. The pointer generated by reinterpret_cast treats b's memory location as if it were a plain A object, and so when the pointer tries to get the data field it returns some B-specific data as if it were the contents of this field.

One use of reinterpret_cast is to convert a pointer to an unsigned integer (when pointers and unsigned integers are the same size):

int i; unsigned int u = reinterpret_cast<unsigned int>(&i);

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

Import and Export Excel - What is the best library?

SpreadsheetGear for .NET reads and writes CSV / XLS / XLSX and does more.

You can see live ASP.NET samples with C# and VB source code here and download a free trial here.

Of course I think SpreadsheetGear is the best library to import / export Excel workbooks in ASP.NET - but I am biased. You can see what some of our customers say on the right hand side of this page.

Disclaimer: I own SpreadsheetGear LLC

Array versus List<T>: When to use which?

Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."

You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

When would you use the different git merge strategies?

With Git 2.30 (Q1 2021), there will be a new merge strategy: ORT ("Ostensibly Recursive's Twin").

git merge -s ort

This comes from this thread from Elijah Newren:

For now, I'm calling it "Ostensibly Recursive's Twin", or "ort" for short. > At first, people shouldn't be able to notice any difference between it and the current recursive strategy, other than the fact that I think I can make it a bit faster (especially for big repos).

But it should allow me to fix some (admittedly corner case) bugs that are harder to handle in the current design, and I think that a merge that doesn't touch $GIT_WORK_TREE or $GIT_INDEX_FILE will allow for some fun new features.
That's the hope anyway.

Problem:

In the ideal world, we should:

  • ask unpack_trees() to do "read-tree -m" without "-u";

  • do all the merge-recursive computations in-core and prepare the resulting index, while keeping the current index intact;

  • compare the current in-core index and the resulting in-core index, and notice the paths that need to be added, updated or removed in the working tree, and ensure that there is no loss of information when the change is reflected to the working tree;
    E.g. the result wants to create a file where the working tree currently has a directory with non-expendable contents in it, the result wants to remove a file where the working tree file has local modification, etc.;
    And then finally

  • carry out the working tree update to make it match what the resulting in-core index says it should look like.

Result:

See commit 14c4586 (02 Nov 2020), commit fe1a21d (29 Oct 2020), and commit 47b1e89, commit 17e5574 (27 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit a1f9595, 18 Nov 2020)

merge-ort: barebones API of new merge strategy with empty implementation

Signed-off-by: Elijah Newren

This is the beginning of a new merge strategy.

While there are some API differences, and the implementation has some differences in behavior, it is essentially meant as an eventual drop-in replacement for merge-recursive.c.

However, it is being built to exist side-by-side with merge-recursive so that we have plenty of time to find out how those differences pan out in the real world while people can still fall back to merge-recursive.
(Also, I intend to avoid modifying merge-recursive during this process, to keep it stable.)

The primary difference noticable here is that the updating of the working tree and index is not done simultaneously with the merge algorithm, but is a separate post-processing step.
The new API is designed so that one can do repeated merges (e.g. during a rebase or cherry-pick) and only update the index and working tree one time at the end instead of updating it with every intermediate result.

Also, one can perform a merge between two branches, neither of which match the index or the working tree, without clobbering the index or working tree.

And:

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

t6423, t6436: note improved ort handling with dirty files

Signed-off-by: Elijah Newren

The "recursive" backend relies on unpack_trees() to check if unstaged changes would be overwritten by a merge, but unpack_trees() does not understand renames -- and once it returns, it has already written many updates to the working tree and index.
As such, "recursive" had to do a special 4-way merge where it would need to also treat the working copy as an extra source of differences that we had to carefully avoid overwriting and resulting in moving files to new locations to avoid conflicts.

The "ort" backend, by contrast, does the complete merge inmemory, and only updates the index and working copy as a post-processing step.
If there are dirty files in the way, it can simply abort the merge.

t6423: expect improved conflict markers labels in the ort backend

Signed-off-by: Elijah Newren

Conflict markers carry an extra annotation of the form REF-OR-COMMIT:FILENAME to help distinguish where the content is coming from, with the :FILENAME piece being left off if it is the same for both sides of history (thus only renames with content conflicts carry that part of the annotation).

However, there were cases where the :FILENAME annotation was accidentally left off, due to merge-recursive's every-codepath-needs-a-copy-of-all-special-case-code format.

t6404, t6423: expect improved rename/delete handling in ort backend

Signed-off-by: Elijah Newren

When a file is renamed and has content conflicts, merge-recursive does not have some stages for the old filename and some stages for the new filename in the index; instead it copies all the stages corresponding to the old filename over to the corresponding locations for the new filename, so that there are three higher order stages all corresponding to the new filename.

Doing things this way makes it easier for the user to access the different versions and to resolve the conflict (no need to manually 'git rm '(man) the old version as well as 'git add'(man) the new one).

rename/deletes should be handled similarly -- there should be two stages for the renamed file rather than just one.
We do not want to destabilize merge-recursive right now, so instead update relevant tests to have different expectations depending on whether the "recursive" or "ort" merge strategies are in use.


With Git 2.30 (Q1 2021), Preparation for a new merge strategy.

See commit 848a856, commit fd15863, commit 23bef2e, commit c8c35f6, commit c12d1f2, commit 727c75b, commit 489c85f, commit ef52778, commit f06481f (26 Oct 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 66c62ea, 18 Nov 2020)

merge tests: expect improved directory/file conflict handling in ort

Signed-off-by: Elijah Newren

merge-recursive.c is built on the idea of running unpack_trees() and then "doing minor touch-ups" to get the result.
Unfortunately, unpack_trees() was run in an update-as-it-goes mode, leading merge-recursive.c to follow suit and end up with an immediate evaluation and fix-it-up-as-you-go design.

Some things like directory/file conflicts are not well representable in the index data structure, and required special extra code to handle.
But then when it was discovered that rename/delete conflicts could also be involved in directory/file conflicts, the special directory/file conflict handling code had to be copied to the rename/delete codepath.
...and then it had to be copied for modify/delete, and for rename/rename(1to2) conflicts, ...and yet it still missed some.
Further, when it was discovered that there were also file/submodule conflicts and submodule/directory conflicts, we needed to copy the special submodule handling code to all the special cases throughout the codebase.

And then it was discovered that our handling of directory/file conflicts was suboptimal because it would create untracked files to store the contents of the conflicting file, which would not be cleaned up if someone were to run a 'git merge --abort'(man) or 'git rebase --abort'(man).

It was also difficult or scary to try to add or remove the index entries corresponding to these files given the directory/file conflict in the index.
But changing merge-recursive.c to handle these correctly was a royal pain because there were so many sites in the code with similar but not identical code for handling directory/file/submodule conflicts that would all need to be updated.

I have worked hard to push all directory/file/submodule conflict handling in merge-ort through a single codepath, and avoid creating untracked files for storing tracked content (it does record things at alternate paths, but makes sure they have higher-order stages in the index).


With Git 2.31 (Q1 2021), the merge backend "done right" starts to emerge.
Example:

See commit 6d37ca2 (11 Nov 2020) by Junio C Hamano (gitster).
See commit 89422d2, commit ef2b369, commit 70912f6, commit 6681ce5, commit 9fefce6, commit bb470f4, commit ee4012d, commit a9945bb, commit 8adffaa, commit 6a02dd9, commit 291f29c, commit 98bf984, commit 34e557a, commit 885f006, commit d2bc199, commit 0c0d705, commit c801717, commit e4171b1, commit 231e2dd, commit 5b59c3d (13 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit f9d29da, 06 Jan 2021)

merge-ort: add implementation of record_conflicted_index_entries()

Signed-off-by: Elijah Newren

After checkout(), the working tree has the appropriate contents, and the index matches the working copy.
That means that all unmodified and cleanly merged files have correct index entries, but conflicted entries need to be updated.

We do this by looping over the conflicted entries, marking the existing index entry for the path with CE_REMOVE, adding new higher order staged for the path at the end of the index (ignoring normal index sort order), and then at the end of the loop removing the CE_REMOVED-marked cache entries and sorting the index.


With Git 2.31 (Q1 2021), rename detection is added to the "ORT" merge strategy.

See commit 6fcccbd, commit f1665e6, commit 35e47e3, commit 2e91ddd, commit 53e88a0, commit af1e56c (15 Dec 2020), and commit c2d267d, commit 965a7bc, commit f39d05c, commit e1a124e, commit 864075e (14 Dec 2020) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 2856089, 25 Jan 2021)

Example:

merge-ort: add implementation of normal rename handling

Signed-off-by: Elijah Newren

Implement handling of normal renames.
This code replaces the following from merge-recurisve.c:

  • the code relevant to RENAME_NORMAL in process_renames()
  • the RENAME_NORMAL case of process_entry()

Also, there is some shared code from merge-recursive.c for multiple different rename cases which we will no longer need for this case (or other rename cases):

  • handle_rename_normal()
  • setup_rename_conflict_info()

The consolidation of four separate codepaths into one is made possible by a change in design: process_renames() tweaks the conflict_info entries within opt->priv->paths such that process_entry() can then handle all the non-rename conflict types (directory/file, modify/delete, etc.) orthogonally.

This means we're much less likely to miss special implementation of some kind of combination of conflict types (see commits brought in by 66c62ea ("Merge branch 'en/merge-tests'", 2020-11-18, Git v2.30.0-rc0 -- merge listed in batch #6), especially commit ef52778 ("merge tests: expect improved directory/file conflict handling in ort", 2020-10-26, Git v2.30.0-rc0 -- merge listed in batch #6) for more details).

That, together with letting worktree/index updating be handled orthogonally in the merge_switch_to_result() function, dramatically simplifies the code for various special rename cases.

(To be fair, the code for handling normal renames wasn't all that complicated beforehand, but it's still much simpler now.)

And, still with Git 2.31 (Q1 2021), With Git 2.31 (Q1 2021), oRT merge strategy learns more support for merge conflicts.

See commit 4ef88fc, commit 4204cd5, commit 70f19c7, commit c73cda7, commit f591c47, commit 62fdec1, commit 991bbdc, commit 5a1a1e8, commit 23366d2, commit 0ccfa4e (01 Jan 2021) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit b65b9ff, 05 Feb 2021)

merge-ort: add handling for different types of files at same path

Signed-off-by: Elijah Newren

Add some handling that explicitly considers collisions of the following types:

  • file/submodule
  • file/symlink
  • submodule/symlink> Leaving them as conflicts at the same path are hard for users to resolve, so move one or both of them aside so that they each get their own path.

Note that in the case of recursive handling (i.e.
call_depth > 0), we can just use the merge base of the two merge bases as the merge result much like we do with modify/delete conflicts, binary files, conflicting submodule values, and so on.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).

When to use static classes in C#

I wrote my thoughts of static classes in an earlier Stack Overflow answer: Class with single method -- best approach?

I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.

Polymorphism

Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.

Interface woes

Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.

Testing

This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.

Fosters blobs

As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.

Parameter creep

To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.

Demanding consumers to create an instance of classes for no reason

One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();

Only a Sith deals in absolutes

Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.

Standards, standards, standards!

Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.

On design patterns: When should I use the singleton?

It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.

In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.

Most efficient way to check for DBNull and then assign to a variable?

Not that I've done this, but you could get around the double indexer call and still keep your code clean by using a static / extension method.

Ie.

public static IsDBNull<T>(this object value, T default)
{
    return (value == DBNull.Value)
        ? default
        : (T)value;
}

public static IsDBNull<T>(this object value)
{
    return value.IsDBNull(default(T));
}

Then:

IDataRecord record; // Comes from somewhere

entity.StringProperty = record["StringProperty"].IsDBNull<string>(null);
entity.Int32Property = record["Int32Property"].IsDBNull<int>(50);

entity.NoDefaultString = record["NoDefaultString"].IsDBNull<string>();
entity.NoDefaultInt = record["NoDefaultInt"].IsDBNull<int>();

Also has the benefit of keeping the null checking logic in one place. Downside is, of course, that it's an extra method call.

Just a thought.

Quicksort: Choosing the pivot

Don't try and get too clever and combine pivoting strategies. If you combined median of 3 with random pivot by picking the median of the first, last and a random index in the middle, then you'll still be vulnerable to many of the distributions which send median of 3 quadratic (so its actually worse than plain random pivot)

E.g a pipe organ distribution (1,2,3...N/2..3,2,1) first and last will both be 1 and the random index will be some number greater than 1, taking the median gives 1 (either first or last) and you get an extermely unbalanced partitioning.

Why not use tables for layout in HTML?

It doesn't have to be a war. Harmony is possible.

Use one table for the overall layout and divs inside it.

<table> 
    <tr><td colspan="3"><div>Top content</div></td></tr>
    <tr> 
        <td><div>Left navigation</div></td> 
        <td><div>Main content</div></td> 
        <td><div>Right navigation</div></td> 
    </tr>
    <tr><td colspan="3"><div>Bottom content</div></td></tr>
</table>

Look - no nested tables.

I have read so many articles on how to achieve this with divs but have never found anything that works every time with no issues.

Divs are great once you have the overall structure but quite frankly, fluid header/footer and three fluid columns is a total pain in divs. Divs weren't designed for fluidity so why use them?

Note that this approach will give you 100 % CSS compliance at link text

When should you use a class vs a struct in C++?

There are lots of misconceptions in the existing answers.

Both class and struct declare a class.

Yes, you may have to rearrange your access modifying keywords inside the class definition, depending on which keyword you used to declare the class.

But, beyond syntax, the only reason to choose one over the other is convention/style/preference.

Some people like to stick with the struct keyword for classes without member functions, because the resulting definition "looks like" a simple structure from C.

Similarly, some people like to use the class keyword for classes with member functions and private data, because it says "class" on it and therefore looks like examples from their favourite book on object-oriented programming.

The reality is that this completely up to you and your team, and it'll make literally no difference whatsoever to your program.

The following two classes are absolutely equivalent in every way except their name:

struct Foo
{
   int x;
};

class Bar
{
public:
   int x;
};

You can even switch keywords when redeclaring:

class Foo;
struct Bar;

(although this breaks Visual Studio builds due to non-conformance, so that compiler will emit a warning when you do this.)

and the following expressions both evaluate to true:

std::is_class<Foo>::value
std::is_class<Bar>::value

Do note, though, that you can't switch the keywords when redefining; this is only because (per the one-definition rule) duplicate class definitions across translation units must "consist of the same sequence of tokens". This means you can't even exchange const int member; with int const member;, and has nothing to do with the semantics of class or struct.

What's the difference between a temp table and table variable in SQL Server?

There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.

As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)

Some points to consider when choosing between them:

  • Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.

  • Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) SQL 2014 has non-unique indexes too.

  • Table variables don't participate in transactions and SELECTs are implicitly with NOLOCK. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!

  • Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.

  • You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.

  • You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).

  • Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.

  • Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.

  • Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

Some further reading:

cannot connect to pc-name\SQLEXPRESS

Use (LocalDB)\MSSQLLocalDB as the server name

Angular File Upload

Very easy and fastest method is using ng2-file-upload.

Install ng2-file-upload via npm. npm i ng2-file-upload --save

At first import module in your module.

import { FileUploadModule } from 'ng2-file-upload';

Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]

Markup:

<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>

In your commponent ts:

import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });

It`is simplest usage of this. To know all power of this see demo

How do I disable a Button in Flutter?

I like to use flutter_mobx for this and work on the state.

Next I use an observer:

Container(child: Observer(builder: (_) {
  var method;
  if (!controller.isDisabledButton) method = controller.methodController;
  return RaiseButton(child: Text('Test') onPressed: method);
}));

On the Controller:

@observable
bool isDisabledButton = true;

Then inside the control you can manipulate this variable as you want.

Refs.: Flutter mobx

Escaping ampersand character in SQL string

I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.

SELECT 'Hello ' '&' ' World';

Hello & World

You're welcome ;)

Difference between Divide and Conquer Algo and Dynamic Programming

I think of Divide & Conquer as an recursive approach and Dynamic Programming as table filling.

For example, Merge Sort is a Divide & Conquer algorithm, as in each step, you split the array into two halves, recursively call Merge Sort upon the two halves and then merge them.

Knapsack is a Dynamic Programming algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.

What is the difference between const int*, const int * const, and int const *?

The const with the int on either sides will make pointer to constant int:

const int *ptr=&i;

or:

int const *ptr=&i;

const after * will make constant pointer to int:

int *const ptr=&i;

In this case all of these are pointer to constant integer, but none of these are constant pointer:

 const int *ptr1=&i, *ptr2=&j;

In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:

int const *ptr1=&i, *const ptr2=&j;

SPAN vs DIV (inline-block)

I think it will help you to understand the basic differences between Inline-Elements (e.g. span) and Block-Elements (e.g. div), in order to understand why "display: inline-block" is so useful.

Problem: inline elements (e.g. span, a, button, input etc.) take "margin" only horizontally (margin-left and margin-right) on, not vertically. Vertical spacing works only on block elements (or if "display:block" is set)

Solution: Only through "display: inline-block" will also take the vertical distance (top and bottom). Reason: Inline element Span, behaves now like a block element to the outside, but like an inline element inside

Here Code Examples:

_x000D_
_x000D_
 /* Inlineelement */

        div,
        span {
            margin: 30px;
        }

        span {
            outline: firebrick dotted medium;
            background-color: antiquewhite;
        }

        span.mitDisplayBlock {
            background: #a2a2a2;
            display: block;
            width: 200px;
            height: 200px;
        }

        span.beispielMargin {
            margin: 20px;
        }

        span.beispielMarginDisplayInlineBlock {
            display: inline-block;
        }

        span.beispielMarginDisplayInline {
            display: inline;
        }

        span.beispielMarginDisplayBlock {
            display: block;
        }

        /* Blockelement */

        div {
            outline: orange dotted medium;
            background-color: deepskyblue;
        }

        .paddingDiv {
            padding: 20px;
            background-color: blanchedalmond;
        }

        .marginDivWrapper {
            background-color: aliceblue;

        }

        .marginDiv {
            margin: 20px;
            background-color: blanchedalmond;
        }
    </style>
    <style>
        /* Nur für das w3school Bild */

        #w3_DIV_1 {
            bottom: 0px;
            box-sizing: border-box;
            height: 391px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 913.984px;
            perspective-origin: 456.984px 195.5px;
            transform-origin: 456.984px 195.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
            transition: all 0.25s ease-in-out 0s;
        }

        /*#w3_DIV_1*/

        #w3_DIV_1:before {
            bottom: 349.047px;
            box-sizing: border-box;
            content: '"Margin"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 6.95312px;
            width: 909.984px;
            perspective-origin: 454.984px 15.5px;
            transform-origin: 454.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_1:before*/

        #w3_DIV_2 {
            bottom: 0px;
            box-sizing: border-box;
            color: black;
            height: 297px;
            left: 0px;
            position: relative;
            right: 0px;
            text-decoration: none solid rgb(255, 255, 255);
            text-size-adjust: 100%;
            top: 0px;
            width: 819.984px;
            column-rule-color: rgb(255, 255, 255);
            perspective-origin: 409.984px 148.5px;
            transform-origin: 409.984px 148.5px;
            caret-color: rgb(255, 255, 255);
            background: rgb(76, 175, 80) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 0px none rgb(255, 255, 255);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            outline: rgb(255, 255, 255) none 0px;
            padding: 45px;
        }

        /*#w3_DIV_2*/

        #w3_DIV_2:before {
            bottom: 258.578px;
            box-sizing: border-box;
            content: '"Border"';
            display: block;
            height: 31px;
            left: 0px;
            position: absolute;
            right: 0px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.42188px;
            width: 819.984px;
            perspective-origin: 409.984px 15.5px;
            transform-origin: 409.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_2:before*/

        #w3_DIV_3 {
            bottom: 0px;
            box-sizing: border-box;
            height: 207px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 729.984px;
            perspective-origin: 364.984px 103.5px;
            transform-origin: 364.984px 103.5px;
            background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 45px;
        }

        /*#w3_DIV_3*/

        #w3_DIV_3:before {
            bottom: 168.344px;
            box-sizing: border-box;
            content: '"Padding"';
            display: block;
            height: 31px;
            left: 3.64062px;
            position: absolute;
            right: -3.64062px;
            text-align: center;
            text-size-adjust: 100%;
            top: 7.65625px;
            width: 729.984px;
            perspective-origin: 364.984px 15.5px;
            transform-origin: 364.984px 15.5px;
            font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
        }

        /*#w3_DIV_3:before*/

        #w3_DIV_4 {
            bottom: 0px;
            box-sizing: border-box;
            height: 117px;
            left: 0px;
            position: relative;
            right: 0px;
            text-size-adjust: 100%;
            top: 0px;
            width: 639.984px;
            perspective-origin: 319.984px 58.5px;
            transform-origin: 319.984px 58.5px;
            background: rgb(191, 201, 101) none repeat scroll 0% 0% / auto padding-box border-box;
            border: 2px dashed rgb(187, 187, 187);
            font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
            padding: 20px;
        }

        /*#w3_DIV_4*/

        #w3_DIV_4:before {
            box-sizing: border-box;
            content: '"Content"';
            display: block;
            height: 73px;
            text-align: center;
            text-size-adjust: 100%;
            width: 595.984px;
            perspective-origin: 297.984px 36.5px;
            transform-origin: 297.984px 36.5px;
            font: normal normal 400 normal 21px / 73.5px Lato, sans-serif;
        }

        /*#w3_DIV_4:before*/
_x000D_
   <h1> The Box model - content, padding, border, margin</h1>
    <h2> Inline element - span</h2>
    <span>Info: A span element can not have height and width (not without "display: block"), which means it takes the fixed inline size </span>

    <span class="beispielMargin">
        <b>Problem:</b> inline elements (eg span, a, button, input etc.) take "margin" only vertically (margin-left and margin-right)
        on, not horizontal. Vertical spacing works only on block elements (or if display: block is set) </span>

    <span class="beispielMarginDisplayInlineBlock">
        <b>Solution</b> Only through
        <b> "display: inline-block" </ b> will also take the vertical distance (top and bottom). Reason: Inline element Span,
        behaves now like a block element to the outside, but like an inline element inside</span>

    <span class="beispielMarginDisplayInline">Example: here "display: inline". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayBlock">Example: here "display: block". See the margin with Inspector!</span>

    <span class="beispielMarginDisplayInlineBlock">Example: here "display: inline-block". See the margin with Inspector! </span>

    <span class="mitDisplayBlock">Only with the "Display" -property and "block" -Value in addition, a width and height can be assigned. "span" is then like
        a "div" block element.  </span>

    <h2>Inline-Element - Div</h2>
    <div> A div automatically takes "display: block." </ div>
    <div class = "paddingDiv"> Padding is for padding </ div>

    <div class="marginDivWrapper">
Wrapper encapsulates the example "marginDiv" to clarify the "margin" (distance from inner element "marginDiv" to the text)
        of the outer element "marginDivWrapper". Here 20px;)
        
    <div class = "marginDiv"> margin is for the margins </ div>
        And there, too, 20px;
    </div>

    <h2>w3school sample image </h2>
    source:
    <a href="https://www.w3schools.com/css/css_boxmodel.asp">CSS Box Model</a>
    <div id="w3_DIV_1">
        <div id="w3_DIV_2">
            <div id="w3_DIV_3">
                <div id="w3_DIV_4">
                </div>
            </div>
        </div>
    </div>
_x000D_
_x000D_
_x000D_

How to convert a char array back to a string?

Try this:

CharSequence[] charArray = {"a","b","c"};

for (int i = 0; i < charArray.length; i++){
    String str = charArray.toString().join("", charArray[i]);
    System.out.print(str);
}

How can I get query string values in JavaScript?

There is a nice little url utility for this with some cool sugaring:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

Check out more examples and download here: https://github.com/websanova/js-url#url

bash string compare to multiple correct values

As @Renich suggests (but with an important typo that has not been fixed unfortunately), you can also use extended globbing for pattern matching. So you can use the same patterns you use to match files in command arguments (e.g. ls *.pdf) inside of bash comparisons.

For your particular case you can do the following.

if [[ "${cms}" != @(wordpress|magento|typo3) ]]

The @ means "Matches one of the given patterns". So this is basically saying cms is not equal to 'wordpress' OR 'magento' OR 'typo3'. In normal regular expression syntax @ is similar to just ^(wordpress|magento|typo3)$.

Mitch Frazier has two good articles in the Linux Journal on this Pattern Matching In Bash and Bash Extended Globbing.

For more background on extended globbing see Pattern Matching (Bash Reference Manual).

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Default value in Doctrine

Use:

options={"default":"foo bar"}

and not:

options={"default"="foo bar"}

For instance:

/**
* @ORM\Column(name="foo", type="smallint", options={"default":0})
*/
private $foo

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

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

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

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

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

Virtual/pure virtual explained

A virtual function is a member function that is declared in a base class and that is redefined by derived class. Virtual function are hierarchical in order of inheritance. When a derived class does not override a virtual function, the function defined within its base class is used.

A pure virtual function is one that contains no definition relative to the base class. It has no implementation in the base class. Any derived class must override this function.

Set View Width Programmatically

This code let you fill the banner to the maximum width and keep the ratio. This will only work in portrait. You must recreate the ad when you rotate the device. In landscape you should just leave the ad as is because it will be quite big an blurred.

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
double ratio = ((float) (width))/300.0;
int height = (int)(ratio*50);

AdView adView = new AdView(this,"ad_url","my_ad_key",true,true);
LinearLayout layout = (LinearLayout) findViewById(R.id.testing);
mAdView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,height));
adView.setAdListener(this);
layout.addView(adView);

How do I finish the merge after resolving my merge conflicts?

The first thing I want to make clear is that branch names are just an alias to a specific commit. a commit is what git works off, when you pull, push merge and so forth. Each commit has a unique id.

When you do $ git merge , what is actually happening is git tries to fast forward your current branch to to the commit the referenced branch is on (in other words both branch names point to the same commit.) This scenario is the easiest for git to deal, since there's no new commit. Think of master jumping onto the lilipad your branch is chilling on. It's possible to set the --no-ff flag, in which case git will create a new commit regardless of whether there were any code conflicts.

In a situation where there are code conflicts between the two branches you are trying to merge (usually two branches whose commit history share a common commit in the past), the fast forward won't work. git may still be able to automatically merge the files, so long as the same line wasn't changed by both branches in a conflicting file. in this case, git will merge the conflicting files for you AND automatically commit them. You can preview how git did by doing $ git diff --cached. Or you can pass the --no-commit flag to the merge command, which will leave modified files in your index you'll need to add and commit. But you can $ git diff these files to review what the merge will change.

The third scenario is when there are conflicts git can't automatically resolve. In this case you'll need to manually merge them. In my opinion this is easiest to do with a merge took, like araxis merge or p4merge (free). Either way, you have to do each file one by one. If the merge ever seems to be stuck, use $ git merge --continue, to nudge it along. Git should tell you if it can't continue, and if so why not. If you feel you loused up the merge at some point, you can do $ git merge --abort, and any merging will undo and you can start over. When you're done, each file you merged will be a modified file that needs to be added and committed. You can verify where the files are with $ git status. If you haven't committed the merged files yet. You need to do that to complete the merge. You have to complete the merge or abort the merge before you can switch branches.

Java JDBC - How to connect to Oracle using Service Name instead of SID

You can also specify the TNS name in the JDBC URL as below

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

How to create a date object from string in javascript

You definitely want to use the second expression since months in JS are enumerated from 0.

Also you may use Date.parse method, but it uses different date format:

var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);

How to edit the size of the submit button on a form?

Change height using:

input[type=submit] {
  border: none; /*rewriting standard style, it is necessary to be able to change the size*/
  height: 100px;
  width: 200px
}

How can I know if a branch has been already merged into master?

In order to verify which branches are merged into master you should use these commands:

  • git branch <flag[-r/-a/none]> --merged master list of all branches merged into master.
  • git branch <flag[-r/-a/none]> --merged master | wc -l count number of all branches merged into master.

Flags Are:

  • -a flag - (all) showing remote and local branches
  • -r flag - (remote) showing remote branches only
  • <emptyFlag> - showing local branches only

for example: git branch -r --merged master will show you all remote repositories merged into master.

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

Removing Spaces from a String in C?

That's the easiest I could think of (TESTED) and it works!!

char message[50];
fgets(message, 50, stdin);
for( i = 0, j = 0; i < strlen(message); i++){
        message[i-j] = message[i];
        if(message[i] == ' ')
            j++;
}
message[i] = '\0';

Querying a linked sql server

I use open query to perform this task like so:

select top 1 *
INTO [DATABASE_TO_INSERT_INTO].[dbo].[TABLE_TO_SELECT_INTO]
from openquery(
    [LINKED_SERVER_NAME],
    'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)

The example above uses open query to select data from a database on a linked server into a database of your choosing.

Note: For completeness of reference, you may perform a simple select like so:

select top 1 * from openquery(
    [LINKED_SERVER_NAME],
    'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

Can a website detect when you are using Selenium with chromedriver?

The bot detection I've seen seems more sophisticated or at least different than what I've read through in the answers below.

EXPERIMENT 1:

  1. I open a browser and web page with Selenium from a Python console.
  2. The mouse is already at a specific location where I know a link will appear once the page loads. I never move the mouse.
  3. I press the left mouse button once (this is necessary to take focus from the console where Python is running to the browser).
  4. I press the left mouse button again (remember, cursor is above a given link).
  5. The link opens normally, as it should.

EXPERIMENT 2:

  1. As before, I open a browser and the web page with Selenium from a Python console.

  2. This time around, instead of clicking with the mouse, I use Selenium (in the Python console) to click the same element with a random offset.

  3. The link doesn't open, but I am taken to a sign up page.

IMPLICATIONS:

  • opening a web browser via Selenium doesn't preclude me from appearing human
  • moving the mouse like a human is not necessary to be classified as human
  • clicking something via Selenium with an offset still raises the alarm

Seems mysterious, but I guess they can just determine whether an action originates from Selenium or not, while they don't care whether the browser itself was opened via Selenium or not. Or can they determine if the window has focus? Would be interesting to hear if anyone has any insights.

How to convert the time from AM/PM to 24 hour format in PHP?

$time = '09:15 AM';

$chunks = explode(':', $time);
if (strpos( $time, 'AM') === false && $chunks[0] !== '12') {
    $chunks[0] = $chunks[0] + 12;
} else if (strpos( $time, 'PM') === false && $chunks[0] == '12') {
    $chunks[0] = '00';
}

echo preg_replace('/\s[A-Z]+/s', '', implode(':', $chunks));

Find oldest/youngest datetime object in a list

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

Reload browser window after POST without prompting user to resend POST data

This works too:

window.location.href = window.location.pathname + window.location.search

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

How to show progress bar while loading, using ajax

Here is an example that's working for me with MVC and Javascript in the Razor. The first function calls an action via ajax on my controller and passes two parameters.

        function redirectToAction(var1, var2)
        {
            try{

                var url = '../actionnameinsamecontroller/' + routeId;

                $.ajax({
                    type: "GET",
                    url: url,
                    data: { param1: var1, param2: var2 },
                    dataType: 'html',
                    success: function(){
                    },
                    error: function(xhr, ajaxOptions, thrownError){
                        alert(error);
                    }
                });

            }
            catch(err)
            {
                alert(err.message);
            }
        }

Use the ajaxStart to start your progress bar code.

           $(document).ajaxStart(function(){
            try
            {
                // showing a modal
                $("#progressDialog").modal();

                var i = 0;
                var timeout = 750;

                (function progressbar()
                {
                    i++;
                    if(i < 1000)
                    {
                        // some code to make the progress bar move in a loop with a timeout to 
                        // control the speed of the bar
                        iterateProgressBar();
                        setTimeout(progressbar, timeout);
                    }
                }
                )();
            }
            catch(err)
            {
                alert(err.message);
            }
        });

When the process completes close the progress bar

        $(document).ajaxStop(function(){
            // hide the progress bar
            $("#progressDialog").modal('hide');
        });

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

Is an anchor tag without the href attribute safe?

From an accessibility perspective <a> without a href is not tab-able, all links should be tab-able so add a tabindex='0" if you don't have a href.

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

How do I use InputFilter to limit characters in an EditText in Android?

For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:

class ABCFilter extends LoginFilter.UsernameFilterGeneric {
    public UsernameFilter() {
        super(false); // false prevents not-allowed characters from being appended
    }

    @Override
    public boolean isAllowed(char c) {
        if ('A' <= c && c <= 'C')
            return true;
        if ('a' <= c && c <= 'c')
            return true;

        return false;
    }
}

This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.

Using SELECT result in another SELECT

NewScores is an alias to Scores table - it looks like you can combine the queries as follows:

SELECT 
    ROW_NUMBER() OVER( ORDER BY NETT) AS Rank, 
    Name, 
    FlagImg, 
    Nett, 
    Rounds 
FROM (
    SELECT 
        Members.FirstName + ' ' + Members.LastName AS Name, 
        CASE 
            WHEN MenuCountry.ImgURL IS NULL THEN 
                '~/images/flags/ismygolf.png' 
            ELSE 
                MenuCountry.ImgURL 
        END AS FlagImg, 
        AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett, 
        COUNT(Score.ScoreID) AS Rounds 
    FROM 
        Members 
        INNER JOIN 
        Score NewScores
            ON Members.MemberID = NewScores.MemberID 
        LEFT OUTER JOIN MenuCountry 
            ON Members.Country = MenuCountry.ID 
    WHERE 
        Members.Status = 1 
        AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
    GROUP BY 
        Members.FirstName + ' ' + Members.LastName, 
        MenuCountry.ImgURL
    ) AS Dertbl 
ORDER BY;

Most efficient method to groupby on an array of objects

data = [{id:1, name:'BMW'}, {id:2, name:'AN'}, {id:3, name:'BMW'}, {id:1, name:'NNN'}]
key = 'id'//try by id or name
data.reduce((previous, current)=>{
    previous[current[key]] && previous[current[key]].length != 0 ? previous[current[key]].push(current) : previous[current[key]] = new Array(current)
    return previous;
}, {})

How to use refs in React with Typescript

EDIT: This is no longer the right way to use refs with Typescript. Look at Jeff Bowen's answer and upvote it to increase its visibility.

Found the answer to the problem. Use refs as below inside the class.

refs: {
    [key: string]: (Element);
    stepInput: (HTMLInputElement);
}

Thanks @basarat for pointing in the right direction.

Getting list of files in documents folder

A shorter syntax for SWIFT 3

func listFilesFromDocumentsFolder() -> [String]?
{
    let fileMngr = FileManager.default;

    // Full path to documents directory
    let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path

    // List all contents of directory and return as [String] OR nil if failed
    return try? fileMngr.contentsOfDirectory(atPath:docs)
}

Usage example:

override func viewDidLoad()
{
    print(listFilesFromDocumentsFolder())
}

Tested on xCode 8.2.3 for iPhone 7 with iOS 10.2 & iPad with iOS 9.3

React / JSX Dynamic Component Name

With the introduction of React.lazy, we can now use a true dynamic approach to import the component and render it.

import React, { lazy, Suspense } from 'react';

const App = ({ componentName, ...props }) => {
  const DynamicComponent = lazy(() => import(`./${componentName}`));
    
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ComponentName {...props} />
    </Suspense>
  );
};

This approach makes some assumptions about the file hierarchy of course and can make the code easy to break.

Eclipse Intellisense?

Tony is a pure genius. However to achieve even better auto-completion try setting the triggers to this:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz =.(!+-*/~,[{@#$%^&

(specifically aranged in order of usage for faster performance :)

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

How to view UTF-8 Characters in VIM or Gvim

On Windows gvim just select "Lucida Console" font.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

Cloudfront will cache a file/object until the cache expiry. By default it is 24 hrs. If you have changed this to a large value, then it takes longer.

If you anytime needs to force clear the cache, use the invalidation. It is charged separately.

Another option is to change the URL (object key), so it fetches the new object always.

Git on Windows: How do you set up a mergetool?

i use an app called WinMerge ( http://winmerge.org/ ) info from their manual ( http://manual.winmerge.org/CommandLine.html )

this is the bash script i use from the mergetool directive via .gitconfig

#!/bin/sh
# using winmerge with git
# replaces unix style null files with a newly created empty windows temp file

file1=$1
if [ "$file1" == '/dev/null' ] || [ "$file1" == '\\.\nul' ] || [ ! -e "$file1" ]
    then 
       file1="/tmp/gitnull"
       `echo "">$file1`
fi
file2=$2
if [ "$file2" == '/dev/null' ] || [ "$file2" == '\\.\nul' ] || [ ! -e "$file2" ]
    then 
       file2="/tmp/gitnull"
       `echo "">$file2`
fi
echo diff : $1 -- $2
"C:\Program files (x86)\WinMerge\WinMergeU.exe" -e -ub -dl "Base" -dr "Mine" "$file1" "$file2"

basically the bash accounts for when the result of the diff in an empty file and creates a new temp file in the correct location.

Bash foreach loop

You'll probably want to handle spaces in your file names, abhorrent though they are :-)

So I would opt initially for something like:

pax> cat qq.in
normalfile.txt
file with spaces.doc

pax> sed 's/ /\\ /g' qq.in | xargs -n 1 cat
<<contents of 'normalfile.txt'>>
<<contents of 'file with spaces.doc'>>

pax> _

Defining static const integer members in class definition

Another way to do this, for integer types anyway, is to define constants as enums in the class:

class test
{
public:
    enum { N = 10 };
};

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

How to show multiline text in a table cell

Wrap the content in a <pre> (pre-formatted text) tag

<pre>hello ,
my name is x.</pre>

How can I get session id in php and show it?

Before getting a session id you need to start a session and that is done by using: session_start() function.

Now that you have started a session you can get a session id by using: session_id().

/* A small piece of code for setting, displaying and destroying session in PHP */

<?php
session_start();
$r=session_id();

/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */

/* now registering a session for an authenticated user */
$_SESSION['username']=$username;

/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];


/* now destroying the session id */

if(isset($_SESSION['username']))
{
    $_SESSION=array();
    unset($_SESSION);
    session_destroy();
    echo "session destroyed...";
}
?>

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

og:type and valid values : constantly being parsed as og:type=website

As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type

apps.saves An action representing someone saving an app to try later.

article This object represents an article on a website. It is the preferred type for blog posts and news stories.

book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines

books.author This object type represents a single author of a book.

books.book This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books

books.genre This object type represents the genre of a book or publication.

books.quotes
Returns no data as of April 4, 2018.

An action representing someone quoting from a book.

books.rates
Returns no data as of April 4, 2018.

An action representing someone rating a book.

books.reads
Returns no data as of April 4, 2018.

An action representing someone reading a book.

books.wants_to_read
Returns no data as of April 4, 2018.

An action representing someone wanting to read a book.

business.business This object type represents a place of business that has a location, operating hours and contact information.

fitness.bikes
Returns no data as of April 4, 2018.

An action representing someone cycling a course.

fitness.course This object type represents the user's activity contributing to a particular run, walk, or bike course.

fitness.runs
Returns no data as of April 4, 2018.

An action representing someone running a course.

fitness.walks
Returns no data as of April 4, 2018.

An action representing someone walking a course.

game.achievement This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has a game:points value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.

games.achieves An action representing someone reaching a game achievement.

games.celebrate An action representing someone celebrating a victory in a game.

games.plays An action representing someone playing a game. Stories for this action will only appear in the activity log.

games.saves An action representing someone saving a game.

music.album This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.

music.listens
Returns no data as of April 4, 2018.

An action representing someone listening to a song, album, radio station, playlist or musician

music.playlist This object type represents a music playlist, an ordered collection of songs from a collection of artists.

music.playlists
Returns no data as of April 4, 2018.

An action representing someone creating a playlist.

music.radio_station This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.

music.song This object type represents a single song.

news.publishes An action representing someone publishing a news article.

news.reads
Returns no data as of April 4, 2018.

An action representing someone reading a news article.

og.follows An action representing someone following a Facebook user

og.likes An action representing someone liking any object.

pages.saves An action representing someone saving a place.

place This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.

product This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.

product.group This object type represents a group of product items.

product.item This object type represents a product item.

profile This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. The fb:profile_id field associates the object with a Facebook user.

restaurant.menu This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.

restaurant.menu_item This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.

restaurant.menu_section This object type represents a section in a restaurant's menu. A section contains multiple menu items.

restaurant.restaurant This object type represents a restaurant at a specific location.

restaurant.visited An action representing someone visiting a restaurant.

restaurant.wants_to_visit An action representing someone wanting to visit a restaurant

sellers.rates An action representing a commerce seller has been given a rating.

video.episode This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.

video.movie This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.

video.other This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use the video.movie or video.tv_show object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)

video.rates
Returns no data as of April 4, 2018.

An action representing someone rating a movie, TV show, episode or another piece of video content.

video.tv_show This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use the video.episode object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)

video.wants_to_watch
Returns no data as of April 4, 2018.

An action representing someone wanting to watch video content.

video.watches
Returns no data as of April 4, 2018.

An action representing someone watching video content.

Angular 2 optional route parameter

I can't comment, but in reference to: Angular 2 optional route parameter

an update for Angular 6:

import {map} from "rxjs/operators"

constructor(route: ActivatedRoute) {
  let paramId = route.params.pipe(map(p => p.id));

  if (paramId) {
    ...
  }
}

See https://angular.io/api/router/ActivatedRoute for additional information on Angular6 routing.

How do I obtain a list of all schemas in a Sql Server database

You can also query the INFORMATION_SCHEMA.SCHEMATA view:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA

I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:

Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

Ironically, this is immediately preceded by this note:

Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.

HashMap: One Key, multiple Values

Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap

HashMap<String, MyObject>

class MyObject {
public String value1;
public int value2;
public List<String> value3;
}

Eclipse Bug: Unhandled event loop exception No more handles

Wow, what a variety of causes of these error messages! I'll throw one more out:

In my case, Eclipse 4.17 on Ubuntu 16.04LTS was showing these messages for multiple operations. It turns out that 16.04LTS has GTK 3.18, but Eclipse 4.17 requires GTK 3.20. Updating GTK (https://askubuntu.com/questions/933010/how-to-upgrade-gtk-3-18-to-3-20-on-ubuntu-16-04) made the error messages go away.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Is there a good Valgrind substitute for Windows?

I used Insure++ which does excellent job in finding c++ memory leaks/corruptions and many other bugs like uninitialized variables, pointer errors, strings etc., It also does visual "Code coverage" and run time memory usage etc.. which give more confident on your code.. You can try it for trail version..

Is there a standardized method to swap two variables in Python?

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Python docs: Evaluation order

That means the following for the expression a,b = b,a :

  • The right-hand side b,a is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during the execution of the program.
  • Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
  • Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
  • As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier a be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b)
    and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a)

This mechanism has effectively swapped the objects assigned to the identifiers a and b

So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.

Run two async tasks in parallel and collect results in .NET 4.5

async Task<int> LongTask1() { 
  ...
  return 0; 
}

async Task<int> LongTask2() { 
  ...
  return 1; 
}

...
{
   Task<int> t1 = LongTask1();
   Task<int> t2 = LongTask2();
   await Task.WhenAll(t1,t2);
   //now we have t1.Result and t2.Result
}

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

Ultimate solution (works in SSRS 2012 too!)

Append the following script to the following file (on the SSRS Server)
C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js

function pageLoad() {    
    var element = document.getElementById("ctl31_ctl10");
    if (element) 
    {
        element.style.overflow = "visible"; 
    }
}

Note: As azzlak noted, the div's name isn't always ctl31_ctl10. For SQL 2012 tryctl32_ctl09 and for 2008 R2 try ctl31_ctl09. If this solution doesn't work, look at the HTML from your browser to see if the script has worked properly changing the overflow:auto property to overflow:visible.


Solution for ReportViewer control

Insert into .aspx page (or into a linked .css file, if available) this style line

#reportViewer_ctl09 {
  overflow:visible !important;
 }

Reason

Chrome and Safari render overflow:auto in different way respect to IE.

SSRS HTML is QuirksMode HTML and depends on IE 5.5 bugs. Non-IE browsers don't have the IE quirksmode and therefore render the HTML correctly

The HTML page produced by SSRS 2008 R2 reports contain a div which has overflow:auto style, and it turns report into an invisible report.

<div id="ctl31_ctl10" style="height:100%;width:100%;overflow:auto;position:relative;">

I can see reports on Chrome by manually changing overflow:auto to overflow:visible in the produced webpage using Chrome's Dev Tools (F12).


I love Tim's solution, it's easy and working.

But there is still a problem: any time the user change parameters (my reports use parameters!) AJAX refreshes the div, the overflow:auto tag is rewritten, and no script changes it.

This technote detail explains what is the problem:

This happens because in a page built with AJAX panels, only the AJAX panels change their state, without refreshing the whole page. Consequently, the OnLoad events you applied on the <body> tag are only fired once: the first time your page loads. After that, changing any of the AJAX panels will not trigger these events anymore.

User einarq suggested this solution:

Another option is to rename your function to pageLoad. Any functions with this name will be called automatically by asp.net ajax if it exists on the page, also after each partial update. If you do this you can also remove the onload attribute from the body tag

So wrote the improved script that is shown in the solution.

What strategies and tools are useful for finding memory leaks in .NET?

one of the best tools I used its DotMemory.you can use this tool as an extension in VS.after run your app you can analyze every part of memory(by Object, NameSpace, etc) that your app use and take some snapshot of that, Compare it with other SnapShots. DotMemory

enumerate() for dictionary in python

You may find it useful to include index inside key:

d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}

Output:

{(0, 'a'): True, (1, 'b'): False}

Android Fragment onClick button Method

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
    // Inflate the layout for this fragment

    txt_name = (TextView) view.findViewById(R.id.name);
    txt_usranme = (TextView) view.findViewById(R.id.surname);
    txt_number = (TextView) view.findViewById(R.id.number);
    txt_province = (TextView) view.findViewById(R.id.province);
    txt_write = (EditText) view.findViewById(R.id.editText_write);
    txt_show1 = (Button) view.findViewById(R.id.buttonShow1);

    txt_show1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("Onclick","Onclick");

            txt_show1.setVisibility(View.INVISIBLE);
            txt_name.setVisibility(View.VISIBLE);
            txt_usranme.setVisibility(View.VISIBLE);
            txt_number.setVisibility(View.VISIBLE);
            txt_province.setVisibility(View.VISIBLE);
        }
    });
    return view;
}

You OK !!!!

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

Installing Python 3 on RHEL

You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here

This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6

Search for a string in all tables, rows and columns of a DB

To "find where the data I get comes from", you can start SQL Profiler, start your report or application, and you will see all the queries issued against your database.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Convert List to Pandas Dataframe Column

if your list looks like this: [1,2,3] you can do:

lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df

to get this:

    col1    col2    col3
0   1       2       3

alternatively you can create a column as follows:

import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df

to get this:

  col1
0   1
1   2
2   3

Rotating videos with FFmpeg

For me it works like this

Rotate clockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=1" "path_output_video.mp4"

Rotate counterclockwise

 ffmpeg -i "path_source_video.mp4" -filter:v "transpose=0,transpose=1,transpose=0" -acodec copy "path_output_video.mp4"

the package I use zeranoe

How do I install the babel-polyfill library?

The Babel docs describe this pretty concisely:

Babel includes a polyfill that includes a custom regenerator runtime and core.js.

This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.

Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).

If you're using a tool like gulp-babel or babel-loader, you need to also install the babel package itself to use the polyfill.

Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:

import 'babel/polyfill';

How to get current local date and time in Kotlin

checkout these easy to use Kotlin extensions for date format

fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
    return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}

fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

Is there a short cut for going back to the beginning of a file by vi editor?

using :<line number> you can navigate to any line, thus :1 takes you to the first line.

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

using javascript to detect whether the url exists before display in iframe

You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side

$.get(
   yourURL,
   function(data, textStatus, jqXHR) {
      //load the iframe here...
   }
);

Replacement for "rename" in dplyr

The next version of dplyr will support an improved version of select that also incorporates renaming:

> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
                  disp2
Mazda RX4         160
Mazda RX4 Wag     160
Datsun 710        108
Hornet 4 Drive    258
Hornet Sportabout 360
Valiant           225
> changes( mtcars, mtcars2 )
Changed variables:
      old         new
disp  0x105500400
disp2             0x105500400

Changed attributes:
      old         new
names 0x106d2cf50 0x106d28a98

Maven: add a dependency to a jar by relative path

Using the system scope. ${basedir} is the directory of your pom.

<dependency>
    <artifactId>..</artifactId>
    <groupId>..</groupId>
    <scope>system</scope>
    <systemPath>${basedir}/lib/dependency.jar</systemPath>
</dependency>

However it is advisable that you install your jar in the repository, and not commit it to the SCM - after all that's what maven tries to eliminate.

How to create a CPU spike with a bash command

You can also do

dd if=/dev/zero of=/dev/null

To run more of those to put load on more cores, try to fork it:

fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd

Repeat the command in the curly brackets as many times as the number of threads you want to produce (here 4 threads). Simple enter hit will stop it (just make sure no other dd is running on this user or you kill it too).

Shell script not running, command not found

I'm new to shell scripting too, but I had this same issue. Make sure at the end of your script you have a blank line. Otherwise it won't work.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Extracting specific columns in numpy array

I assume you wanted columns 1 and 9?

To select multiple columns at once, use

X = data[:, [1, 9]]

To select one at a time, use

x, y = data[:, 1], data[:, 9]

With names:

data[:, ['Column Name1','Column Name2']]

You can get the names from data.dtype.names

Deleting a file in VBA

In VB its normally Dir to find the directory of the file. If it's not blank then it exists and then use Kill to get rid of the file.

test = Dir(Filename)
If Not test = "" Then
    Kill (Filename)
End If

Hive load CSV with commas in quoted fields

Add a backward slash in FIELDS TERMINATED BY '\;'

For Example:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

I have tested it, and it worked.

How to use the "required" attribute with a "radio" input field

Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

_x000D_
_x000D_
fieldset { 
  display: block;
  margin-left: 0;
  margin-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  border: none;
}
body {font-size: 15px; font-family: serif;}
input {
  background: transparent;
  border-radius: 0px;
  border: 1px solid black;
  padding: 5px;
  box-shadow: none!important;
  font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
  opacity: 0; 
  position: absolute; 
  pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
  display: block;
  border: 1px solid black;
  border-left: 0;
  padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
  <div>
    <label for="name">Name (optional)</label>
    <input id="name" type="text" name="name">
  </div>
  <fieldset>
  <legend>Gender</legend>
  <div class="checkboxes">
    <label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
    <label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
    <label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
  </div>
  </fieldset>
  <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

OOP vs Functional Programming vs Procedural

All of them are good in their own ways - They're simply different approaches to the same problems.

In a purely procedural style, data tends to be highly decoupled from the functions that operate on it.

In an object oriented style, data tends to carry with it a collection of functions.

In a functional style, data and functions tend toward having more in common with each other (as in Lisp and Scheme) while offering more flexibility in terms of how functions are actually used. Algorithms tend also to be defined in terms of recursion and composition rather than loops and iteration.

Of course, the language itself only influences which style is preferred. Even in a pure-functional language like Haskell, you can write in a procedural style (though that is highly discouraged), and even in a procedural language like C, you can program in an object-oriented style (such as in the GTK+ and EFL APIs).

To be clear, the "advantage" of each paradigm is simply in the modeling of your algorithms and data structures. If, for example, your algorithm involves lists and trees, a functional algorithm may be the most sensible. Or, if, for example, your data is highly structured, it may make more sense to compose it as objects if that is the native paradigm of your language - or, it could just as easily be written as a functional abstraction of monads, which is the native paradigm of languages like Haskell or ML.

The choice of which you use is simply what makes more sense for your project and the abstractions your language supports.

How to allow access outside localhost

you can also introspect all HTTP traffic running over your tunnels using ngrok , then you can expose using ngrok http --host-header=rewrite 4200

Check OS version in Swift?

For iOS, try:

var systemVersion = UIDevice.current.systemVersion

For OS X, try:

var systemVersion = NSProcessInfo.processInfo().operatingSystemVersion

If you just want to check if the users is running at least a specific version, you can also use the following Swift 2 feature which works on iOS and OS X:

if #available(iOS 9.0, *) {
    // use the feature only available in iOS 9
    // for ex. UIStackView
} else {
    // or use some work around
}

BUT it is not recommended to check the OS version. It is better to check if the feature you want to use is available on the device than comparing version numbers. For iOS, as mentioned above, you should check if it responds to a selector; eg.:

if (self.respondsToSelector(Selector("showViewController"))) {
    self.showViewController(vc, sender: self)
} else {
    // some work around
}

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

Find out if string ends with another string in C++

I know the question's for C++, but if anyone needs a good ol' fashioned C function to do this:


/*  returns 1 iff str ends with suffix  */
int str_ends_with(const char * str, const char * suffix) {

  if( str == NULL || suffix == NULL )
    return 0;

  size_t str_len = strlen(str);
  size_t suffix_len = strlen(suffix);

  if(suffix_len > str_len)
    return 0;

  return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len );
}

changing textbox border colour using javascript

Add an onchange event to your input element:

<input type="text" id="fName" value="" onchange="fName_Changed(this)" />

Javascript:

function fName_Changed(fName)
{
    fName.style.borderColor = (fName.value != 'correct text') ? "#FF0000"; : fName.style.borderColor="";
}

How do check if a PHP session is empty?

The best practice is to check if the array key exists using the built-in array_key_exists function.

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

When are static variables initialized?

Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

How to get current user who's accessing an ASP.NET application?

If you're using membership you can do: Membership.GetUser()

Your code is returning the Windows account which is assigned with ASP.NET.

Additional Info Edit: You will want to include System.Web.Security

using System.Web.Security

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

Are there any standard exit status codes in Linux?

None of the older answers describe exit status 2 correctly. Contrary to what they claim, status 2 is what your command line utilities actually return when called improperly. (Yes, an answer can be nine years old, have hundreds of upvotes, and still be wrong.)

Here is the real, long-standing exit status convention for normal termination, i.e. not by signal:

  • Exit status 0: success
  • Exit status 1: "failure", as defined by the program
  • Exit status 2: command line usage error

For example, diff returns 0 if the files it compares are identical, and 1 if they differ. By long-standing convention, unix programs return exit status 2 when called incorrectly (unknown options, wrong number of arguments, etc.) For example, diff -N, grep -Y or diff a b c will all result in $? being set to 2. This is and has been the practice since the early days of Unix in the 1970s.

The accepted answer explains what happens when a command is terminated by a signal. In brief, termination due to an uncaught signal results in exit status 128+[<signal number>. E.g., termination by SIGINT (signal 2) results in exit status 130.

Notes

  1. Several answers define exit status 2 as "Misuse of bash builtins". This applies only when bash (or a bash script) exits with status 2. Consider it a special case of incorrect usage error.

  2. In sysexits.h, mentioned in the most popular answer, exit status EX_USAGE ("command line usage error") is defined to be 64. But this does not reflect reality: I am not aware of any common Unix utility that returns 64 on incorrect invocation (examples welcome). Careful reading of the source code reveals that sysexits.h is aspirational, rather than a reflection of true usage:

     *    This include file attempts to categorize possible error
     *    exit statuses for system programs, notably delivermail
     *    and the Berkeley network.
    
     *    Error numbers begin at EX__BASE [64] to reduce the possibility of 
     *    clashing with oth­er exit statuses that random programs may 
     *    already return. 
    

    In other words, these definitions do not reflect the common practice at the time (1993) but were intentionally incompatible with it. More's the pity.

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

What's the difference between a proxy server and a reverse proxy server?

Difference between Proxy server (also called forward proxy) and Reverse Proxy Server depends on the point of reference.

Technically, both are exactly the same. Both serve the same purpose of transmitting data to a destination on behalf of a source.

The difference lies in 'on whose behalf is the proxy server acting / who is the proxy server representing?'

If the proxy server is forwarding requests to internet server on behalf of the end users (Example: students in a college accessing internet through college proxy server.), then the proxy is called 'Forward proxy' or simply 'Proxy'.

If the proxy server is responding to incoming requests, on behalf of a server, then the proxy is called 'Reverse Proxy', as it is working in the reverse direction, from the point of view of the end user.

Some Examples of Reverse proxies:

  1. Load balancer in front of web servers acts as a reverse-proxy on behalf of the actual web servers.
  2. API gateway
  3. Free Website hosting services like (facebook pages / blog page servers) are also reverse proxies. The actual content may be in some web server, but the outside world knows it through specific url advertised by reverse-proxy.

Use of forward proxy:

  1. Monitor all outbound internet connections from an organization
  2. Apply security policies on internet browsing and block malicious content from being downloaded
  3. Block access to specific websites

Use of Reverse proxy:

  1. Present friendly URL for a website
  2. Perform load balancing across multiple web servers
  3. Apply security policy and protect actual web servers from attacks

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

PHP 7+

As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :

echo !empty($address['street2']) ?? 'Empty';

incompatible character encodings: ASCII-8BIT and UTF-8

I have a suspicion that you either copy/pasted a part of your Haml template into the file, or you're working with a non-Unicode/non-UTF-8 friendly editor.

See if you can recreate that file from the scratch in a UTF-8 friendly editor. There are plenty for any platform and see whether this fixes your problem. Start by erasing the line with #content and retyping it manually.

Echoing the last command run in Bash?

The command history is an interactive feature. Only complete commands are entered in the history. For example, the case construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history built-in (nor printing it through shell expansion (!:p)) does what you seem to want, which is to print invocations of simple commands.

The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

Furthermore, if you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x.

How to make fixed header table inside scrollable div?

Some of these answers seem unnecessarily complex. Make your tbody:

display: block; height: 300px; overflow-y: auto

Then manually set the widths of each column so that the thead and tbody columns are the same width. Setting the table's style="table-layout: fixed" may also be necessary.

Java: recommended solution for deep cloning/copying an instance

Use XStream toXML/fromXML in memory. Extremely fast and has been around for a long time and is going strong. Objects don't need to be Serializable and you don't have use reflection (although XStream does). XStream can discern variables that point to the same object and not accidentally make two full copies of the instance. A lot of details like that have been hammered out over the years. I've used it for a number of years and it is a go to. It's about as easy to use as you can imagine.

new XStream().toXML(myObj)

or

new XStream().fromXML(myXML)

To clone,

new XStream().fromXML(new XStream().toXML(myObj))

More succinctly:

XStream x = new XStream();
Object myClone = x.fromXML(x.toXML(myObj));

Decimal or numeric values in regular expression validation

I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:

function isNumber(v) {
  // [0-9]* Zero or more digits between 0 and 9  (This allows .25 to be considered valid.)
  // ()? Matches 0 or 1 things in the parentheses.  (Allows for an optional decimal point)
  // Decimal point escaped with \.
  // If a decimal point does exist, it must be followed by 1 or more digits [0-9]
  // \d and [0-9] are equivalent 
  // ^ and $ anchor the endpoints so tthe whole string must match.
  return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}

Where my trim() method is

String.prototype.trim = function() {
  return this.replace(/(^\s*|\s*$)/g, "");
};

Matthew DesVoigne

Password encryption/decryption code in .NET

First create a class like:

public class Encryption
    { 
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }

**In Controller **

add reference for this encryption class:

using testdemo.Models

public ActionResult Index() {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string text)
        {
            if (Request["txtEncrypt"] != null)
            {
                string getEncryptionCode = Request["txtEncrypt"];
                string DecryptCode = Encryption.Decrypt(HttpUtility.UrlDecode(getEncryptionCode));
                ViewBag.GetDecryptCode = DecryptCode;
                return View();
            }
            else {
                string getDecryptCode = Request["txtDecrypt"];
                string EncryptionCode = HttpUtility.UrlEncode(Encryption.Encrypt(getDecryptCode));
                ViewBag.GetEncryptionCode = EncryptionCode;
                return View();
            }

        }

In View

<h2>Decryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Encryption Code</th>
            <td><input type="text" id="txtEncrypt" name="txtEncrypt" placeholder="Enter Encryption Code" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetDecryptCode</span>
            </td>
        </tr>
        <tr>
                <td colspan="2">
                    <input type="submit" id="btnEncrypt" name="btnEncrypt"value="Decrypt to Encrypt code" />
                </td>
            </tr>
    </table>
}
    <br />
    <br />
    <br />
    <h2>Encryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Decryption Code</th>
            <td><input type="text" id="txtDecrypt" name="txtDecrypt" placeholder="Enter Decryption Code" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetEncryptionCode</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" id="btnDecryt" name="btnDecryt" value="Encrypt to Decrypt code" />
            </td>
        </tr>
    </table>
}

javascript return true or return false when and how to use it?

Your code makes no sense, maybe because it's out of context.

If you mean code like this:

$('a').click(function () {
    callFunction();
    return false;
});

The return false will return false to the click-event. That tells the browser to stop following events, like follow a link. It has nothing to do with the previous function call. Javascript runs from top to bottom more or less, so a line cannot affect a previous line.

Getting the length of two-dimensional array

Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size. so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.

Hope that helps..:)

Putting a simple if-then-else statement on one line

Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.

if i > 3: print("We are done.")

or

field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural)) 

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

cursor.fetchall() vs list(cursor) in Python

cursor.fetchall() and list(cursor) are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:

for result in cursor:

This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).

Floating point comparison functions for C#

I think your second option is the best bet. Generally in floating-point comparison you often only care that one value is within a certain tolerance of another value, controlled by the selection of epsilon.

Bootstrap 4, How do I center-align a button?

Use text-center class in the parent container for Bootstrap 4

Modify request parameter with servlet filter

Based on all your remarks here is my proposal that worked for me :

 private final class CustomHttpServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> queryParameterMap;
    private final Charset requestEncoding;

    public CustomHttpServletRequest(HttpServletRequest request) {
        super(request);
        queryParameterMap = getCommonQueryParamFromLegacy(request.getParameterMap());

        String encoding = request.getCharacterEncoding();
        requestEncoding = (encoding != null ? Charset.forName(encoding) : StandardCharsets.UTF_8);
    }

    private final Map<String, String[]> getCommonQueryParamFromLegacy(Map<String, String[]> paramMap) {
        Objects.requireNonNull(paramMap);

        Map<String, String[]> commonQueryParamMap = new LinkedHashMap<>(paramMap);

        commonQueryParamMap.put(CommonQueryParams.PATIENT_ID, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_ID)[0] });
        commonQueryParamMap.put(CommonQueryParams.PATIENT_BIRTHDATE, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_BIRTHDATE)[0] });
        commonQueryParamMap.put(CommonQueryParams.KEYWORDS, new String[] { paramMap.get(LEGACY_PARAM_STUDYTYPE)[0] });

        String lowerDateTime = null;
        String upperDateTime = null;

        try {
            String studyDateTime = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("dd-MM-yyyy").parse(paramMap.get(LEGACY_PARAM_STUDY_DATE_TIME)[0]));

            lowerDateTime = studyDateTime + "T23:59:59";
            upperDateTime = studyDateTime + "T00:00:00";

        } catch (ParseException e) {
            LOGGER.error("Can't parse StudyDate from query parameters : {}", e.getLocalizedMessage());
        }

        commonQueryParamMap.put(CommonQueryParams.LOWER_DATETIME, new String[] { lowerDateTime });
        commonQueryParamMap.put(CommonQueryParams.UPPER_DATETIME, new String[] { upperDateTime });

        legacyQueryParams.forEach(commonQueryParamMap::remove);
        return Collections.unmodifiableMap(commonQueryParamMap);

    }

    @Override
    public String getParameter(String name) {
        String[] params = queryParameterMap.get(name);
        return params != null ? params[0] : null;
    }

    @Override
    public String[] getParameterValues(String name) {
        return queryParameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
            return queryParameterMap; // unmodifiable to uphold the interface contract.
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(queryParameterMap.keySet());
        }

        @Override
        public String getQueryString() {
            // @see : https://stackoverflow.com/a/35831692/9869013
            // return queryParameterMap.entrySet().stream().flatMap(entry -> Stream.of(entry.getValue()).map(value -> entry.getKey() + "=" + value)).collect(Collectors.joining("&")); // without encoding !!
            return queryParameterMap.entrySet().stream().flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), requestEncoding)).collect(Collectors.joining("&"));
        }

        private Stream<String> encodeMultiParameter(String key, String[] values, Charset encoding) {
            return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
        }

        private String encodeSingleParameter(String key, String value, Charset encoding) {
            return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
        }

        private String urlEncode(String value, Charset encoding) {
            try {
                return URLEncoder.encode(value, encoding.name());
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Cannot url encode " + value, e);
            }
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            throw new UnsupportedOperationException("getInputStream() is not implemented in this " + CustomHttpServletRequest.class.getSimpleName() + " wrapper");
        }

    }

note : queryString() requires to process ALL the values for each KEY and don't forget to encodeUrl() when adding your own param values, if required

As a limitation, if you call request.getParameterMap() or any method that would call request.getReader() and begin reading, you will prevent any further calls to request.setCharacterEncoding(...)

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

How to start nginx via different port(other than 80)

You will need to change the configure port of either Apache or Nginx. After you do this you will need to restart the reconfigured servers, using the 'service' command you used.


Apache

Edit

sudo subl /etc/apache2/ports.conf 

and change the 80 on the following line to something different :

Listen 80

If you just change the port or add more ports here, you will likely also have to change the VirtualHost statement in

sudo subl /etc/apache2/sites-enabled/000-default.conf

and change the 80 on the following line to something different :

<VirtualHost *:80>

then restart by :

sudo service apache2 restart

Nginx

Edit

/etc/nginx/sites-enabled/default

and change the 80 on the following line :

listen 80;

then restart by :

sudo service nginx restart

How to convert DataTable to class Object?

It is Vb.Net version:

Public Class Test
Public Property id As Integer
Public Property name As String
Public Property address As String
Public Property createdDate As Date

End Class

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim x As Date = Now

    Debug.WriteLine("Begin: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Dim dt As New DataTable
    dt.Columns.Add("id")
    dt.Columns.Add("name")
    dt.Columns.Add("address")
    dt.Columns.Add("createdDate")

    For i As Integer = 0 To 100000
        dt.Rows.Add(i, "name - " & i, "address - " & i, DateAdd(DateInterval.Second, i, Now))
    Next

    Debug.WriteLine("Datatable created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)


    Dim items As IList(Of Test) = dt.AsEnumerable().[Select](Function(row) New _
            Test With {
                        .id = row.Field(Of String)("id"),
                        .name = row.Field(Of String)("name"),
                        .address = row.Field(Of String)("address"),
                        .createdDate = row.Field(Of String)("createdDate")
                       }).ToList()

    Debug.WriteLine("List created: " & DateDiff(DateInterval.Second, x, Now) & "-" & Now)

    Debug.WriteLine("Complated")

End Sub

set dropdown value by text using jquery

$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes

Get most recent file in a directory on Linux

The find / sort solution works great until the number of files gets really large (like an entire file system). Use awk instead to just keep track of the most recent file:

find $DIR -type f -printf "%T@ %p\n" | 
awk '
BEGIN { recent = 0; file = "" }
{
if ($1 > recent)
   {
   recent = $1;
   file = $0;
   }
}
END { print file; }' |
sed 's/^[0-9]*\.[0-9]* //'

How to change PHP version used by composer

I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.

PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)

export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH

Position buttons next to each other in the center of page

Have both the buttons inside a div as shown below and add the given CSS for that div

_x000D_
_x000D_
#button1, #button2{_x000D_
width: 200px;_x000D_
height: 40px;_x000D_
}_x000D_
_x000D_
#butn{_x000D_
    margin: 0 auto;_x000D_
    display: block;_x000D_
}
_x000D_
<div id="butn">_x000D_
 <button type="button home-button" id="button1" >Home</button>_x000D_
 <button type="button contact-button" id="button2">Contact Us</button>_x000D_
<div>
_x000D_
_x000D_
_x000D_

Display only 10 characters of a long string?

('very long string'.slice(0,10))+'...'
// "very long ..."

How to use jQuery to select a dropdown option?

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);

Cannot read property 'getContext' of null, using canvas

Put your JavaScript code after your tag <canvas></canvas>

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

What is the correct syntax of ng-include?

On ng-build, file not found(404) error occur. So we can use below code

<ng-include src="'views/transaction/test.html'"></ng-include>

insted of,

<div ng-include="'views/transaction/test.html'"></div>

How to parse a text file with C#

Another solution, this time making use of regular expressions:

using System.Text.RegularExpressions;

...

Regex parts = new Regex(@"^\d+\t(\d+)\t.+?\t(item\\[^\t]+\.ddj)");

StreamReader reader = FileInfo.OpenText("filename.txt");
string line;
while ((line = reader.ReadLine()) != null) {
    Match match = parts.Match(line);
    if (match.Success) {
        int number = int.Parse(match.Group(1).Value);
        string path = match.Group(2).Value;

        // At this point, `number` and `path` contain the values we want
        // for the current line. We can then store those values or print them,
        // or anything else we like.
    }
}

That expression's a little complex, so here it is broken down:

^        Start of string
\d+      "\d" means "digit" - 0-9. The "+" means "one or more."
         So this means "one or more digits."
\t       This matches a tab.
(\d+)    This also matches one or more digits. This time, though, we capture it
         using brackets. This means we can access it using the Group method.
\t       Another tab.
.+?      "." means "anything." So "one or more of anything". In addition, it's lazy.
         This is to stop it grabbing everything in sight - it'll only grab as much
         as it needs to for the regex to work.
\t       Another tab.

(item\\[^\t]+\.ddj)
    Here's the meat. This matches: "item\<one or more of anything but a tab>.ddj"

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

SQL statement to select all rows from previous day

subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp

Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)

Using grep to search for hex strings in a file

This seems to work for me:

LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>

short form:

LANG=C grep -obUaP "<\x-hex pattern>" <file>

Example:

LANG=C grep -obUaP "\x01\x02" /bin/grep

Output (cygwin binary):

153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>

So you can grep this again to extract offsets. But don't forget to use binary mode again.

Note: LANG=C is needed to avoid utf8 encoding issues.

jQuery UI - Close Dialog When Clicked Outside

I don't think finding dialog stuff using $('.any-selector') from the whole DOM is so bright.

Try

$('<div />').dialog({
    open: function(event, ui){
        var ins = $(this).dialog('instance');
        var overlay = ins.overlay;
        overlay.off('click').on('click', {$dialog: $(this)}, function(event){
            event.data.$dialog.dialog('close');
        });
    }
});

You're really getting the overlay from the dialog instance it belongs to, things will never go wrong this way.

what is Ljava.lang.String;@

The method works if you provide an array. The output of

String[] helloWorld = {"Hello", "World"};
System.out.println(helloWorld);
System.out.println(Arrays.toString(helloWorld));

is

[Ljava.lang.String;@45a877
[Hello, World]

(the number after @ is almost always different)

Please tell us the return type of Employee.getSelectCancel()

How to draw interactive Polyline on route google maps v2 android

Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.

enter image description here

What is the difference between a candidate key and a primary key?

If superkey is a big set than candidate key is some smaller set inside big set and primary key any one element(one at a time or for a table) in candidate key set.

Using import fs from 'fs'

In order to use import { readFileSync } from 'fs', you have to:

  1. Be using Node.js 10 or later
  2. Use the --experimental-modules flag (in Node.js 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

The other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.

Here's the Node.js 10 ESM documentation.

Python how to write to a binary file?

Use struct.pack to convert the integer values into binary bytes, then write the bytes. E.g.

newFile.write(struct.pack('5B', *newFileBytes))

However I would never give a binary file a .txt extension.

The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i' for the format instead to get full 32-bit integers.

jQuery checkbox onChange

There is no need to use :checkbox, also replace #activelist with #inactivelist:

$('#inactivelist').change(function () {
    alert('changed');
 });

Make sure that the controller has a parameterless public constructor error

If you are using UnityConfig.cs to resister your type's mappings like below.

public static void RegisterTypes(IUnityContainer container)
    {
     container.RegisterType<IProductRepository, ProductRepository>();
    }

You have to let the know **webApiConfig.cs** about Container

config.DependencyResolver = new Unity.AspNet.WebApi.UnityDependencyResolver(UnityConfig.Container);

Reverse engineering from an APK file to a project

For the Android platform, you can try ShowJava, available on the Play Store.

You can consult the generated code through the app interface and the generated java files and folders structure are stored in ShowJava folder in /sdcard, alongside the resulting .jar file from the conversion.

The app is free with an ad banner at the bottom of the main view, but there is an in-app purchase option (3,99$) to remove it. In-app purchase does not add any functionality beside removing the ad banner.

Disclosure : I'm not the developer of the app neither I'm affiliated with him in any way.

What does %s mean in a python format string?

The format method was introduced in Python 2.6. It is more capable and not much more difficult to use:

>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.

>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'

>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'

>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'

How to get child element by index in Jquery?

$('.second').find('div:first')

How to pass a function as a parameter in Java?

Java supports closures just fine. It just doesn't support functions, so the syntax you're used to for closures is much more awkward and bulky: you have to wrap everything up in a class with a method. For example,

public Runnable foo(final int x) {
  return new Runnable() {
    public void run() {
      System.out.println(x);
    }
  };
}

Will return a Runnable object whose run() method "closes over" the x passed in, just like in any language that supports first-class functions and closures.

counting number of directories in a specific directory

Run stat -c %h folder and subtract 2 from the result. This employs only a single subprocess as opposed to the 2 (or even 3) required by most of the other solutions here (typically find plus wc).

Using sh/bash:

cnt=$((`stat -c %h folder` - 2))
echo $cnt   # 'echo' is a sh/bash builtin, not an additional process

Using csh/tcsh:

@ cnt = `stat -c %h folder` - 2
echo $cnt   # 'echo' is a csh/tcsh builtin, not an additional process


Explanation: stat -c %h folder prints the number of hardlinks to folder, and each subfolder under folder contains a ../ entry which is a hardlink back to folder. You must subtract 2 because there are two additional hardlinks in the count:

  1. folder's own self-referential ./ entry, and
  2. folder's parent's link to folder

Running the new Intel emulator for Android

For Windows, there are some answers explained how it works. But I'm a Mac User, I don't know how to install HAX driver for Mac as they did for Windows. Finally I found the below link and it did fix my problem. You should download HAXM of Mac and then install it.

https://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement-macosx/

Android splash screen image sizes to fit all devices

Density buckets

LDPI    120dpi    .75x
MDPI    160dpi    1x
HDPI    240dpi    1.5x
XHDPI   320dpi    2x
XXHDPI  480dpi    3x
XXXHDPI 640dpi    4x

px / dp = dpi / 160 dpi

How can I make an "are you sure" prompt in a Windows batchfile?

The choice command is not available everywhere. With newer Windows versions, the set command has the /p option you can get user input

SET /P variable=[promptString]

see set /? for more info

How do I create and access the global variables in Groovy?

def iamnotglobal=100 // This will not be accessible inside the function

iamglobal=200 // this is global and will be even available inside the 

def func()
{
    log.info "My value is 200. Here you see " + iamglobal
    iamglobal=400
    //log.info "if you uncomment me you will get error. Since iamnotglobal cant be printed here " + iamnotglobal
}
def func2()
{
   log.info "My value was changed inside func to 400 . Here it is = " + iamglobal
}
func()
func2()

here iamglobal variable is a global variable used by func and then again available to func2

if you declare variable with def it will be local, if you don't use def its global

Twitter Bootstrap Multilevel Dropdown Menu

Updated Answer

* Updated answer which support the v2.1.1** bootstrap version stylesheet.

**But be careful because this solution has been removed from v3

Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:

http://jsfiddle.net/2Smgv/2858/


Original Answer

There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.

Relevant code

CSS

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
    display: block;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
}

Created my own .sub-menu class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.

Demo

R command for setting working directory to source file location in Rstudio

Here is another way to do it:

set2 <- function(name=NULL) {
  wd <- rstudioapi::getSourceEditorContext()$path
  if (!is.null(name)) {
    if (substr(name, nchar(name) - 1, nchar(name)) != '.R') 
      name <- paste0(name, '.R')
  }
  else {
    name <- stringr::word(wd, -1, sep='/')
  }
  wd <- gsub(wd, pattern=paste0('/', name), replacement = '')
  no_print <- eval(expr=setwd(wd), envir = .GlobalEnv)
}
set2()

Reload chart data via JSON with Highcharts

You can always load a json data

here i defined Chart as namespace

 $.getJSON('data.json', function(data){
                Chart.options.series[0].data = data[0].data;
                Chart.options.series[1].data = data[1].data;
                Chart.options.series[2].data = data[2].data;

                var chart = new Highcharts.Chart(Chart.options);

            });

How to use Comparator in Java to sort

You want to implement Comparable, not Comparator. You need to implement the compareTo method. You're close though. Comparator is a "3rd party" comparison routine. Comparable is that this object can be compared with another.

public int compareTo(Object obj1) {
  People that = (People)obj1;
  Integer p1 = this.getId();
  Integer p2 = that.getid();

  if (p1 > p2 ){
   return 1;
  }
  else if (p1 < p2){
   return -1;
  }
  else
   return 0;
 }

Note, you may want to check for nulls in here for getId..just in case.

Move div to new line

Try this

#movie_item {
    display: block;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
    background: red;
}

#movie_item_content {
    float: left;
    background: gold;
}

.movie_item_content_title {
    display: block;
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
    display: block;

}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

In Html

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
            <div class="movie_item_content_year">(1890-)</div>
        <div class="movie_item_content_title">title my film is a long word</div>
        <div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

I change position div year.

List of enum values in java

An enum is just another class in Java, it should be possible.

More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html

So yes, it should work.

Activity restart on rotation Android

Use orientation listener to perform different tasks on different orientation.

@Override
public void onConfigurationChanged(Configuration myConfig) 
{
    super.onConfigurationChanged(myConfig);
    int orient = getResources().getConfiguration().orientation; 
    switch(orient) 
    {
       case Configuration.ORIENTATION_LANDSCAPE:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
       case Configuration.ORIENTATION_PORTRAIT:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
       default:
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
}

How do I add python3 kernel to jupyter (IPython)

When you use conda managing your python envs, follow these two steps:

  1. activate py3 (on Windows or source activate py3 on Linux)
  2. conda install notebook ipykernel or just use conda install jupyter

RGB to hex and hex to RGB

Using combining anonymous functions and Array.map for a cleaner; more streamlined look.

_x000D_
_x000D_
var write=function(str){document.body.innerHTML=JSON.stringify(str,null,'    ');};_x000D_
_x000D_
function hexToRgb(hex, asObj) {_x000D_
  return (function(res) {_x000D_
    return res == null ? null : (function(parts) {_x000D_
      return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] }_x000D_
    }(res.slice(1,4).map(function(val) { return parseInt(val, 16); })));_x000D_
  }(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)));_x000D_
}_x000D_
_x000D_
function rgbToHex(r, g, b) {_x000D_
  return (function(values) {_x000D_
    return '#' + values.map(function(intVal) {_x000D_
      return (function(hexVal) {_x000D_
        return hexVal.length == 1 ? "0" + hexVal : hexVal;_x000D_
      }(intVal.toString(16)));_x000D_
    }).join('');_x000D_
  }(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b]))_x000D_
}_x000D_
_x000D_
// Prints: { r: 255, g: 127, b: 92 }_x000D_
write(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true));
_x000D_
body{font-family:monospace;white-space:pre}
_x000D_
_x000D_
_x000D_

Cant get text of a DropDownList in code - can get value but not text

Have a look here, this has a proof-of-concept page and demo you can use to get anything from the drop-down: asp:DropDownList Control Tutorial Page

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

If any of your users are running linux they can use this from a terminal:

lsusb -v 2> /dev/null | grep -e "Apple Inc" -A 2

This gets the all the information for your connected usb devices and prints lines with "Apple Inc" including the next 2 lines.

The result looks like this:

iManufacturer           1 Apple Inc.
iProduct                2 iPad
iSerial                 3 7ddf32e17a6ac5ce04a8ecbf782ca509...

This has worked for me on iOS5 -> iOS7, I haven’t tried on any iOS4 devices though.

IMO this is faster then any Win/Mac/Browser solution I have found and requires no "software" installation.

How to create a hidden <img> in JavaScript?

You can hide an image using javascript like this:

document.images['imageName'].style.visibility = hidden;

If that isn't what you are after, you need to explain yourself more clearly.

Detecting input change in jQuery?

As others already suggested, the solution in your case is to sniff multiple events.
Plugins doing this job often listen for the following events:

$input.on('change keydown keypress keyup mousedown click mouseup', handler);

If you think it may fit, you can add focus, blur and other events too.
I suggest not to exceed in the events to listen, as it loads in the browser memory further procedures to execute according to the user's behaviour.

Attention: note that changing the value of an input element with JavaScript (e.g. through the jQuery .val() method) won't fire any of the events above.
(Reference: https://api.jquery.com/change/).

SQL distinct for 2 fields in a database

If you still want to group only by one column (as I wanted) you can nest the query:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

What is the LDF file in SQL Server?

The LDF file holds the database transaction log. See, for example, http://www.databasedesign-resource.com/sql-server-transaction-log.html for a full explanation. There are ways to shrink the transaction file; for example, see http://support.microsoft.com/kb/873235.

Write HTML file using Java

if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..

Run jar file in command prompt

You can run a JAR file from the command line like this:

java -jar myJARFile.jar

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

Using Keras & Tensorflow with AMD GPU

Technically you can if you use something like OpenCL, but Nvidia's CUDA is much better and OpenCL requires other steps that may or may not work. I would recommend if you have an AMD gpu, use something like Google Colab where they provide a free Nvidia GPU you can use when coding.

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml

values.yaml

.....  
databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
.....  
secrets:
    type: Opaque  
    name: dbservice-secrets  
    data:  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  
.....

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}

secret.yaml

when using inside range i:e iteration

  {{ range .Values.deployments.secrets.data }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl .Values.deployments.secrets.data.name . }}
  {{ tpl .Values.deployments.secrets.data.value . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

How to create Drawable from resource

This code is deprecated:

Drawable drawable = getResources().getDrawable( R.drawable.icon );

Use this instead:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

Django DB Settings 'Improperly Configured' Error

in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver instead of manage.py runserver in my project directory.

How to destroy an object?

A handy post explaining several mis-understandings about this:

Don't Call The Destructor explicitly

This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.

How can I time a code segment for testing performance with Pythons timeit?

You can use time.time() or time.clock() before and after the block you want to time.

import time

t0 = time.time()
code_block
t1 = time.time()

total = t1-t0

This method is not as exact as timeit (it does not average several runs) but it is straightforward.

time.time() (in Windows and Linux) and time.clock() (in Linux) are not precise enough for fast functions (you get total = 0). In this case or if you want to average the time elapsed by several runs, you have to manually call the function multiple times (As I think you already do in you example code and timeit does automatically when you set its number argument)

import time

def myfast():
   code

n = 10000
t0 = time.time()
for i in range(n): myfast()
t1 = time.time()

total_n = t1-t0

In Windows, as Corey stated in the comment, time.clock() has much higher precision (microsecond instead of second) and is preferred over time.time().

Replace given value in vector

Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")
needles <- c("q", "w")
replacements <- c("a", "z")

replace(haystack, haystack %in% needles, replacements)
#> [1] "a" "z" "e" "r" "t" "y"

Hide HTML element by id

.nav ul li a#nav-ask{
    display:none;
}

Change navbar text color Bootstrap

The syntax is :

.nav navbar-nav .navbar-right > li > a {
   color: blue;
}

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How to Populate a DataTable from a Stored Procedure

You can use a SqlDataAdapter:

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
    cmd.CommandType = CommandType.StoredProcedure;
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable();
    adapter.Fill(dt);

How to add custom validation to an AngularJS form?

I recently created a directive to allow for expression-based invalidation of angular form inputs. Any valid angular expression can be used, and it supports custom validation keys using object notation. Tested with angular v1.3.8

        .directive('invalidIf', [function () {
        return {
            require: 'ngModel',
            link: function (scope, elm, attrs, ctrl) {

                var argsObject = scope.$eval(attrs.invalidIf);

                if (!angular.isObject(argsObject)) {
                    argsObject = { invalidIf: attrs.invalidIf };
                }

                for (var validationKey in argsObject) {
                    scope.$watch(argsObject[validationKey], function (newVal) {
                        ctrl.$setValidity(validationKey, !newVal);
                    });
                }
            }
        };
    }]);

You can use it like this:

<input ng-model="foo" invalid-if="{fooIsGreaterThanBar: 'foo > bar',
                                   fooEqualsSomeFuncResult: 'foo == someFuncResult()'}/>

Or by just passing in an expression (it will be given the default validationKey of "invalidIf")

<input ng-model="foo" invalid-if="foo > bar"/>

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Uncaught TypeError: Cannot read property 'value' of null

HTML : Pass the whole body inside on click

div class="calculate" id="calculate">
            <div class="button" id="button" onclick="myCode(this.body)"> CALCULATE ! </div>
        </div>

Then write the JavaScript code inside the function "myCode()"

function myCode()
{
    var bill = document.getElementById("currency").value ;

    var people_count = document.getElementById("number1").value;
    var select_value = document.getElementById("select").value;

    var calculate = document.getElementById("calculate");

    calculate.addEventListener("click" ,function()
    {
        console.log(bill);
        console.log(people_count);
        console.log(select_value);
    });
}

you will get your values I am using visual studio code editor

Does 'position: absolute' conflict with Flexbox?

You have to give width:100% to parent to center the text.

_x000D_
_x000D_
 .parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you also need to centre align vertically, give height:100% and align-itens: center

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   position: absolute;
   width:100%;
   height: 100%;
 }

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Open Turn On/Off Windows Features.

Make sure you have Active Directory Domain Services selected. If not, install it. enter image description here

In Mongoose, how do I sort by date? (node.js)

Short solution:

const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }

Room.find(query, projection, options).exec(function(err, docs) { ... });

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How To Format A Block of Code Within a Presentation?

If you write your code in emacs then you might be interested in the htmlize elisp package.

Windows service with timer

First approach with Windows Service is not easy..

A long time ago, I wrote a C# service.

This is the logic of the Service class (tested, works fine):

namespace MyServiceApp
{
    public class MyService : ServiceBase
    {
        private System.Timers.Timer timer;

        protected override void OnStart(string[] args)
        {
            this.timer = new System.Timers.Timer(30000D);  // 30000 milliseconds = 30 seconds
            this.timer.AutoReset = true;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
            this.timer.Start();
        }

        protected override void OnStop()
        {
            this.timer.Stop();
            this.timer = null;
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MyServiceApp.ServiceWork.Main(); // my separate static method for do work
        }

        public MyService()
        {
            this.ServiceName = "MyService";
        }

        // service entry point
        static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new MyService());
        }
    }
}

I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.

Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

Hope this helps!

including parameters in OPENQUERY

Actually, We found a way to do this:

DECLARE @username varchar(50)
SET @username = 'username'
DECLARE @Output as numeric(18,4)
DECLARE @OpenSelect As nvarchar(500)
SET @OpenSelect = '(SELECT @Output = CAST((CAST(pwdLastSet As bigint) / 864000000000) As numeric(18,4)) FROM OpenQuery (ADSI,''SELECT pwdLastSet
                                FROM  ''''LDAP://domain.net.intra/DC=domain,DC=net,DC=intra''''
                                WHERE objectClass =  ''''User'''' AND sAMAccountName = ''''' + @username + '''''
                          '') AS tblADSI)'
EXEC sp_executesql @OpenSelect, N'@Output numeric(18,4) out', @Output out
SELECT @Output As Outputs

This will assign the result of the OpenQuery execution, in the variable @Output.

We tested for Store procedure in MSSQL 2012, but should work with MSSQL 2008+.

Microsoft Says that sp_executesql(Transact-SQL): Applies to: SQL Server (SQL Server 2008 through current version), Windows Azure SQL Database (Initial release through current release). (http://msdn.microsoft.com/en-us/library/ms188001.aspx)

git: fatal: Could not read from remote repository

I had a perfectly fine working git and suddenly I got that error when I tried to push to the master. As I found out, it was because the repository host had problems.

If you using GitHub or Bitbucket you can easily check the status at

https://status.github.com/messages or https://status.bitbucket.org/

enter image description here

Upload files with HTTPWebrequest (multipart/form-data)

VB Example (converted from C# example on another post):

Private Sub HttpUploadFile( _
    ByVal uri As String, _
    ByVal filePath As String, _
    ByVal fileParameterName As String, _
    ByVal contentType As String, _
    ByVal otherParameters As Specialized.NameValueCollection)

    Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
    Dim newLine As String = System.Environment.NewLine
    Dim boundaryBytes As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
    Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)

    request.ContentType = "multipart/form-data; boundary=" & boundary
    request.Method = "POST"
    request.KeepAlive = True
    request.Credentials = Net.CredentialCache.DefaultCredentials

    Using requestStream As IO.Stream = request.GetRequestStream()

        Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"

        For Each key As String In otherParameters.Keys

            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
            Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
            Dim formItemBytes As Byte() = Text.Encoding.UTF8.GetBytes(formItem)
            requestStream.Write(formItemBytes, 0, formItemBytes.Length)

        Next key

        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)

        Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
        Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
        Dim headerBytes As Byte() = Text.Encoding.UTF8.GetBytes(header)
        requestStream.Write(headerBytes, 0, headerBytes.Length)

        Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)

            Dim buffer(4096) As Byte
            Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)

            Do While (bytesRead > 0)

                requestStream.Write(buffer, 0, bytesRead)
                bytesRead = fileStream.Read(buffer, 0, buffer.Length)

            Loop

        End Using

        Dim trailer As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
        requestStream.Write(trailer, 0, trailer.Length)

    End Using

    Dim response As Net.WebResponse = Nothing

    Try

        response = request.GetResponse()

        Using responseStream As IO.Stream = response.GetResponseStream()

            Using responseReader As New IO.StreamReader(responseStream)

                Dim responseText = responseReader.ReadToEnd()
                Diagnostics.Debug.Write(responseText)

            End Using

        End Using

    Catch exception As Net.WebException

        response = exception.Response

        If (response IsNot Nothing) Then

            Using reader As New IO.StreamReader(response.GetResponseStream())

                Dim responseText = reader.ReadToEnd()
                Diagnostics.Debug.Write(responseText)

            End Using

            response.Close()

        End If

    Finally

        request = Nothing

    End Try

End Sub

Invalid application path

even it was getting the above error. i found out that IIS was not registered on the server.

registering the iis fixed the issue.

Thanks,