Programs & Examples On #Contenttype

In Microsoft SharePoint Foundation 2010, a content type is a reusable collection of settings that you want to apply to a certain category of content.

Cross-Origin Read Blocking (CORB)

It seems that this warning occured when sending an empty response with a 200.

This configuration in my .htaccess display the warning on Chrome:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST,GET,HEAD,OPTIONS,PUT,DELETE"
Header always set Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

But changing the last line to

RewriteRule .* / [R=204,L]

resolve the issue!

ReferenceError: fetch is not defined

The fetch API is not implemented in Node.

You need to use an external module for that, like node-fetch.

Install it in your Node application like this

npm i node-fetch --save

then put the line below at the top of the files where you are using the fetch API:

const fetch = require("node-fetch");

Laravel 5.5 ajax call 419 (unknown status)

If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.

index.blade.php

...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
        var token = '{{ csrf_token() }}';
</script>

anotherfile.js

$.ajax({
    url: 'yourUrl',
    type: 'POST',
    data: {
        '_token': token
    },
    dataType: "json",
    beforeSend:function(){
        //do stuff
    },
    success: function(data) {
        //do stuff
    },
    error: function(data) {
        //do stuff
    },
    complete: function(){
        //do stuff
    }
});

Django - Reverse for '' not found. '' is not a valid view function or pattern name

When you use the url tag you should use quotes for string literals, for example:

{% url 'products' %}

At the moment product is treated like a variable and evaluates to '' in the error message.

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

How to enable CORS in ASP.net Core WebAPI

Use a custom Action/Controller Attribute to set the CORS headers.

Example:

public class AllowMyRequestsAttribute : ControllerAttribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        // check origin
        var origin = context.HttpContext.Request.Headers["origin"].FirstOrDefault();
        if (origin == someValidOrigin)
        {
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
            context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
            // Add whatever CORS Headers you need.
        }
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // empty
    }
}

Then on the Web API Controller / Action:

[ApiController]
[AllowMyRequests]
public class MyController : ApiController
{
    [HttpGet]
    public ActionResult<string> Get()
    {
        return "Hello World";
    }
}

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Please add the shared dependency having jackson databind package . Hope this will clear the issue.

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
  </dependency>

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I was using a .Net Core 2.1 API with the [FromBody] attribute and I had to use the following solution to successfully Post to it:

_apiClient =  new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
    FirstName = "Me",
    LastName = "Myself"
};

var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Django model "doesn't declare an explicit app_label"

I ran into this error when I tried generating migrations for a single app which had existing malformed migrations due to a git merge. e.g.

manage.py makemigrations myapp

When I deleted it's migrations and then ran:

manage.py makemigrations

the error did not occur and the migrations generated successfully.

How can I set a cookie in react?

A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

You can use this library, makes it seamless to send push notifications using Firebase Service from a C# backend download here

How to get response from S3 getObject in Node.js?

Alternatively you could use minio-js client library get-object.js

var Minio = require('minio')

var s3Client = new Minio({
  endPoint: 's3.amazonaws.com',
  accessKey: 'YOUR-ACCESSKEYID',
  secretKey: 'YOUR-SECRETACCESSKEY'
})

var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
  if (e) {
    return console.log(e)
  }
  dataStream.on('data', function(chunk) {
    size += chunk.length
  })
  dataStream.on('end', function() {
    console.log("End. Total size = " + size)
  })
  dataStream.on('error', function(e) {
    console.log(e)
  })
})

Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.

download a file from Spring boot rest service

Option 1 using an InputStreamResource

Resource implementation for a given InputStream.

Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    // ...

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

AWS Lambda import module error in python

I found Nithin's answer very helpful. Here is a specific walk-through:

Look-up these values:

  1. The name of the lambda_handler function in your python script. The name used in the AWS examples is "lambda_handler" looking like "def lambda_handler(event, context)". In this case, the value is "lambda_handler"
  2. In the Lambda dashboard, find the name of the Handler in the "Handler" text-box in the "Configuration" section in the lambda dashboard for the function (shown in Nithin's screenshot). My default name was "lambda_function.lambda_handler".
  3. The name of your python script. Let's say it's "cool.py"

With these values, you would need to rename the handler (shown in the screenshot) to "cool.lambda_handler". This is one way to get rid of the "Unable to import module 'lambda_function'" errorMessage. If you were to rename the handler in your python script to "sup" then you'd need to rename the handler in the lambda dashboard to "cool.sup"

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

TypeScript: Property does not exist on type '{}'

Near the top of the file, you need to write var fadeDiv = ... instead of fadeDiv = ... so that the variable is actually declared.

The error "Property 'fadeDiv' does not exist on type '{}'." seems to be triggering on a line you haven't posted in your example (there is no access of a fadeDiv property anywhere in that snippet).

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you are just visiting a webpage that you trust and you want to move forward fast, just:

1- Click the shield icon in the far right of the address bar.

Allow mixed content in Google Chrome

2- In the pop-up window, click "Load anyway" or "Load unsafe script" (depending on your Chrome version).


If you want to set your Chrome browser to ALWAYS(in all webpages) allow mixed content:

1- In an open Chrome browser, press Ctrl+Shift+Q on your keyboard to force close Chrome. Chrome must be fully closed before the next steps.

2- Right-click the Google Chrome desktop icon (or Start Menu link). Select Properties.

3- At the end of the existing information in the Target field, add: " --allow-running-insecure-content" (There is a space before the first dash.)

4- Click OK.

5- Open Chrome and try to launch the content that was blocked earlier. It should work now.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

http://learn.jquery.com/ajax/working-with-jsonp/

Try example

$.ajax({
    url: "https://api.dailymotion.com/video/x28j5hv?fields=title",

    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response
    }

});

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.

HttpClient - A task was cancelled?

There's 2 likely reasons that a TaskCanceledException would be thrown:

  1. Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed.
  2. The request timed out, i.e. didn't complete within the timespan you specified on HttpClient.Timeout.

My guess is it was a timeout. (If it was an explicit cancellation, you probably would have figured that out.) You can be more certain by inspecting the exception:

try
{
    var response = task.Result;
}
catch (TaskCanceledException ex)
{
    // Check ex.CancellationToken.IsCancellationRequested here.
    // If false, it's pretty safe to assume it was a timeout.
}

How to write a unit test for a Spring Boot Controller endpoint

The new testing improvements that debuted in Spring Boot 1.4.M2 can help reduce the amount of code you need to write situation such as these.

The test would look like so:

import static org.springframework.test.web.servlet.request.MockMvcRequestB??uilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.content; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat??chers.status;

    @RunWith(SpringRunner.class)
    @WebMvcTest(HelloWorld.class)
    public class UserVehicleControllerTests {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testSayHelloWorld() throws Exception {
            this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("application/json"));

        }

    }

See this blog post for more details as well as the documentation

How to set up a Web API controller for multipart/form-data

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

No connection could be made because the target machine actively refused it 127.0.0.1

If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

Style jQuery autocomplete in a Bootstrap input field

The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2

When using jQuery version 3.1.1 it seem to not happen.

Possible reason is the notable update in v3.2.0 related to a bug fix on .width() and .height(). Check out the jQuery release notes for further details: v3.2.0 / v3.1.1

Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used

Reading HTTP headers in a Spring REST controller

The error that you get does not seem to be related to the RequestHeader.

And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
    // your code goes here
}

And your REST class should have annotations like:

@Controller
@RequestMapping("/rest/")


Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.

Example:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
    String userAgent = request.getHeader("user-agent");
}

Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)

java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

How to convert Blob to File in JavaScript

My modern variant:

function blob2file(blobData) {
  const fd = new FormData();
  fd.set('a', blobData);
  return fd.get('a');
}

Solve Cross Origin Resource Sharing with Flask

I used decorator given by Armin Ronacher with little modifications (due to different headers that are requested by the client).And that worked for me. (where I use angular as the requester requesting application/json type).

The code is slightly modified at below places,

from flask import jsonify

@app.route('/my_service', methods=['POST', 'GET','OPTIONS'])
@crossdomain(origin='*',headers=['access-control-allow-origin','Content-Type'])
def my_service():
    return jsonify(foo='cross domain ftw')

jsonify will send a application/json type, else it will be text/html. headers are added as the client in my case request for those headers

 const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin':'*'
      })
    };
    return this.http.post<any>(url, item,httpOptions)

Multipart File Upload Using Spring Rest Template + Spring Web MVC

The Multipart File Upload worked after following code modification to Upload using RestTemplate

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    HttpEntity<LinkedMultiValueMap<String, Object>>(
                    map, headers);
ResponseEntity<String> result = template.get().exchange(
                    contextPath.get() + path, HttpMethod.POST, requestEntity,
                    String.class);

And adding MultipartFilter to web.xml

    <filter>
        <filter-name>multipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>multipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

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

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

Jquery Ajax, return success/error from mvc.net controller

 $.ajax({
    type: "POST",
    data: formData,
    url: "/Forms/GetJobData",
    dataType: 'json',
    contentType: false,
    processData: false,               
    success: function (response) {
        if (response.success) {
            alert(response.responseText);
        } else {
            // DoSomethingElse()
            alert(response.responseText);
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }

});

Controller:

[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
    var mimeType = jobData.File.ContentType;
    var isFileSupported = IsFileSupported(mimeType);

    if (!isFileSupported){        
         //  Send "false"
        return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        //  Send "Success"
        return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
    }   
}

---Supplement:---

basically you can send multiple parameters this way:

Controller:

 return Json(new { 
                success = true,
                Name = model.Name,
                Phone = model.Phone,
                Email = model.Email                                
            }, 
            JsonRequestBehavior.AllowGet);

Html:

<script> 
     $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                contentType: 'application/json; charset=utf-8',            
                success: function (response) {

                   if(response.success){ 
                      console.log(response.Name);
                      console.log(response.Phone);
                      console.log(response.Email);
                    }


                },
                error: function (response) {
                    alert("error!"); 
                }
            });

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

Django: OperationalError No Such Table

I'm using Django 1.9, SQLite3 and DjangoCMS 3.2 and had the same issue. I solved it by running python manage.py makemigrations. This was followed by a prompt stating that the database contained non-null value types but did not have a default value set. It gave me two options: 1) select a one off value now or 2) exit and change the default setting in models.py. I selected the first option and gave the default value of 1. Repeated this four or five times until the prompt said it was finished. I then ran python manage.py migrate. Now it works just fine. Remember, by running python manage.py makemigrations first, a revised copy of the database is created (mine was 0004) and you can always revert back to a previous database state.

Multipart File upload Spring Boot

In Controller, your method should be;

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity<SaveResponse> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
....

Further, you need to update application.yml (or application.properties) to support maximum file size and request size.

spring:
    http:
        multipart:
            max-file-size: 5MB
            max-request-size: 20MB

How can I define an interface for an array of objects with Typescript?

Also you can do this.

            interface IenumServiceGetOrderBy {
                id: number; 
                label: string; 
                key: any;
            }

            // notice i am not using the []
            var oneResult: IenumServiceGetOrderBy = { id: 0, label: 'CId', key: 'contentId'};

            //notice i am using []
            // it is read like "array of IenumServiceGetOrderBy"
            var ArrayOfResult: IenumServiceGetOrderBy[] = 
            [
                { id: 0, label: 'CId', key: 'contentId' },
                { id: 1, label: 'Modified By', key: 'modifiedBy' },
                { id: 2, label: 'Modified Date', key: 'modified' },
                { id: 3, label: 'Status', key: 'contentStatusId' },
                { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
                { id: 5, label: 'Title', key: 'title' },
                { id: 6, label: 'Type', key: 'contentTypeId' },
                { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
            ];

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Django 1.7 - makemigrations not detecting changes

Just in case you have a specific field that does not get identified by makemigrations: check twice if you have a property with the same name.

example:

field = django.db.models.CharField(max_length=10, default = '', blank=True, null=True)

# ... later

@property
def field(self):
    pass

the property will "overwrite" the field definition so changes will not get identified by makemigrations

jQuery AJAX file upload PHP

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$name;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" height="100" width="100" />';
}

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

I think your issue may be in the url pattern. Changing

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

and

<form action="/Register" method="post">

may fix your problem

Send JSON via POST in C# and Receive the JSON returned?

You can also use the PostAsJsonAsync() method available in HttpClient()

_x000D_
_x000D_
   var requestObj= JsonConvert.SerializeObject(obj);_x000D_
   HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);
_x000D_
_x000D_
_x000D_

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

receiving json and deserializing as List of object at spring mvc controller

I believe this will solve the issue

var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
    url: "/setTest",
    data: z,
    type: "POST",
    dataType:"json",
    contentType:'application/json'               
});

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The code below resolved the issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

Summernote image upload

Summernote converts your uploaded images to a base64 encoded string by default, you can process this string or as other fellows mentioned you can upload images using onImageUpload callback. You can take a look at this gist which I modified a bit to adapt laravel csrf token here. But that did not work for me and I had no time to find out why! Instead, I solved it via a server-side solution based on this blog post. It gets the output of the summernote and then it will upload the images and updates the final markdown HTML.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

Route::get('/your-route-to-editor', function () {
    return view('your-view');
});

Route::post('/your-route-to-processor', function (Request $request) {

       $this->validate($request, [
           'editordata' => 'required',
       ]);

       $data = $request->input('editordata');

       //loading the html data from the summernote editor and select the img tags from it
       $dom = new \DomDocument();
       $dom->loadHtml($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);    
       $images = $dom->getElementsByTagName('img');
       
       foreach($images as $k => $img){
           //for now src attribute contains image encrypted data in a nonsence string
           $data = $img->getAttribute('src');
           //getting the original file name that is in data-filename attribute of img
           $file_name = $img->getAttribute('data-filename');
           //extracting the original file name and extension
           $arr = explode('.', $file_name);
           $upload_base_directory = 'public/';

           $original_file_name='time()'.$k;
           $original_file_extension='png';

           if (sizeof($arr) ==  2) {
                $original_file_name = $arr[0];
                $original_file_extension = $arr[1];
           }
           else
           {
                //the file name contains extra . in itself
                $original_file_name = implode("_",array_slice($arr,0,sizeof($arr)-1));
                $original_file_extension = $arr[sizeof($arr)-1];
           }

           list($type, $data) = explode(';', $data);
           list(, $data)      = explode(',', $data);

           $data = base64_decode($data);

           $path = $upload_base_directory.$original_file_name.'.'.$original_file_extension;

           //uploading the image to an actual file on the server and get the url to it to update the src attribute of images
           Storage::put($path, $data);

           $img->removeAttribute('src');       
           //you can remove the data-filename attribute here too if you want.
           $img->setAttribute('src', Storage::url($path));
           // data base stuff here :
           //saving the attachments path in an array
       }

       //updating the summernote WYSIWYG markdown output.
       $data = $dom->saveHTML();

       // data base stuff here :
       // save the post along with it attachments array
       return view('your-preview-page')->with(['data'=>$data]);

});

How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

insert data into database using servlet and jsp in eclipse

Check that doPost() method of servlet is called from the jsp form and remove conn.commit.

How to add and get Header values in WebApi

For .NET Core:

string Token = Request.Headers["Custom"];

Or

var re = Request;
var headers = re.Headers;
string token = string.Empty;
StringValues x = default(StringValues);
if (headers.ContainsKey("Custom"))
{
   var m = headers.TryGetValue("Custom", out x);
}

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Rest-assured. Is it possible to extract value from request json?

To serialize the response into a class, define the target class

public class Result {
    public Long user_id;
}

And map response to it:

Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);

You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)

Send FormData and String Data Together Through JQuery AJAX?

well, as an easier alternative and shorter, you could do this too!!

var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php?'+ other_data,  //<== just add it to the end of url ***
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

How to use FormData for AJAX file upload?

View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
                $(document).on('change', ':file', function () {
                    var fileUpload = $(this).get(0);
                    var files = fileUpload.files;
                    var bid = 0;
                    if (files.length != 0) {
                        var data = new FormData();
                        for (var i = 0; i < files.length ; i++) {
                            data.append(files[i].name, files[i]);
                        }
                        $.ajax({
                            xhr: function () {
                                var xhr = $.ajaxSettings.xhr();
                                xhr.upload.onprogress = function (e) {
                                    console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                };
                                return xhr;
                            },
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            data: data,
                            url: '/ControllerX/' + bid,
                            success: function (response) {
                                location.href = 'xxx/Index/';
                            }
                        });
                    }
                });
            });
</Script>
Controller:
[HttpPost]
        public ActionResult ControllerX(string id)
        {
            var files = Request.Form.Files;
...

how to set the background image fit to browser using html

body
{
    position: fixed;  /*fixes the image in background*/
    top: 0; /*fixes the image at top*/
    left: 0; /*fixes the image at left*/
    min-width: 100%; /*fixes the image width to 100% of screen*/
    min-height: 100%; /*fixes the image height to 100% of screen*/
}

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Looks to be the same question as:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

No Access-Control-Allow-Origin header is present on the requested resource

I find the solution in spring.io,like this:

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

json parsing error syntax error unexpected end of input

spoiler: possible Server Side Problem

Here is what i've found, my code expected the responce from my server, when the server returned just 200 code, it wasnt enough herefrom json parser thrown the error error unexpected end of input

fetch(url, {
        method: 'POST',
        body: JSON.stringify(json),
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => res.json()) // here is my code waites the responce from the server
        .then((res) => {
          toastr.success('Created Type is sent successfully');
        })
        .catch(err => {
          console.log('Type send failed', err);
          toastr.warning('Type send failed');
        })

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

Iterating through a List Object in JSP

 <c:forEach items="${sessionScope.empL}" var="emp">
            <tr>
                <td>Employee ID: <c:out value="${emp.eid}"/></td>
                <td>Employee Pass: <c:out value="${emp.ename}"/></td>  
            </tr>
        </c:forEach>

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

Testing Spring's @RequestBody using Spring MockMVC

the following works for me,

  mockMvc.perform(
            MockMvcRequestBuilders.post("/api/test/url")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(asJsonString(createItemForm)))
            .andExpect(status().isCreated());

  public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Creating a JSON Array in node js

You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

download csv file from web api in angular js

In Angular 1.5, use the $window service to download a file.

angular.module('app.csv').factory('csvService', csvService);

csvService.$inject = ['$window'];

function csvService($window) {
    function downloadCSV(urlToCSV) {
        $window.location = urlToCSV;
    }
}

How to upload file to server with HTTP POST multipart/form-data?

Top to @loop answer.

We got below error for Asp.Net MVC, Unable to connect to the remote server

Fix: After adding the below code in Web.Confing issue has been resolved for us

  <system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
  </system.net>

Spring MVC Missing URI template variable

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

For example

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to upload files on server folder using jsp

public class FileUploadExample extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);

                try {
                    // Parse the request
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            String fileName = item.getName();    
                            String root = getServletContext().getRealPath("/");
                            File path = new File(root + "/uploads");
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            System.out.println(uploadedFile.getAbsolutePath());
                            item.write(uploadedFile);
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

}

Spring Rest POST Json RequestBody Content type not supported

try to add jackson dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.3</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotations</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>

Django: TemplateSyntaxError: Could not parse the remainder

You have indented part of your code in settings.py:

# Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    #'django.contrib.admindocs',
     'tinymce',
     'sorl.thumbnail',
     'south',
     'django_facebook',
     'djcelery',
     'devserver',
     'main',

Therefore, it is giving you an error.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book Two scoops of Django.

I resolved the issue by setting

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local")

in manage.py and wsgi.py.

Update:

In the above solution, local is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.

Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.

Your settings folder will look like:

settings/
    __init__.py
    base.py
    local.py
    prod.py
    stage.py

and keep the following code in your settings/__init__.py

from .base import *

env_name = os.getenv('ENV_NAME', 'local')

if env_name == 'prod':
    from .prod import *
elif env_name == 'stage':
    from .stage import *
else:
    from .local import *

How to call webmethod in Asp.net C#

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

Script example:

$.ajax({
    type: "POST",
    url: '/Default.aspx/TestMethod',
    data: '{message: "HAI" }',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
    },
    failure: function (response) {
        alert(response.d);
    }
});

WebMethod example:

[WebMethod]
public static string TestMethod(string message)
{
     return "The message" + message;
}

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

I had this same problem. For me the fix was to remove the custom content type from the jQuery AJAX call. Custom content types trigger the pre-flight request. I found this:

The browser can skip the preflight request if the following conditions are true:

The request method is GET, HEAD, or POST, and

The application does not set any request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID, and

The Content-Type header (if set) is one of the following:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

From this page: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api (under "Preflight Requests")

Add Header and Footer for PDF using iTextsharp

pdfDoc.Open();
Paragraph para = new Paragraph("Hello World", new Font(Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(para);
pdfDoc.Add(new Paragraph("\r\n"));
htmlparser.Parse(sr);
pdfDoc.Close();

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

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

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

How to pass parameters in $ajax POST?

function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}

How to simulate POST request?

It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:

For example:

curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource

OR, for a RESTful API:

curl -X POST -d @file http://host/resource

You can check out more information here-> http://curl.haxx.se/


EDITs:

OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests.

Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.


More EDITs

So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be

http://localhost/library/book/34

Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:

POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name

From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.

Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

ASP.NET file download from server

Simple solution for downloading a file from the server:

protected void btnDownload_Click(object sender, EventArgs e)
        {
            string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "image/jpeg";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(Server.MapPath("~/File/001.jpg"));
            response.Flush();
            response.End();
        }

Why I get 411 Length required error?

Hey i'm using Volley and was getting Server error 411, I added to the getHeaders method the following line :

params.put("Content-Length","0");

And it solved my issue

How to check String in response body with mockMvc

here a more elegant way

mockMvc.perform(post("/retrieve?page=1&countReg=999999")
            .header("Authorization", "Bearer " + validToken))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("regCount")));

How to return JSON with ASP.NET & jQuery

This structure works for me - I used it in a small tasks management application.

The controller:

public JsonResult taskCount(string fDate)
{
  // do some stuff based on the date

  // totalTasks is a count of the things I need to do today
  // tasksDone is a count of the tasks I actually did
  // pcDone is the percentage of tasks done

  return Json(new {
    totalTasks = totalTasks,
    tasksDone = tasksDone,
    percentDone = pcDone
  });
}

In the AJAX call I access the data like this:

.done(function (data) {
  // data.totalTasks
  // data.tasksDone
  // data.percentDone
});

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

org.apache.jasper.JasperException: Unable to compile class for JSP:

This maybe caused by jar conflict. Remove the servlet-api.jar in your servlet/WEB-INF/ directory, %Tomcat home%/lib already have this lib.

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

Well my client side (a cshtml file) was using DataTables to display a grid (now using Infragistics control which are great). And once the user clicked on the row, I captured the row event and the date associated with that record in order to go back to the server and make additional server-side requests for trades, etc. And no - I DID NOT stringify it...

The DataTables def started as this (leaving lots of stuff out), and the click event is seen below where I PUSH onto my Json object :

    oTablePf = $('#pftable').dataTable({         // INIT CODE
             "aaData": PfJsonData,
             'aoColumnDefs': [                     
                { "sTitle": "Pf Id", "aTargets": [0] },
                { "sClass": "**td_nodedate**", "aTargets": [3] }
              ]
              });

   $("#pftable").delegate("tbody tr", "click", function (event) {   // ROW CLICK EVT!! 

        var rownum = $(this).index(); 
        var thisPfId = $(this).find('.td_pfid').text();  // Find Port Id and Node Date
        var thisDate = $(this).find('.td_nodedate').text();

         //INIT JSON DATA
        var nodeDatesJson = {
            "nodedatelist":[]
        };

         // omitting some code here...
         var dateArry = thisDate.split("/");
         var nodeDate = dateArry[2] + "-" + dateArry[0] + "-" + dateArry[1];

         nodeDatesJson.nodedatelist.push({ nodedate: nodeDate });

           getTradeContribs(thisPfId, nodeDatesJson);     // GET TRADE CONTRIBUTIONS 
    });

Parse JSON response using jQuery

The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].

You have to iterate through that values to get actuall value. Like the following

jQuery provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (linktext, link) {
        console.log(linktext);
        console.log(link);
    });
});

Now just create an Hyperlink using that info.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

  using (MemoryStream mem = new MemoryStream())
  {
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);

    // Add a WorkbookPart to the document.
    WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet(new SheetData());

    // Add Sheets to the Workbook.
    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

    // Add a row to the cell table.
    Row row;
    row = new Row() { RowIndex = 1 };
    sheetData.Append(row);

    // In the new row, find the column location to insert a cell in A1.  
    Cell refCell = null;
    foreach (Cell cell in row.Elements<Cell>())
    {
      if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
      {
        refCell = cell;
        break;
      }
    }

    // Add the cell to the cell table at A1.
    Cell newCell = new Cell() { CellReference = "A1" };
    row.InsertBefore(newCell, refCell);

    // Set the cell value to be a numeric value of 100.
    newCell.CellValue = new CellValue("100");
    newCell.DataType = new EnumValue<CellValues>(CellValues.Number);

    // Append a new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet()
    {
      Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
      SheetId = 1,
      Name = "mySheet"
    };

    sheets.Append(sheet);

    workbookpart.Workbook.Save();
    spreadsheetDocument.Close();

    return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
  }

Creating a BLOB from a Base64 string in JavaScript

See this example: https://jsfiddle.net/pqhdce2L/

_x000D_
_x000D_
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
  contentType = contentType || '';_x000D_
  sliceSize = sliceSize || 512;_x000D_
_x000D_
  var byteCharacters = atob(b64Data);_x000D_
  var byteArrays = [];_x000D_
_x000D_
  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    var byteNumbers = new Array(slice.length);_x000D_
    for (var i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
    _x000D_
  var blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

Making a Simple Ajax call to controller in asp.net mvc

First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..

Here is your controller code:

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FirstAjax(string a)
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   

This is how your view should look like:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
    var a = "Test";
    $.ajax({
        url: "../../Home/FirstAjax",
        type: "GET",
        data: { a : a },
        success: function (response) {
            alert(response);
        },
        error: function (response) {
            alert(response);
        }
    });
});
</script>

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

appending array to FormData and send via AJAX

I've fixed the typescript version. For javascript, just remove type definitions.

  _getFormDataKey(key0: any, key1: any): string {
    return !key0 ? key1 : `${key0}[${key1}]`;
  }
  _convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
    let formData = frmData || new FormData();

    if (!model) return formData;

    if (model instanceof Date) {
      formData.append(key, model.toISOString());
    } else if (model instanceof Array) {
      model.forEach((element: any, i: number) => {
        this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
      });
    } else if (typeof model === 'object' && !(model instanceof File)) {
      for (let propertyName in model) {
        if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
        this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
      }
    } else {
      formData.append(key, model);
    }

    return formData;
  }

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.

Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.

You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.

In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.

gridview data export to excel in asp.net

Instead of doing all these.. cant you use a simpler approach as shown below.

Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

You can get the entire walkthrough here

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case, neither the port nor the host was the problem. The index.js was divided into 2 files. server.js:

//server.js
const express = require('express')
const path = require('path')

const app = express()

app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app

//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
    console.log('Server is running s on port: ' + port)
});

from package.json we ran node app.js.

Apparently that was the problem. Once I combined the two into one file, the Heroku app deployed as expected.

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

Try browse the WCF in IIS see if it's alive and works normally,

In my case it's because the physical path of the WCF is misdirected.

Setting DEBUG = False causes 500 Error

I know this post is quite old but it's still perfectly relevant today.

For what it's worth - I was getting a 500 with DEBUG = False for all pages on my site.

I got no traceback when in debug.

I had to go through every static link in my templates within my site and found one / (forward slash) in front of my image source. {% static ... %}. This caused the 500 error in DEBUG = False but worked perfectly fine in Debug = True with no errors. Very annoying! Be warned! Many hours of time wasted due to a forward slash...

The input is not a valid Base-64 string as it contains a non-base 64 character

And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file

string string64 = string64.Replace(@"""", string.Empty);
byte[] bytes = Convert.ToBase64String(string64);

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

Mongoose delete array element in document and save

Answers above are shown how to remove an array and here is how to pull an object from an array.

Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/

db.survey.update( // select your doc in moongo
    { }, // your query, usually match by _id
    { $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
    { multi: true } // set this to true if you want to remove multiple elements.
)

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

include antiforgerytoken in ajax post ASP.NET MVC

it is so simple! when you use @Html.AntiForgeryToken() in your html code it means that server has signed this page and each request that is sent to server from this particular page has a sign that is prevented to send a fake request by hackers. so for this page to be authenticated by the server you should go through two steps:

1.send a parameter named __RequestVerificationToken and to gets its value use codes below:

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
   }
</script>

for example take an ajax call

$.ajax({
    type: "POST",
    url: "/Account/Login",
    data: {
        __RequestVerificationToken: gettoken(),
        uname: uname,
        pass: pass
    },
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    success: successFu,
});

and step 2 just decorate your action method by [ValidateAntiForgeryToken]

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.

In Jelly Bean it is: Settings > Data Usage > mobile data

Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.

For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.

It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

what is the use of "response.setContentType("text/html")" in servlet

response.setContentType("text/html");

Above code would be include in "HTTP response" to inform the browser about the format of the response, so that the browser can interpret it.

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

how to download file using AngularJS and calling MVC API?

I had the same problem. Solved it by using a javascript library called FileSaver

Just call

saveAs(file, 'filename');

Full http post request:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            saveAs(file, 'filename.pdf');
        });

Can I append an array to 'formdata' in javascript?

We can simply do like this.

_x000D_
_x000D_
formData = new FormData;
words = ["apple", "ball", "cat"]
words.forEach((item) => formData.append("words[]", item))

// verify the data
console.log(formData.getAll("words[]"))
//["apple", "ball", "cat"]
_x000D_
_x000D_
_x000D_

On server-side you will get words = ["apple", "ball", "cat"]

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

Go through C:\apache-tomcat-7.0.47\lib path (this path may be differ based on where you installed the Tomcat server) then past ojdbc14.jar if its not contain.

Then restart the server in eclipse then run your app on server

POST string to ASP.NET Web Api application - returns null

I use this code to post HttpRequests.

/// <summary>
        /// Post this message.
        /// </summary>
        /// <param name="url">URL of the document.</param>
        /// <param name="bytes">The bytes.</param>
        public T Post<T>(string url, byte[] bytes)
    {
        T item;
        var request = WritePost(url, bytes);

        using (var response = request.GetResponse() as HttpWebResponse)
        {
            item = DeserializeResponse<T>(response);
            response.Close();
        }

        return item;
    }

    /// <summary>
    /// Writes the post.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="bytes">The bytes.</param>
    /// <returns></returns>
    private static HttpWebRequest WritePost(string url, byte[] bytes)
    {
        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        Stream stream = null;
        try
        {
            request.Headers.Clear();
            request.PreAuthenticate = true;
            request.Connection = null;
            request.Expect = null;
            request.KeepAlive = false;
            request.ContentLength = bytes.Length;
            request.Timeout = -1;
            request.Method = "POST";
            stream = request.GetRequestStream();
            stream.Write(bytes, 0, bytes.Length);
        }
        catch (Exception e)
        {
            GetErrorResponse(url, e);
        }
        finally
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }
        return request;
    }

In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";)

update

I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.

On the server, try getting the bytes from stream. The following code is what I use.

     /// <summary> Gets the body. </summary>
     /// <returns> The body. </returns>
     protected byte[] GetBytes()
     {
       byte[] bytes;
        using (var binaryReader = new BinaryReader(Request.InputStream))
        {
            bytes = binaryReader.ReadBytes(Request.ContentLength);
        }

         return bytes;
     }

Datatables warning(table id = 'example'): cannot reinitialise data table

Try adding "bDestroy": true to the options object literal, e.g.

$('#dataTable').dataTable({
    ...
    ....
    "bDestroy": true
});

Source: iodocs.com

or Remove the first:

$(document).ready(function() {
    $('#example').dataTable();
} );

In your case is the best option vjk.

Duplicate headers received from server

Just put a pair of double quotes around your file name like this:

this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.

In my case the solution was as follows:

Script - stringify the original array (without using a named property)

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: mycontrolleraction,
        data: JSON.stringify(things)
    });

And in the controller method, use [FromBody]

    [HttpPost]
    public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }

Failures include:

  • Naming the content

    data: { content: nodes }, // Server error 500

  • Not having the contentType = Server error 500

Notes

  • dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
  • List<Thing> also works in the controller method

How to solve "Connection reset by peer: socket write error"?

I had the same problem with small difference:

Exception was raised at the moment of flushing

It is a different stackoverflow issue. The brief explanation was a wrong response header setting:

response.setHeader("Content-Encoding", "gzip");

despite uncompressed response data content.

So the the connection was closed by the browser.

How to ignore the certificate check when ssl

For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

In .NET 4.0, the Lambda Expression can be applied to the global filter as such

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.

I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.

Here are essential parts of related functions in Start class look like:

ConfigureServices method:

    services.AddCors(options =>
    {
        options.AddPolicy(name: MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder
                                  .WithOrigins("http://localhost:4200")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  //.AllowCredentials()
                                  ;
                          });
    });

Configure method:

        app.UseCors(MyAllowSpecificOrigins);

Found this from:

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

from jquery $.ajax to angular $http

We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.

$http service methods are listed below,

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

One of the Example:

    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

In my case, I had the mapping b/w A and B like

A has

@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
Set<B> bs;

in the DAO layer, the method needs to be annotated with @Transactional if you haven't annotated the mapping with Fetch Type - Eager

Powershell v3 Invoke-WebRequest HTTPS error

I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.

Here are few things you can try out

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

Try this to see if you can filter out the columns that you are getting from the API

$a.Results | ft

or, you can try using this also

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

Curl Style Headers

$b.Headers

I tested the IRM / IWR with the twitter JSON api.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

Hope this helps.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I added the control to the Triggers tag in the update panel:

    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="exportLinkButton" />
    </Triggers>
</asp:UpdatePanel>

This way the exportLinkButton will trigger the UpdatePanel to update.
More info here.

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Try the following:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

Sending JSON to PHP using ajax

Lose the contentType: "application/json; charset=utf-8",. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).

That should make what you have work.

Thing is, you don't need to use JSON.stringify or json_decode here at all. Just do:

data: {myData:postData},

Then in PHP:

$obj = $_POST['myData'];

Uploading both data and files in one form using Ajax?

For me, it didn't work without enctype: 'multipart/form-data' field in the Ajax request. I hope it helps someone who is stuck in a similar problem.

Even though the enctype was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype without explicit declaration (jQuery 3.3.1).

// Tested, this works for me (jQuery 3.3.1)

fileUploadForm.submit(function (e) {   
    e.preventDefault();
    $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            enctype: 'multipart/form-data',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (data) {
                console.log('Thank God it worked!');
            }
        }
    );
});

// enctype field was set in the form but Ajax request didn't set it by default.

<form action="process/file-upload" enctype="multipart/form-data" method="post" >

     <input type="file" name="input-file" accept="text/plain" required> 
     ...
</form>

As others mentioned above, please also pay special attention to the contentType and processData fields.

Display PNG image as response to jQuery AJAX request

This allows you to just get the image data and set to the img src, which is cool.

var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );        
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
    var blob = oReq.response;
    var imgSrc = URL.createObjectURL( blob );                        
    var $img = $( '<img/>', {                
        "alt": "test image",
        "src": imgSrc
    } ).appendTo( $( '#bb_theImageContainer' ) );
    window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );

The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.

How to send data in request body with a GET when using jQuery $.ajax()

In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.

You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.

If you aren't absolutely tied to GET requests with the body being the data, you have two options.

POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.

GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.

url: 'somesite.com/models/thing?ids=1,2,3'

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

Ajax call Into MVC Controller- Url Issue

you have an type error in example of code. You forget curlybracket after success

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

MVC: How to Return a String as JSON

Use the following code in your controller:

return Json(new { success = string }, JsonRequestBehavior.AllowGet);

and in JavaScript:

success: function (data) {
    var response = data.success;
    ....
}

Cannot set content-type to 'application/json' in jQuery.ajax

I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.

I'm using that construction:

$.ajax({
   url: path,
   type: "POST",
   contentType: "text/plain",
   data: {"some":"some"}
}

as you can see, if I use

contentType: "",

or

contentType: "text/plain", //chrome

Everything works fine.

I'm not 100% sure that it's all that you need, cause I've also changed headers.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

With this error I was able to trace it, thanks to @Yaur, you need to basically check the service (WCF) if it's running and also check the outbound and inbound TCP properties on your advance firewall settings.

How do I make calls to a REST API using C#?

    var TakingRequset = WebRequest.Create("http://xxx.acv.com/MethodName/Get");
    TakingRequset.Method = "POST";
    TakingRequset.ContentType = "text/xml;charset=utf-8";
    TakingRequset.PreAuthenticate = true;

    //---Serving Request path query
     var PAQ = TakingRequset.RequestUri.PathAndQuery;

    //---creating your xml as per the host reqirement
    string xmlroot=@"<root><childnodes>passing parameters</childnodes></root>";
    string xmlroot2=@"<root><childnodes>passing parameters</childnodes></root>";

    //---Adding Headers as requested by host 
    xmlroot2 = (xmlroot2 + "XXX---");
    //---Adding Headers Value as requested by host 
  //  var RequestheaderVales = Method(xmlroot2);

    WebProxy proxy = new WebProxy("XXXXX-----llll", 8080);
    proxy.Credentials = new NetworkCredential("XXX---uuuu", "XXX----", "XXXX----");
    System.Net.WebRequest.DefaultWebProxy = proxy;


    // Adding The Request into Headers
    TakingRequset.Headers.Add("xxx", "Any Request Variable ");
    TakingRequset.Headers.Add("xxx", "Any Request Variable");

    byte[] byteData = Encoding.UTF8.GetBytes(xmlroot);
    TakingRequset.ContentLength = byteData.Length;

    using (Stream postStream = TakingRequset.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
        postStream.Close();
    }



    StreamReader stredr = new StreamReader(TakingRequset.GetResponse().GetResponseStream());
    string response = stredr.ReadToEnd();

System.Net.Http: missing from namespace? (using .net 4.5)

You'll need a using System.Net.Http at the top.

How to post JSON to a server using C#?

I find this to be the friendliest and most concise way to post an read JSON data:

var url = @"http://www.myapi.com/";
var request = new Request { Greeting = "Hello world!" };
var json = JsonSerializer.Serialize<Request>(request);
using (WebClient client = new WebClient())
{
    var jsonResponse = client.UploadString(url, json);
    var response = JsonSerializer.Deserialize<Response>(jsonResponse);
}

I'm using Microsoft's System.Text.Json for serializing and deserializing JSON. See NuGet.

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

ASP.Net Download file to client browser

Try changing it to.

 Response.Clear();
 Response.ClearHeaders();
 Response.ClearContent();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
 Response.AddHeader("Content-Length", file.Length.ToString());
 Response.ContentType = "text/plain";
 Response.Flush();
 Response.TransmitFile(file.FullName);
 Response.End();

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

this may help

Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How to get error information when HttpWebRequest.GetResponse() fails

I faced a similar situation:

I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.

However, when reading the response using GetResponseStream(), got the error:

Stream not readable

So, this code worked for me:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

If you importing some other project in xcode and if current and import project both have same files in Compiler source then just remove same file in current project in "Build phase' settings. It worked for me.

How to send FormData objects with Ajax-requests in jQuery?

If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.

Samples http://jquery.malsup.com/form/#ajaxSubmit

rough view :

<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>


<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{ 
    information= responseText;
    callAjaxtolist();
    $("#AddPhotoForm").resetForm();
    $("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');        
};

$(document).ready(function(){
    $('.add_new_photo_div').live('click',function(){
            var options = {success:showResponseAfterAddPhoto};  
            $("#AddPhotoForm").ajaxSubmit(options);
        });
});
</script>

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
}

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.

...

Jquery Ajax Posting json to webservice

I have encountered this one too and this is my solution.

If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:

$.post(CONTEXT+"servlet/capture",{
        yesTransactionId : yesTransactionId, 
        productOfferId : productOfferId
        },
        function(data){
            try{
                var trimData = $.trim(JSON.stringify(data));
                var obj      = $.parseJSON(trimData);
                if(obj.success == 'true'){ 
                    //some codes ...

How can I use JQuery to post JSON data?

Base on lonesomeday's answer, I create a jpost that wraps certain parameters.

$.extend({
    jpost: function(url, body) {
        return $.ajax({
            type: 'POST',
            url: url,
            data: JSON.stringify(body),
            contentType: "application/json",
            dataType: 'json'
        });
    }
});

Usage:

$.jpost('/form/', { name: 'Jonh' }).then(res => {
    console.log(res);
});

Ajax request returns 200 OK, but an error event is fired instead of success

I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.

Then in your Ajax call please mention dataType='text'.

It will resolve the problem.

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

what you have is fine - however to save some typing, you can simply use for your data


data: $('#formId').serialize()

see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).

The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.

If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.

JQuery, Spring MVC @RequestBody and JSON - making it work together

In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.

Returning a file to View/Download in ASP.NET MVC

Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link How to download files using asp.net core

[Route("api/[controller]")]
public class DownloadController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Download()
    {
        var path = @"C:\Vetrivel\winforms.png";
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            ...
        };
    }
}

Spring MVC: How to return image in @ResponseBody?

With Spring 4.1 and above, you can return pretty much anything (such as pictures, pdfs, documents, jars, zips, etc) quite simply without any extra dependencies. For example, the following could be a method to return a user's profile picture from MongoDB GridFS:

@RequestMapping(value = "user/avatar/{userId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> downloadUserAvatarImage(@PathVariable Long userId) {
    GridFSDBFile gridFsFile = fileService.findUserAccountAvatarById(userId);

    return ResponseEntity.ok()
            .contentLength(gridFsFile.getLength())
            .contentType(MediaType.parseMediaType(gridFsFile.getContentType()))
            .body(new InputStreamResource(gridFsFile.getInputStream()));
}

The things to note:

  • ResponseEntity with InputStreamResource as a return type

  • ResponseEntity builder style creation

With this method you dont have to worry about autowiring in the HttpServletResponse, throwing an IOException or copying stream data around.

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character. In the case of an ampresand, you should replace the character with %26.

.NET provides a nice way of encoding the entire string for you though:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);

UTF-8 encoding problem in Spring MVC

Also add to your beans :

   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
        </bean></bean>

For @ExceptionHandler :

enter code<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
    <property name="messageConverters">
        <array>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                        <value>application/x-www-form-urlencoded;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </array>
    </property>
</bean>

If you use <mvc:annotation-driven/> it should be after beans.

Download/Stream file from URL - asp.net

The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).

The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.

So what was missing was:

Response.End();

See also: Trying to stream a PDF file with asp.net is producing a "damaged file"

Pass a datetime from javascript to c# (Controller)

var Ihours = Math.floor(TotMin / 60);          

var Iminutes = TotMin % 60; var TotalTime = Ihours+":"+Iminutes+':00';

   $.ajax({
            url: ../..,
            cache: false,
            type: "POST",                
            data: JSON.stringify({objRoot: TotalTime}) ,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {

            },
            error: function (er) {
                console.log(er);
            }
        });

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

iOS UIImagePickerController result image orientation after upload

I used this page when designing my app that takes pictures and I found that the following method will correct the orientation and use less memory and processor than previous answers:

CGImageRef cgRef = image.CGImage;
image = [[UIImage alloc] initWithCGImage:cgRef scale:1.0 orientation:UIImageOrientationUp];

This basically just rewraps the actual image data with a new orientation. I was using @an0's code but it makes a new image in memory which can be taxing on a 3264x2448 image that you might get from a camera.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Sending multipart/formdata with jQuery.ajax

If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.

$('#my-form').submit( function(e) {
    e.preventDefault();

    var data = new FormData(this); // <-- 'this' is your form element

    $.ajax({
            url: '/my_URL/',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',     
            success: function(data){
            ...

HTTP response header content disposition for attachments

Try changing your Content Type (media type) to application/x-download and your Content-Disposition to: attachment;filename=" + fileName;

response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);

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

For me the issue was resolved when I commented the following line in Web.config

<httpErrors errorMode="Detailed" />

jQuery Call to WebService returns "No Transport" error

For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.

I built jquery myself with webpack picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.

After a long debugging, the problem turns out to be XMLHttpRequest is pluggable in jquery and it not include by default.

You have to explicitly include jquery/src/ajax/xhr file in order to make the ajax working in browsers.

How to create folder with PHP code?

You can create it easily:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

Here it goes an example:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

How do I output an ISO 8601 formatted string in JavaScript?

I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;
};

The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))
};

toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    }
    return str;
}

Calling Python in PHP

Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

On - window.location.hash - Change?

I was using this in a react application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

window.addEventListener('hashchange', doSomethingWithChangeFunction());

Then

doSomethingWithChangeFunction () { 
    // Get new hash value
    let urlParam = window.location.hash;
    // Do something with new hash value
};

Worked a treat, works with forward and back browser buttons and also in browser history.

What is a MIME type?

I couldn't possibly explain it better than wikipedia does: http://en.wikipedia.org/wiki/MIME_type

In addition to e-mail applications, Web browsers also support various MIME types. This enables the browser to display or output files that are not in HTML format.

IOW, it helps the browser (or content consumer, because it may not just be a browser) determine what content they are about to consume; this means a browser may be able to make a decision on the correct plugin to use to display content, or a media player may be able to load up the correct codec or plugin.

Lombok added but getters and setters not recognized in Intellij IDEA

Complete steps to fix or configure lombok.

1. Add dependency

<dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.18.8</version>
          <scope>provided</scope>
      </dependency>

2. Install the plugin of Lombok for ide. File > Settings > Plugins > Search (lombok) > install

3.Ticking the "Enable annotation processing" checkbox using below steps:- Settings->Compiler->Annotation Processors

4.Restart for change to take effect.

how to set select element as readonly ('disabled' doesnt pass select value on server)

To simplify things here's a jQuery plugin that can achieve this goal : https://github.com/haggen/readonly

  1. Include readonly.js in your project. (also needs jquery)
  2. Replace .attr('readonly', 'readonly') with .readonly() instead. That's it.

    For example, change from $(".someClass").attr('readonly', 'readonly'); to $(".someClass").readonly();.

How to JSON decode array elements in JavaScript?

I decode JSON this way:

eval( 'var from_json_object = ' + my_json_str + ';' );

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Multiline TextBox multiple newline

textBox1.Text = "Line1\r\r\Line2";
Solved the problem.

How to see top processes sorted by actual memory usage?

You have this simple command:

$ free -h

Java: Calculating the angle between two points in degrees

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

What is the correct way to create a single-instance WPF application?

MSDN actually has a sample application for both C# and VB to do exactly this: http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx

The most common and reliable technique for developing single-instance detection is to use the Microsoft .NET Framework remoting infrastructure (System.Remoting). The Microsoft .NET Framework (version 2.0) includes a type, WindowsFormsApplicationBase, which encapsulates the required remoting functionality. To incorporate this type into a WPF application, a type needs to derive from it, and be used as a shim between the application static entry point method, Main, and the WPF application's Application type. The shim detects when an application is first launched, and when subsequent launches are attempted, and yields control the WPF Application type to determine how to process the launches.

  • For C# people just take a deep breath and forget about the whole 'I don't wanna include VisualBasic DLL'. Because of this and what Scott Hanselman says and the fact that this pretty much is the cleanest solution to the problem and is designed by people who know a lot more about the framework than you do.
  • From a usability standpoint the fact is if your user is loading an application and it is already open and you're giving them an error message like 'Another instance of the app is running. Bye' then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.

The framework already has support for this - its just that some idiot named the DLL Microsoft.VisualBasic and it didn't get put into Microsoft.ApplicationUtils or something like that. Get over it - or open up Reflector.

Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to take a look at this too.

A formula to copy the values from a formula to another column

What about trying with VLOOKUP? The syntax is:

=VLOOKUP(cell you want to copy, range you want to copy, 1, FALSE).

It should do the trick.

Attach the Source in Eclipse of a jar

  1. Download JDEclipse from http://java-decompiler.github.io/
  2. Follow the installation steps
  3. If you still didn't find the source, right click on the jar file and select "Attach Library Source" option from the project folder, as you can see below.

Drop down option location

Dialog with transparent background in Android

In my case solution works like this:

dialog_AssignTag.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

And Additionally in Xml of custom dialog:

android:alpha="0.8"

pg_config executable not found

Simply run the following:

sudo apt install libpq-dev

Fixed the issue for me

github: server certificate verification failed

You can also disable SSL verification, (if the project does not require a high level of security other than login/password) by typing :

git config --global http.sslverify false

enjoy git :)

Android get image from gallery into ImageView

Simple pass Intent first:

Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

And you will get picture path on your onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

for full source code here

Rename column SQL Server 2008

Try:

EXEC sp_rename 'TableName.OldName', 'NewName', 'COLUMN'

what is the use of xsi:schemaLocation?

According to the spec for locating Schemas

there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy

(thanks for being unambiguous, spec!)

and

in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.

So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation attribute), depending on your "community." If you specify a specific schemaLocation, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation or noNamespaceSchemaLocation attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).

Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd" typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd (so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.

Removing page title and date when printing web page (with CSS?)

There's a facility to have a separate style sheet for print, using

 <link type="text/css" rel="stylesheet" media="print" href="print.css">

I don't know if it does what you want though.

Get first key in a (possibly) associative array?

I think the best and fastest way to do it is:

$first_key=key(array_slice($array, 0, 1, TRUE))

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

Text in HTML Field to disappear when clicked?

How about something like this?

<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">

This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

Query to display all tablespaces in a database and datafiles

Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?

select tablespace_name, 
       file_name
from dba_tablespaces
order by tablespace_name, 
         file_name;

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

In Html5, you can now use

<form>
<input type="number" min="1" max="100">
</form>

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

How to use PowerShell select-string to find more than one pattern in a file?

If you want to match the two words in either order, use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'

If Failed always comes after VendorEnquiry on the line, just use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

If you are dealing with a table and one of the dates happens to be null, you can code it like this:

  @{
     if (Model.SomeCollection[i].date_due == null)
       {
         <td><input type='date' id="@("dd" + i)" name="dd" /></td>
       }
       else
       {
         <td><input type='date' value="@Model.SomeCollection[i].date_due.Value.ToString("yyyy-MM-dd")" id="@("dd" + i)" name="dd" /></td>
       }
   }

jQuery: Check if button is clicked

$('input[type="button"]').click(function (e) {
    if (e.target) {
        alert(e.target.id + ' clicked');
    }
});

you should tweak this a little (eg. use a name in stead of an id to alert), but this way you have more generic function.

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

How to parse Excel (XLS) file in Javascript/HTML5

If you want the simplest and tiniest way of reading an *.xlsx file in a browser then this library might do:

https://catamphetamine.github.io/read-excel-file/

<input type="file" id="input" />
import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')

input.addEventListener('change', () => {
  readXlsxFile(input.files[0]).then((data) => {
    // `data` is an array of rows
    // each row being an array of cells.
  })
})

In the example above data is raw string data. It can be parsed to JSON with a strict schema by passing schema argument. See API docs for an example of that.

API docs: http://npmjs.com/package/read-excel-file

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

In my case my site on IIS was pointing to a different project than the one I was running on visual studio.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I wanted to do away with lockfiles, lockdirs, special locking programs and even pidof since it isn't found on all Linux installations. Also wanted to have the simplest code possible (or at least as few lines as possible). Simplest if statement, in one line:

if [[ $(ps axf | awk -v pid=$$ '$1!=pid && $6~/'$(basename $0)'/{print $1}') ]]; then echo "Already running"; exit; fi

Remove everything after a certain character

You can also use the split() function. This seems to be the easiest one that comes to my mind :).

url.split('?')[0]

jsFiddle Demo

One advantage is this method will work even if there is no ? in the string - it will return the whole string.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

How can I parse a JSON file with PHP?

Try:

$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);

foreach ($json as $key => $value) {
    if (!is_array($value)) {
        echo $key . '=>' . $value . '<br />';
    } else {
        foreach ($value as $key => $val) {
            echo $key . '=>' . $val . '<br />';
        }
    }
}

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

You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it's the "Pythonic" way, but that's one area where I part ways with them. To me, it's neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.

I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness.

Here's a quick and dirty edit of Bruno's post:

import sys, time, re

g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")

testvals = [
    # integers
    0, 1, -1, 1.0, -1.0,
    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
    # non-integers
    'abc 123',
    1.1, -1.1, '1.1', '-1.1', '+1.1',
    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
    '1.0.', '1..0', '1..',
    '0.0.', '0..0', '0..',
    'one', object(), (1,2,3), [1,2,3], {'one':'two'},
    # with spaces
    ' 0 ', ' 0.', ' .0','.01 '
]

def isInt_try(v):
    try:     i = int(v)
    except:  return False
    return True

def isInt_str(v):
    v = str(v).strip()
    return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def isInt_re(v):
    import re
    if not hasattr(isInt_re, 'intRegex'):
        isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
    return isInt_re.intRegex.match(str(v).strip()) is not None

def isInt_re2(v):
    return g_intRegex.match(str(v).strip()) is not None

def check_int(s):
    s = str(s)
    if s[0] in ('-', '+'):
        return s[1:].isdigit()
    return s.isdigit()    


def timeFunc(func, times):
    t1 = time.time()
    for n in range(times):
        for v in testvals: 
            r = func(v)
    t2 = time.time()
    return t2 - t1

def testFuncs(funcs):
    for func in funcs:
        sys.stdout.write( "\t%s\t|" % func.__name__)
    print()
    for v in testvals:
        if type(v) == type(''):
            sys.stdout.write("'%s'" % v)
        else:
            sys.stdout.write("%s" % str(v))
        for func in funcs:
            sys.stdout.write( "\t\t%s\t|" % func(v))
        sys.stdout.write("\r\n") 

if __name__ == '__main__':
    print()
    print("tests..")
    testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
    print()

    print("timings..")
    print("isInt_try:   %6.4f" % timeFunc(isInt_try, 10000))
    print("isInt_str:   %6.4f" % timeFunc(isInt_str, 10000)) 
    print("isInt_re:    %6.4f" % timeFunc(isInt_re, 10000))
    print("isInt_re2:   %6.4f" % timeFunc(isInt_re2, 10000))
    print("check_int:   %6.4f" % timeFunc(check_int, 10000))

Here are the performance comparison results:

timings..
isInt_try:   0.6426
isInt_str:   0.7382
isInt_re:    1.1156
isInt_re2:   0.5344
check_int:   0.3452

A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think.

EDIT:

I've updated the code above to work in Python 3.5, and to include the check_int function from the currently most voted up answer, and to use the current most popular regex that I can find for testing for integer-hood. This regex rejects strings like 'abc 123'. I've added 'abc 123' as a test value.

It is Very Interesting to me to note, at this point, that NONE of the functions tested, including the try method, the popular check_int function, and the most popular regex for testing for integer-hood, return the correct answers for all of the test values (well, depending on what you think the correct answers are; see the test results below).

The built-in int() function silently truncates the fractional part of a floating point number and returns the integer part before the decimal, unless the floating point number is first converted to a string.

The check_int() function returns false for values like 0.0 and 1.0 (which technically are integers) and returns true for values like '06'.

Here are the current (Python 3.5) test results:

              isInt_try |       isInt_str       |       isInt_re        |       isInt_re2       |   check_int   |
0               True    |               True    |               True    |               True    |       True    |
1               True    |               True    |               True    |               True    |       True    |
-1              True    |               True    |               True    |               True    |       True    |
1.0             True    |               True    |               False   |               False   |       False   |
-1.0            True    |               True    |               False   |               False   |       False   |
'0'             True    |               True    |               True    |               True    |       True    |
'0.'            False   |               True    |               False   |               False   |       False   |
'0.0'           False   |               True    |               False   |               False   |       False   |
'1'             True    |               True    |               True    |               True    |       True    |
'-1'            True    |               True    |               True    |               True    |       True    |
'+1'            True    |               True    |               True    |               True    |       True    |
'1.0'           False   |               True    |               False   |               False   |       False   |
'-1.0'          False   |               True    |               False   |               False   |       False   |
'+1.0'          False   |               True    |               False   |               False   |       False   |
'06'            True    |               True    |               False   |               False   |       True    |
'abc 123'       False   |               False   |               False   |               False   |       False   |
1.1             True    |               False   |               False   |               False   |       False   |
-1.1            True    |               False   |               False   |               False   |       False   |
'1.1'           False   |               False   |               False   |               False   |       False   |
'-1.1'          False   |               False   |               False   |               False   |       False   |
'+1.1'          False   |               False   |               False   |               False   |       False   |
'1.1.1'         False   |               False   |               False   |               False   |       False   |
'1.1.0'         False   |               False   |               False   |               False   |       False   |
'1.0.1'         False   |               False   |               False   |               False   |       False   |
'1.0.0'         False   |               False   |               False   |               False   |       False   |
'1.0.'          False   |               False   |               False   |               False   |       False   |
'1..0'          False   |               False   |               False   |               False   |       False   |
'1..'           False   |               False   |               False   |               False   |       False   |
'0.0.'          False   |               False   |               False   |               False   |       False   |
'0..0'          False   |               False   |               False   |               False   |       False   |
'0..'           False   |               False   |               False   |               False   |       False   |
'one'           False   |               False   |               False   |               False   |       False   |
<obj..>         False   |               False   |               False   |               False   |       False   |
(1, 2, 3)       False   |               False   |               False   |               False   |       False   |
[1, 2, 3]       False   |               False   |               False   |               False   |       False   |
{'one': 'two'}  False   |               False   |               False   |               False   |       False   |
' 0 '           True    |               True    |               True    |               True    |       False   |
' 0.'           False   |               True    |               False   |               False   |       False   |
' .0'           False   |               False   |               False   |               False   |       False   |
'.01 '          False   |               False   |               False   |               False   |       False   |

Just now I tried adding this function:

def isInt_float(s):
    try:
        return float(str(s)).is_integer()
    except:
        return False

It performs almost as well as check_int (0.3486) and it returns true for values like 1.0 and 0.0 and +1.0 and 0. and .0 and so on. But it also returns true for '06', so. Pick your poison, I guess.

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

Date format in the json output using spring boot

If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

For Example :

public class Subject {

     private String uid;
     private String number;
     private String initials;

     @JsonFormat(pattern="yyyy-MM-dd")
     private Date dateOfBirth;  

     //Other Code  

}  

From Docs :

annotation used for configuring details of how values of properties are to be serialized.

More Reference Doc

Hope this helps.

Using "like" wildcard in prepared statement

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);

Mapping a JDBC ResultSet to an object

No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.

Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.

But as of now use this:

List<User> users=new ArrayList<User>();

while(rs.next()) {
   User user = new User();      
   user.setUserId(rs.getString("UserId"));
   user.setFName(rs.getString("FirstName"));
  ...
  ...
  ...


  users.add(user);
} 

Using SSIS BIDS with Visual Studio 2012 / 2013

Today March 6, 2013, Microsoft released SQL Server Data Tools – Business Intelligence for Visual Studio 2012 (SSDT BI) templates. With SSDT BI for Visual Studio 2012 you can develop and deploy SQL Server Business intelligence projects. Projects created in Visual Studio 2010 can be opened in Visual Studio 2012 and the other way around without upgrading or downgrading – it just works.

The download/install is named to ensure you get the SSDT templates that contain the Business Intelligence projects. The setup for these tools is now available from the web and can be downloaded in multiple languages right here: http://www.microsoft.com/download/details.aspx?id=36843

Removing a Fragment from the back stack

What happens if the fragment that you want to remove is not on top of the stack?

Then you can use theses functions

popBackStack(int arg0, int arg1);

popBackStack(String arg0, int arg1);

How to use HTML Agility pack

try this

string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());

private string ParseHmlBody(string html)
        {
            string body = string.Empty;
            try
            {
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);
                var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
                body = htmlBody.OuterHtml;
            }
            catch (Exception ex)
            {

                dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
            }
            return body;
        }

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.

Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.

You can set some value which is present in the parent table and then adding foreign key worked for me.

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

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

How to access form methods and controls from a class in C#?

JUST YOU CAN SEND FORM TO CLASS LIKE THIS

Class1 excell = new Class1 (); //you must declare this in form as you want to control

excel.get_data_from_excel(this); // And create instance for class and sen this form to another class

INSIDE CLASS AS YOU CREATE CLASS1

class Class1
{
    public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
    {
        form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now
    }
}

IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Deletes all files and folders in the path.

function recurseRmdir($dir) {
  $files = array_diff(scandir($dir), array('.','..'));
  foreach ($files as $file) {
    (is_dir("$dir/$file")) ? recurseRmdir("$dir/$file") : unlink("$dir/$file");
  }
  return rmdir($dir);
}

Lists in ConfigParser

import ConfigParser
import os

class Parser(object):
    """attributes may need additional manipulation"""
    def __init__(self, section):
        """section to retun all options on, formatted as an object
        transforms all comma-delimited options to lists
        comma-delimited lists with colons are transformed to dicts
        dicts will have values expressed as lists, no matter the length
        """
        c = ConfigParser.RawConfigParser()
        c.read(os.path.join(os.path.dirname(__file__), 'config.cfg'))

        self.section_name = section

        self.__dict__.update({k:v for k, v in c.items(section)})

        #transform all ',' into lists, all ':' into dicts
        for key, value in self.__dict__.items():
            if value.find(':') > 0:
                #dict
                vals = value.split(',')
                dicts = [{k:v} for k, v in [d.split(':') for d in vals]]
                merged = {}
                for d in dicts:
                    for k, v in d.items():
                        merged.setdefault(k, []).append(v)
                self.__dict__[key] = merged
            elif value.find(',') > 0:
                #list
                self.__dict__[key] = value.split(',')

So now my config.cfg file, which could look like this:

[server]
credentials=username:admin,password:$3<r3t
loggingdirs=/tmp/logs,~/logs,/var/lib/www/logs
timeoutwait=15

Can be parsed into fine-grained-enough objects for my small project.

>>> import config
>>> my_server = config.Parser('server')
>>> my_server.credentials
{'username': ['admin'], 'password', ['$3<r3t']}
>>> my_server.loggingdirs:
['/tmp/logs', '~/logs', '/var/lib/www/logs']
>>> my_server.timeoutwait
'15'

This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from Parser, or re-doing the parsing job accomplished by the Parser class elsewhere.

Kill a postgresql session/connection

Remote scenario. But if you're trying to run tests in a rails app, and you get something like

"ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "myapp_test" is being accessed by other users DETAIL: There is 1 other session using the database."

Make sure you close pgAdmin or any other postgres GUI tools before running tests.

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

What is a lambda (function)?

It is a function that has no name. For e.g. in c# you can use

numberCollection.GetMatchingItems<int>(number => number > 5);

to return the numbers that are greater than 5.

number => number > 5

is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.

Remote origin already exists on 'git push' to a new repository

The previous solutions seem to ignore origin, and they only suggest to use another name. When you just want to use git push origin, keep reading.

The problem appears because a wrong order of Git configuration is followed. You might have already added a 'git origin' to your .git configuration.

You can change the remote origin in your Git configuration with the following line:

git remote set-url origin [email protected]:username/projectname.git

This command sets a new URL for the Git repository you want to push to. Important is to fill in your own username and projectname

Facebook API: Get fans of / people who like a page

Technically this FQL query should work, but for some reason Facebook disallows it because of a missing index. Not sure if that is because of policy or they just forgot.

SELECT uid FROM page_fans WHERE page_id="YOUR_PAGE_ID"

How to set index.html as root file in Nginx?

in your location block you can do:

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

which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html

Content Type text/xml; charset=utf-8 was not supported by service

In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:29495/IntegrationService.asmx"
                binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
                contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>

Both my client and server use basicHttpBinding. I hope this helps the others :)

How do I change the formatting of numbers on an axis with ggplot?

I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:

 ggplot + scale_x_continuous(labels = human_gbp)

which give you human readable numbers for x or y axes (or any number in general really).

You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.

Eclipse - Failed to create the java virtual machine

I had also entered the path of MinGW complier for C++. After removing it, the error disappeared.

What's the most elegant way to cap a number to a segment?

The way you do it is pretty standard. You can define a utility clamp function:

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

(Although extending language built-ins is generally frowned upon)

Pretty-Print JSON in Java

Following the JSON-P 1.0 specs (JSR-353) a more current solution for a given JsonStructure (JsonObject or JsonArray) could look like this:

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.json.Json;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;

public class PrettyJson {

    private static JsonWriterFactory FACTORY_INSTANCE;

    public static String toString(final JsonStructure status) {

        final StringWriter stringWriter = new StringWriter();

        final JsonWriter jsonWriter = getPrettyJsonWriterFactory()
                .createWriter(stringWriter);

        jsonWriter.write(status);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static JsonWriterFactory getPrettyJsonWriterFactory() {
        if (null == FACTORY_INSTANCE) {
            final Map<String, Object> properties = new HashMap<>(1);
            properties.put(JsonGenerator.PRETTY_PRINTING, true);
            FACTORY_INSTANCE = Json.createWriterFactory(properties);
        }
        return FACTORY_INSTANCE;
    }

}

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

How to check if a string starts with one of several prefixes?

if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)

You need to include the whole str.startsWith(otherStr) for each item, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.

An example regular expression for detecting day name abbreviations would be:

if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {

Push Notifications in Android Platform

Android Cloud to Device Messaging Framework

Important: C2DM has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.

Kindly check the following link:

http://developer.android.com/guide/google/gcm/index.html

Copy Data from a table in one Database to another separate database

SELECT * INTO requires that the destination table not exist.

Try this.

INSERT INTO db1.dbo.TempTable
 (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable

How can I capture the result of var_dump to a string?

From the PHP manual:

This function displays structured information about one or more expressions that includes its type and value.

So, here is the real return version of PHP's var_dump(), which actually accepts a variable-length argument list:

function var_dump_str()
{
    $argc = func_num_args();
    $argv = func_get_args();

    if ($argc > 0) {
        ob_start();
        call_user_func_array('var_dump', $argv);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }

    return '';
}

How to set auto increment primary key in PostgreSQL?

If you want to do this in pgadmin, it is much easier. It seems in postgressql, to add a auto increment to a column, we first need to create a auto increment sequence and add it to the required column. I did like this.

1) Firstly you need to make sure there is a primary key for your table. Also keep the data type of the primary key in bigint or smallint. (I used bigint, could not find a datatype called serial as mentioned in other answers elsewhere)

2)Then add a sequence by right clicking on sequence-> add new sequence. If there is no data in the table, leave the sequence as it is, don't make any changes. Just save it. If there is existing data, add the last or highest value in the primary key column to the Current value in Definitions tab as shown below. enter image description here

3)Finally, add the line nextval('your_sequence_name'::regclass) to the Default value in your primary key as shown below.

enter image description here Make sure the sequence name is correct here. This is all and auto increment should work.

Spaces in URLs?

Spaces are simply replaced by "%20" like :

http://www.example.com/my%20beautiful%20page

How to move Docker containers between different hosts?

You cannot move a running docker container from one host to another.

You can commit the changes in your container to an image with docker commit, move the image onto a new host, and then start a new container with docker run. This will preserve any data that your application has created inside the container.

Nb: It does not preserve data that is stored inside volumes; you need to move data volumes manually to new host.

Android Fragment onClick button Method

Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).

public class FragName extends Fragment implements View.OnClickListener { 
    public FragmentCommunicator fComm;
    public ImageButton res1, res2;
    int c;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_test, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            fComm = (FragmentCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement FragmentCommunicator");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
        res1.setOnClickListener(this);
        res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
        res2.setOnClickListener(this);
    }
    public void onClick(final View v) { //check for what button is pressed
            switch (v.getId()) {
                case R.id.responseButton1:
                  c *= fComm.fragmentContactActivity(2);
                  break;
                case R.id.responseButton2:
                  c *= fComm.fragmentContactActivity(4);
                  break;
                default:
                  c *= fComm.fragmentContactActivity(100);
                  break;
    }
    public interface FragmentCommunicator{
        public int fragmentContactActivity(int b);
    }



public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
    int a = 10;
    //variable a is update by fragment. ex. use to change textview or whatever else you'd like.

    public int fragmentContactActivity(int b) {
        //update info on activity here
        a += b;
        return a;
    }
}

http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html

How to compile and run C/C++ in a Unix console/Mac terminal?

Ryan, I am changing this to be an answer instead of a comment, since it appears I was too brief. Do all of this in "Terminal".

To use the G++ compiler, you need to do this:

  1. Navigate to the directory in which you stored the *.cpp file.

    cd ~/programs/myprograms/
    (the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)

  2. Compile it

    g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. bin is just common on unix.)

    There should be NOTHING returned if it was successful, and that is okay. Generally you get returns on failures.

    However, if you type ls, you will see the list of files in the same directory. For example you would see the other folders, input.cpp and output.bin

  3. From inside the directory, now execute it with ./outbut.bin

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I'll have a go at this complicated subject.

What is origin?

The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com or could be a locally opened file file:// etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com, the origin of the web page that is displayed to you is https://www.google.com. You can see this in Chrome Dev Tools under Security:

enter image description here

The same applies for if you open a local HTML file via your file explorer (which is not served via a server):

enter image description here

What has this got to do with CORS issues?

When you open your browser and go to https://website.com, that website will have the origin of https://website.com. This website will most likely only fetch images, icons, js files and do API calls towards https://website.com, basically it is calling the same server as it was served from. It is doing calls to the same origin.

If you open your web browser and open a local HTML file and in that html file there is javascript which wants to do a request to google for example, you get the following error:

enter image description here

The same-origin policy tells the browser to block cross-origin requests. In this instance origin null is trying to do a request to https://www.google.com (a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.

Same applies for if my page was served from a server on localhost:

enter image description here

Localhost server example

If we host our own localhost API server running on localhost:3000 with the following code:

const express = require('express')
const app = express()
 
app.use(express.static('public'))

app.get('/hello', function (req, res) {
    // res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})
 
app.listen(3000, () => {
    console.log('alive');
})

And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:

enter image description here

Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.

But if we uncomment the commented line:

const express = require('express')
const app = express()
 
app.use(express.static('public'))

app.get('/hello', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})
 
app.listen(3000, () => {
    console.log('alive');
})

And now try again:

enter image description here

It works, because the server which sends the HTTP response included now a header stating that it is ok for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.

How to fix things

  1. Serve the page from the same origin as where the requests you are making reside (same host).
  2. Allow the server to receive cross-origin requests by explicitly stating it in the response headers.
  3. Don't use a browser. Use cURL for example, it doesn't care about CORS Policies like browsers do and will get you what you want.

Example flow

Following is taken from: https://web.dev/cross-origin-resource-sharing/#how-does-cors-work

Remember, the same-origin policy tells the browser to block cross-origin requests. When you want to get a public resource from a different origin, the resource-providing server needs to tell the browser "This origin where the request is coming from can access my resource". The browser remembers that and allows cross-origin resource sharing.

  • Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the current origin (scheme, host, and port).

  • Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an Access-Control-Allow-Origin header to the response specifying the requesting origin (or * to allow any origin.)

  • Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the browser allows the response data to be shared with the client site.

More links

Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669

How can I stop float left?

Just add overflow:hidden in the first div style. That should be enough.

How to solve java.lang.NoClassDefFoundError?

I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me ( at least for me). After hours of research I found following solution and may help to android developers who are doing development using android studio. modify the setting as below Preferences ->Build, Execution, Deployment -> Instant Run -> un-check the first option.

With this change I am up and running. Hope this will help my dev friends.

Split data frame string column into multiple columns

Use stringr::str_split_fixed

library(stringr)
str_split_fixed(before$type, "_and_", 2)

What is WEB-INF used for in a Java EE web application?

This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.

Xcode swift am/pm time to 24 hour format

Here is code for other way around

For Swift 3

 func amAppend(str:String) -> String{
    var temp = str
    var strArr = str.characters.split{$0 == ":"}.map(String.init)
    var hour = Int(strArr[0])!
    var min = Int(strArr[1])!
    if(hour > 12){
        temp = temp + "PM"
    }
    else{
        temp = temp + "AM"
    }
    return temp
}

Unable to establish SSL connection, how do I fix my SSL cert?

The problem I faced was in client server environment. The client was trying to connect over http port 80 but wanted the server proxy to redirect the request to some other port and data was https. So basically asking secure information over http. So server should have http port 80 as well as the port client is requesting, let's say urla:1111\subB.

The issue was server was hosting this on some other port e,g urla:2222\subB; so the client was trying to access over 1111 was receiving the error. Correcting the port number should fix this issue. In this case to port number 1111.

How to drop all user tables?

BEGIN
   FOR cur_rec IN (SELECT object_name, object_type
                   FROM user_objects
                   WHERE object_type IN
                             ('TABLE',
                              'VIEW',
                              'MATERIALIZED VIEW',
                              'PACKAGE',
                              'PROCEDURE',
                              'FUNCTION',
                              'SEQUENCE',
                              'SYNONYM',
                              'PACKAGE BODY'
                             ))
   LOOP
      BEGIN
         IF cur_rec.object_type = 'TABLE'
         THEN
            EXECUTE IMMEDIATE 'DROP '
                              || cur_rec.object_type
                              || ' "'
                              || cur_rec.object_name
                              || '" CASCADE CONSTRAINTS';
         ELSE
            EXECUTE IMMEDIATE 'DROP '
                              || cur_rec.object_type
                              || ' "'
                              || cur_rec.object_name
                              || '"';
         END IF;
      EXCEPTION
         WHEN OTHERS
         THEN
            DBMS_OUTPUT.put_line ('FAILED: DROP '
                                  || cur_rec.object_type
                                  || ' "'
                                  || cur_rec.object_name
                                  || '"'
                                 );
      END;
   END LOOP;
   FOR cur_rec IN (SELECT * 
                   FROM all_synonyms 
                   WHERE table_owner IN (SELECT USER FROM dual))
   LOOP
      BEGIN
         EXECUTE IMMEDIATE 'DROP PUBLIC SYNONYM ' || cur_rec.synonym_name;
      END;
   END LOOP;
END;
/

center image in div with overflow hidden

working solution with flex-box for posterity:

main points:

  1. overflow hidden for wrapper
  2. image height and width must be specified, cannot be percentage.
  3. use any method you want to center the image.
  wrapper {
    width: 80;
    height: 80;
    overflow: hidden;
    align-items: center;
    justify-content: center;
  }
  image {
    width: min-content;
    height: min-content;
  }

SQL MERGE statement to update data

If you need just update your records in energydata based on data in temp_energydata, assuming that temp_enerydata doesn't contain any new records, then try this:

UPDATE e SET e.kWh = t.kWh
  FROM energydata e INNER JOIN 
       temp_energydata t ON e.webmeterID = t.webmeterID AND 
                            e.DateTime = t.DateTime

Here is working sqlfiddle

But if temp_energydata contains new records and you need to insert it to energydata preferably with one statement then you should definitely go with the answer that Bacon Bits gave.

Scroll to bottom of Div on page load (jQuery)

for animate in jquery (version > 2.0)

var d = $('#div1');
d.animate({ scrollTop: d.prop('scrollHeight') }, 1000);

Select last row in MySQL

You can use an OFFSET in a LIMIT command:

SELECT * FROM aTable LIMIT 1 OFFSET 99

in case your table has 100 rows this return the last row without relying on a primary_key

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Go in xampp/apache/conf/httpd.conf and open it. Then just chang 2 lines

Listen 80
to
Listen 81

And

ServerName localhost:80
to
ServerName localhost:81

Then start using admin privileges.

As I am working in a corporate environment where developers faces firewall issues, none of the other answers resolved my issue.

As the port is not used by Skype, but by some other internal applications, I followed the below steps to resolve the issue:

Step 1 - From the XAMPP Control Panel, under Apache, click the Config button, and select the Apache (httpd.conf).

Inside the httpd.conf file, somehow I found a line that says:

Listen 80 And change the 80 into any number / port you want. In my scenario I’m using port 8080.

Listen 8080 Still from the httpd.conf file,

You should also do this in the same process Still from the httpd-ssl.conf file, find another line that says

ServerName localhost:443 And change 443 to 4433.

ServerName localhost:4433 Remember to save the httpd.conf and httpd-ssl.conf files after performing some changes. Then restart the Apache service.

MessageBox with YesNoCancel - No & Cancel triggers same event

The way I use a yes/no prompt is:

If MsgBox("Are you sure?", MsgBoxStyle.YesNo) <> MsgBoxResults.Yes Then
    Exit Sub
End If

Copy directory to another directory using ADD command

Indeed ADD go /usr/local/ will add content of go folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR to /usr/local/ then add your directory to it like:

WORKDIR /usr/local/
COPY go go/

or

WORKDIR /usr/local/go
COPY go ./

But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . . and exclude all unwanted directories and files in .dockerignore, let's say I got folders and files:

- src 
- tmp 
- dist 
- assets 
- go 
- justforfun 
- node_modules 
- scripts 
- .dockerignore 
- Dockerfile 
- headache.lock 
- package.json 

and I want to add src assets package.json justforfun go so:

in Dockerfile:

FROM galaxy:latest

WORKDIR /usr/local/
COPY . .

in .dockerignore file:

node_modules
headache.lock
tmp
dist

Or for more fun (or you like to confuse more people make them suffer as well :P) can be:

*
!src 
!assets 
!go 
!justforfun 
!scripts 
!package.json 

In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".

It is a late answer but adding more ways to do the same covering even more cases.

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

Difference between jar and war in Java

.jar and .war are both zipped archived files. Both can have the optional META-INF/MANIFEST.MF manifest file which hold informative information like versioning, and instructional attributes like classpath and main-class for the JVM that will execute it.

.war file - Web Application Archive intended to be execute inside a 'Servlet Container' and may include other jar files (at WEB-INF/lib directory) compiled classes (at WEB-INF/classes (servlet goes there too)) .jsp files images, files etc. All WAR content that is there in order to create a self-contained module.

How to embed a Facebook page's feed into my website

In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.

  1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

_x000D_
_x000D_
<div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
  var js, fjs = d.getElementsByTagName(s)[0];_x000D_
  if (d.getElementById(id)) return;_x000D_
  js = d.createElement(s); js.id = id;_x000D_
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
  fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
_x000D_
_x000D_

  1. Place the code for your plugin wherever you want the plugin to appear on your page.

_x000D_
_x000D_
<div class="fb-page" _x000D_
     data-href="https://www.facebook.com/YourPageName" _x000D_
     data-tabs="timeline" _x000D_
     data-small-header="false" _x000D_
     data-adapt-container-width="true" _x000D_
     data-hide-cover="false" _x000D_
     data-show-facepile="true">_x000D_
  <div class="fb-xfbml-parse-ignore">_x000D_
    <blockquote cite="https://www.facebook.com/facebook">_x000D_
      <a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also change the following settings:

enter image description here

Also You can now have timeline, events and messages tabs with the new page plugin:

  • Timeline Tab: Will show the most recent posts of your Facebook Page timeline.
  • Events Tab: People can follow your page events and subscribe to events from the plugin.
  • Messages Tab: People can message your page directly from your website. People need to be logged in to use this feature.

_x000D_
_x000D_
<div class="fb-page" _x000D_
  data-tabs="timeline,events,messages"_x000D_
  data-href="https://www.facebook.com/YourPageName"_x000D_
  data-width="380" _x000D_
  data-hide-cover="false">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Break a previous commit into multiple commits

git rebase --interactive can be used to split a commit into smaller commits. The Git docs on rebase have a concise walkthrough of the process - Splitting Commits:

In interactive mode, you can mark commits with the action "edit". However, this does not necessarily mean that git rebase expects the result of this edit to be exactly one commit. Indeed, you can undo the commit, or you can add other commits. This can be used to split a commit into two:

  • Start an interactive rebase with git rebase -i <commit>^, where <commit> is the commit you want to split. In fact, any commit range will do, as long as it contains that commit.

  • Mark the commit you want to split with the action "edit".

  • When it comes to editing that commit, execute git reset HEAD^. The effect is that the HEAD is rewound by one, and the index follows suit. However, the working tree stays the same.

  • Now add the changes to the index that you want to have in the first commit. You can use git add (possibly interactively) or git gui (or both) to do that.

  • Commit the now-current index with whatever commit message is appropriate now.

  • Repeat the last two steps until your working tree is clean.

  • Continue the rebase with git rebase --continue.

If you are not absolutely sure that the intermediate revisions are consistent (they compile, pass the testsuite, etc.) you should use git stash to stash away the not-yet-committed changes after each commit, test, and amend the commit if fixes are necessary.

How to Get a Specific Column Value from a DataTable?

Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:

Dim oRows() As DataRow

oRows = dtCountries.Select("CountryName = '" & userinput & "'")

If oRows.Count = 0 Then
   ' No rows found
Else
   ' At least one row found. Could be more than one
End If

Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).

Closing pyplot windows

Please use

plt.show(block=False)
plt.close('all')

Android: Share plain text using intent (to all messaging apps)

Images or binary data:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

or HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Hide scroll bar, but while still being able to scroll

To hide scroll bars for elements with overflowing content use.

.div{

  scrollbar-width: none; /* The most elegant way for Firefox */

}    

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

How to pass data to all views in Laravel 5?

I found this to be the easiest one. Create a new provider and user the '*' wildcard to attach it to all views. Works in 5.3 as well :-)

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $user = request()->user();

            $view->with('user', $user);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

How to compare datetime with only date in SQL Server

You can use LIKE statement instead of =. But to do this with DateStamp you need to CONVERT it first to VARCHAR:

SELECT * 
FROM [User] U
WHERE CONVERT(VARCHAR, U.DateCreated, 120) LIKE '2014-02-07%'

How do I sort a list of dictionaries by a value of the dictionary?

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

Get TimeZone offset value from TimeZone without TimeZone name

@MrBean - I was in a similar situation where I had to call a 3rd-party web service and pass in the Android device's current timezone offset in the format +/-hh:mm. Here is my solution:

public static String getCurrentTimezoneOffset() {

    TimeZone tz = TimeZone.getDefault();  
    Calendar cal = GregorianCalendar.getInstance(tz);
    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

    return offset;
} 

Evenly space multiple views within a container view

I wanted to horizontally align 5 images, so I ended up following Mete's response with a small difference.

The first image will be centered horizontally in container equal to 0 and a multiplier of 1:5:

first image

The second image will be centered horizontally in container equal to 0 and a multiplier of 3:5: second image

And like that for the rest of the images. For example, the fifth (and last) image will be centered horizontally in container equal to 0 and a multiplier of 9:5: last image

As Mete explained, the order goes 1, 3, 5, 7, 9, etc. The positions follow the same logic: the first position is 1, then space, then the next position 3, and so on.

How to get the full path of running process?

What you can do is use WMI to get the paths. This will allow you to get the path regardless it's a 32-bit or 64-bit application. Here's an example demonstrating how you can get it:

// include the namespace
using System.Management;

var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
    var query = from p in Process.GetProcesses()
                join mo in results.Cast<ManagementObject>()
                on p.Id equals (int)(uint)mo["ProcessId"]
                select new
                {
                    Process = p,
                    Path = (string)mo["ExecutablePath"],
                    CommandLine = (string)mo["CommandLine"],
                };
    foreach (var item in query)
    {
        // Do what you want with the Process, Path, and CommandLine
    }
}

Note that you'll have to reference the System.Management.dll assembly and use the System.Management namespace.

For more info on what other information you can grab out of these processes such as the command line used to start the program (CommandLine), see the Win32_Process class and WMI .NET for for more information.

Use jQuery to hide a DIV when the user clicks outside of it

_x000D_
_x000D_
var exclude_div = $("#ExcludedDiv");;  _x000D_
$(document).click(function(e){_x000D_
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden_x000D_
        $(".myDiv1").addClass("hidden");  _x000D_
_x000D_
}); 
_x000D_
_x000D_
_x000D_

FIDDLE

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

How to clamp an integer to some range?

sorted((minval, value, maxval))[1]

for example:

>>> minval=3
>>> maxval=7
>>> for value in range(10):
...   print sorted((minval, value, maxval))[1]
... 
3
3
3
3
4
5
6
7
7
7

How to manually update datatables table with new JSON data

You can use:

$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);

Jsfiddle

Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

SQL Server date format yyyymmdd

Assuming your "date" column is not actually a date.

Select convert(varchar(8),cast('12/24/2016' as date),112)

or

Select format(cast('12/24/2016' as date),'yyyyMMdd')

Returns

20161224

How to hide command output in Bash

>/dev/null 2>&1 will mute both stdout and stderr

yum install nano >/dev/null 2>&1

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

Log4net does not write the log in the log file

In my case I had to give the IIS_IUSRS Read\write permission to the log file.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

To execute more Maven builds from one script you shall use the Windows call function in the following way:

call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true

How to convert a normal Git repository to a bare one?

i've read the answers and i have done this:

cd repos
mv .git repos.git
cd repos.git
git config --bool core.bare true # from another answer
cd ../
mv repos.git ../
cd ../
rm -rf repos/ # or delete using a file manager if you like

this will leave the contents of repos/.git as the bare repos.git

Batch file script to zip files

This is link by Tomas has a well written script to zip contents of a folder.

To make it work just copy the script into a batch file and execute it by specifying the folder to be zipped(source).

No need to mention destination directory as it is defaulted in the script to Desktop ("%USERPROFILE%\Desktop")

Copying the script here, just incase the web-link is down:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET sourceDirPath=%1
IF [%2] EQU [] (
  SET destinationDirPath="%USERPROFILE%\Desktop"
) ELSE (
  SET destinationDirPath="%2"
)
IF [%3] EQU [] (
  SET destinationFileName="%~n1%.zip"
) ELSE (
  SET destinationFileName="%3"
)
SET tempFilePath=%TEMP%\FilesToZip.txt
TYPE NUL > %tempFilePath%

FOR /F "DELIMS=*" %%i IN ('DIR /B /S /A-D "%sourceDirPath%"') DO (
  SET filePath=%%i
  SET dirPath=%%~dpi
  SET dirPath=!dirPath:~0,-1!
  SET dirPath=!dirPath:%sourceDirPath%=!
  SET dirPath=!dirPath:%sourceDirPath%=!
  ECHO .SET DestinationDir=!dirPath! >> %tempFilePath%
  ECHO "!filePath!" >> %tempFilePath%
)

MAKECAB /D MaxDiskSize=0 /D CompressionType=MSZIP /D Cabinet=ON /D Compress=ON /D UniqueFiles=OFF /D DiskDirectoryTemplate=%destinationDirPath% /D CabinetNameTemplate=%destinationFileName%  /F %tempFilePath% > NUL 2>&1

DEL setup.inf > NUL 2>&1
DEL setup.rpt > NUL 2>&1
DEL %tempFilePath% > NUL 2>&1

Load CSV file with Spark

When using spark.read.csv, I find that using the options escape='"' and multiLine=True provide the most consistent solution to the CSV standard, and in my experience works the best with CSV files exported from Google Sheets.

That is,

#set inferSchema=False to read everything as string
df = spark.read.csv("myData.csv", escape='"', multiLine=True,
     inferSchema=False, header=True)

What is Parse/parsing?

Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.

Example of parsing using indexOf to calculate the position of a string in another string:

String s="What a Beautiful day!";

int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8

paresInt essentially converts a String to a Integer.

String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);

Output:

Constructor method: 9876543

parseInt() method: 9876543

How to determine the version of the C++ standard used by the compiler?

Use __cplusplus as suggested. Only one note for Microsoft compiler, use Zc:__cplusplus compiler switch to enable __cplusplus

Source https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Why is textarea filled with mysterious white spaces?

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

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

The box model is something every web-developer should know about. working with percents for sizes and pixels for padding/margin just doesn't work. There always is a resolution at which it doesn't look good (e.g. giving a width of 90% and a padding/margin of 10px in a div with a width of under 100px).

Check this out (using micro.pravi's code): http://jsbin.com/umeduh/2

<div id="container">
    <div class="left">
        <div class="content">
            left
        </div>
    </div>
    <div class="right">
        <div class="content">
            right
            <textarea>Check me out!</textarea>
        </div>
    </div>
</div>

The <div class="content"> are there so you can use padding and margin without screwing up the floats.

this is the most important part of the CSS:

textarea {
    display: block;
    width: 100%;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Can I set an opacity only to the background image of a div?

<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=" background-color: #00000088"> Hi there </div>
<!-- #00 would be r, 00 would be g, 00 would be b, 88 would be a. -->
</body>
</html>

including 4 sets of numbers would make it rgba, not cmyk, but either way would work (rgba= 00000088, cmyk= 0%, 0%, 0%, 50%)

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Please use the following command,

cat /etc/bash.bashrc > ~/.bashrc

This will generate a new bashrc file with the default values. Please use vi ~/.bashrc to edit this file.

mysql: see all open connections to a given database?

You can invoke MySQL show status command

show status like 'Conn%';

For more info read Show open database connections

See line breaks and carriage returns in editor

I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :

cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF

When you're executing vim, the commands into .vimrc are executed, and you can see this example :

My line with CRLF eol here ^M¶

trim left characters in sql server?

For 'Hello' at the start of the string:

SELECT STUFF('Hello World', 1, 6, '')

This will work for 'Hello' anywhere in the string:

SELECT REPLACE('Hello World', 'Hello ', '')

ORDER BY date and time BEFORE GROUP BY name in mysql

This worked for me:

SELECT *
FROM your_table
WHERE id IN (
    SELECT MAX(id)
    FROM your_table
    GROUP BY name
);

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

xampp port 80 is busy when some other application is using the same port at that time. This can be solved by using one of the following methods:

  1. Detect the application which is using the port 80 and close it.
  2. This one is more efficient. xampp installs apache server with default port 80. So, you can change this port manually to any number.

Just find the httpd.conf file in xampp installation and replace the following line of code.

#Listen 12.34.56.78:1234
Listen 80

to any port number of your choice. Here, i have taken 8000.

#Listen 12.34.56.78:1234
Listen 8000

Find the following code in the same file httpd.conf

ServerName localhost

Replace with the following, take the same number you have used in upper code.

ServerName localhost:8000

For detailed answer, check http://webolute.com/blog/programming/this-may-be-due-to-a-blocked-port-missing-dependencies

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Maybe too many years late, but nevertheless a theory to try.

The ratio of bounding rectangle of red logo region to the overall dimension of the bottle/can is different. In the case of Can, should be 1:1, whereas will be different in that of bottle (with or without cap). This should make it easy to distinguish between the two.

Update: The horizontal curvature of the logo region will be different between the Can and Bottle due their respective size difference. This could be specifically useful if your robot needs to pick up can/bottle, and you decide the grip accordingly.

Open a file with Notepad in C#

You can use Process.Start, calling notepad.exe with the file as a parameter.

 Process.Start(@"notepad.exe", pathToFile);

How do I enable EF migrations for multiple contexts to separate databases?

In addition to what @ckal suggested, it is critical to give each renamed Configuration.cs its own namespace. If you do not, EF will attempt to apply migrations to the wrong context.

Here are the specific steps that work well for me.

If Migrations are messed up and you want to create a new "baseline":

  1. Delete any existing .cs files in the Migrations folder
  2. In SSMS, delete the __MigrationHistory system table.

Creating the initial migration:

  1. In Package Manager Console:

    Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
    NamespaceOfContext.ContextA -ProjectName ProjectContextIsInIfNotMainOne
    -StartupProjectName NameOfMainProject  -ConnectionStringName ContextA
    
  2. In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationA.cs. This should automatically rename the constructor if using Visual Studio. Make sure it does. Edit ConfigurationA.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsA

  3. Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
    NamespaceOfContext.ContextB -ProjectName ProjectContextIsInIfNotMainOne
    -StartupProjectName NameOfMainProject  -ConnectionStringName ContextB
    
  4. In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationB.cs. Again, make sure the constructor is also renamed appropriately. Edit ConfigurationB.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsB

  5. add-migration InitialBSchema -IgnoreChanges -ConfigurationTypeName
    ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne
    -StartupProjectName NameOfMainProject  -ConnectionStringName ContextB 
    
  6. Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextB
    
  7. add-migration InitialSurveySchema -IgnoreChanges -ConfigurationTypeName
    ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName
    NameOfMainProject  -ConnectionStringName ContextA 
    
  8. Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextA
    

Steps to create migration scripts in Package Manager Console:

  1. Run command

    Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationA -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextA
    

    or -

    Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationB -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextB
    

    It is OK to re-run this command until changes are applied to the DB.

  2. Either run the scripts against the desired local database, or run Update-Database without -Script to apply locally:

    Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextA
    

    or -

    Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
    ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
    -ConnectionStringName ContextB
    

How to check if the given string is palindrome?

Efficient C++ version:

template< typename Iterator >
bool is_palindrome( Iterator first, Iterator last, std::locale const& loc = std::locale("") )
{
    if ( first == last )
        return true;

    for( --last; first < last; ++first, --last )
    {
        while( ! std::isalnum( *first, loc ) && first < last )
            ++first;
        while( ! std::isalnum( *last, loc ) && first < last )
            --last;
        if ( std::tolower( *first, loc ) != std::tolower( *last, loc ) )
            return false;
    }
    return true;
}

How to download a file from my server using SSH (using PuTTY on Windows)

if you install git with git bash, you get SCP available on windows.

Git fatal: protocol 'https' is not supported

Just add this git config --global http.sslVerify false , so that it doesn't check the certificate and it should work just fine

Get local IP address in Node.js

Here's what might be the cleanest, simplest answer without dependencies & that works across all platforms.

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}

Rails 3.1 and Image Assets

when referencing images in CSS or in an IMG tag, use image-name.jpg

while the image is really located under ./assets/images/image-name.jpg

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

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

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

File to byte[] in Java

Basically you have to read it in memory. Open the file, allocate the array, and read the contents from the file into the array.

The simplest way is something similar to this:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1) {
            ous.write(buffer, 0, read);
        }
    }finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
        }

        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return ous.toByteArray();
}

This has some unnecessary copying of the file content (actually the data is copied three times: from file to buffer, from buffer to ByteArrayOutputStream, from ByteArrayOutputStream to the actual resulting array).

You also need to make sure you read in memory only files up to a certain size (this is usually application dependent) :-).

You also need to treat the IOException outside the function.

Another way is this:

public byte[] read(File file) throws IOException, FileTooBigException {
    if (file.length() > MAX_FILE_SIZE) {
        throw new FileTooBigException(file);
    }

    byte[] buffer = new byte[(int) file.length()];
    InputStream ios = null;
    try {
        ios = new FileInputStream(file);
        if (ios.read(buffer) == -1) {
            throw new IOException(
                    "EOF reached while trying to read the whole file");
        }
    } finally {
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
        }
    }
    return buffer;
}

This has no unnecessary copying.

FileTooBigException is a custom application exception. The MAX_FILE_SIZE constant is an application parameters.

For big files you should probably think a stream processing algorithm or use memory mapping (see java.nio).

Maximum call stack size exceeded on npm install

I'm not a Windows user, so if you are, try to check Rene Knop comment.

For Unix/OSX users, I've removed the root .npmrc file ~/.npmrc.
Before you're going to try it, please, check if there is nothing necessary over there you can use this command to bring all content into your terminal: cat ~/.npmrc .

If you have got something like:

cat: /Users/$USER/.npmrc: No such file or directory

to save a copy:

cp ~/.npmrc ~/.npmrc_copy

Now, try to remove it (Works for bash users: Unix / Ubuntu / OSX ...):

rm -f ~/.npmrc

This worked for me.
Hope this will be helpful for others.

Assigning default values to shell variables with a single command in bash

Then there's the way of expressing your 'if' construct more tersely:

FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}

Cannot find mysql.sock

Unfortunately none of the above have worked in my case. But finally I found solutions.

To find where is mysql.sock file, simply open xampp manager, select MySQL and click on Configure on the right. On the config panel click Open Conf File, and simply search for mysql.sock by pressing the CMD+F shortcut.

In my case, the owner of the mysql.sock was changed, and I had to change it back to root admin with: chmod root:admin mysql.sock

After that the database had been accessed.

Which command do I use to generate the build of a Vue app?

if you used vue-cli and webpack when you created your project.

you can use just

npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.

Powershell 2 copy-item which creates a folder if doesn't exist

I have stumbled here twice, and this last time was a unique situation and even though I ditch using copy-item I wanted to post the solution I used.

Had a list of nothing but files with the full path and in majority of the case the files have no extensions. the -Recurse -Force option would not work for me so I ditched copy-item function and fell back to something like below using xcopy as I still wanted to keep it a one liner. Initially I tied with Robocopy but it is apparently looking for a file extension and since many of mine had no extension it considered it a directory.

$filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")

$filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }

Hope it helps someone.

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

Sometimes you just don't have a choice about having to store numbers mixed with text. In one of our applications, the web site host we use for our e-commerce site makes filters dynamically out of lists. There is no option to sort by any field but the displayed text. When we wanted filters built off a list that said things like 2" to 8" 9" to 12" 13" to 15" etc, we needed it to sort 2-9-13, not 13-2-9 as it will when reading the numeric values. So I used the SQL Server Replicate function along with the length of the longest number to pad any shorter numbers with a leading space. Now 20 is sorted after 3, and so on.

I was working with a view that gave me the minimum and maximum lengths, widths, etc for the item type and class, and here is an example of how I did the text. (LBnLow and LBnHigh are the Low and High end of the 5 length brackets.)

REPLICATE(' ', LEN(LB5Low) - LEN(LB1High)) + CONVERT(NVARCHAR(4), LB1High) + '" and Under' AS L1Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB2Low)) + CONVERT(NVARCHAR(4), LB2Low) + '" to ' + CONVERT(NVARCHAR(4), LB2High) + '"' AS L2Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB3Low)) + CONVERT(NVARCHAR(4), LB3Low) + '" to ' + CONVERT(NVARCHAR(4), LB3High) + '"' AS L3Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB4Low)) + CONVERT(NVARCHAR(4), LB4Low) + '" to ' + CONVERT(NVARCHAR(4), LB4High) + '"' AS L4Text,
CONVERT(NVARCHAR(4), LB5Low) + '" and Over' AS L5Text

How can I turn a DataTable to a CSV?

The following shorter version opens fine in Excel, maybe your issue was the trailing comma

.net = 3.5

StringBuilder sb = new StringBuilder(); 

string[] columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());

.net >= 4.0

And as Tim pointed out, if you are on .net>=4, you can make it even shorter:

StringBuilder sb = new StringBuilder(); 

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("test.csv", sb.ToString());

As suggested by Christian, if you want to handle special characters escaping in fields, replace the loop block by:

foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => 
      string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
    sb.AppendLine(string.Join(",", fields));
}

And last suggestion, you could write the csv content line by line instead of as a whole document, to avoid having a big document in memory.

Difference between map, applymap and apply methods in Pandas

Probably simplest explanation the difference between apply and applymap:

apply takes the whole column as a parameter and then assign the result to this column

applymap takes the separate cell value as a parameter and assign the result back to this cell.

NB If apply returns the single value you will have this value instead of the column after assigning and eventually will have just a row instead of matrix.

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

Changing route doesn't scroll to top in the new page

Setting autoScroll to true did not the trick for me, so I did choose another solution. I built a service that hooks in every time the route changes and that uses the built-in $anchorScroll service to scroll to top. Works for me :-).

Service:

 (function() {
    "use strict";

    angular
        .module("mymodule")
        .factory("pageSwitch", pageSwitch);

    pageSwitch.$inject = ["$rootScope", "$anchorScroll"];

    function pageSwitch($rootScope, $anchorScroll) {
        var registerListener = _.once(function() {
            $rootScope.$on("$locationChangeSuccess", scrollToTop);
        });

        return {
            registerListener: registerListener
        };

        function scrollToTop() {
            $anchorScroll();
        }
    }
}());

Registration:

angular.module("mymodule").run(["pageSwitch", function (pageSwitch) {
    pageSwitch.registerListener();
}]);

Best way to check for "empty or null value"

Checking for the length of the string also works and is compact:

where length(stringexpression) > 0;

The executable was signed with invalid entitlements

I have just had an exciting three hours battling with this. I have just upgraded a project to 4.2 and for some reason it just wouldn't work.

I eventually removed the Entitlements.plist file and then created a new one.

File > New File > Code Signing > Entitlement

Name the file Entitlements.plist

Make sure it's in the Resources group in xCode.

It didn't put in the get-task-allow BOOL type in the Entitlements.plist file. I added it, checked it, saved it, unchecked it, saved it. This made me feel better.

I then removed the Adhoc and Release profiles I had created. Re-downloaded them from the Provisioning Portal and droped them back into the xCode organizer.

I then went into Build Settings and made sure the correct profiles were assigned to the Debug and Release profiles.

I then changed the to Release / Device. Hit the build button and it worked.

I have no idea why.

AngularJS - Attribute directive input value change

Since this must have an input element as a parent, you could just use

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelController and add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

Bootstrap 3 Carousel Not Working

Here is the changes you need to be done

just replace the carousel div with the below code

You have missed the '#' for data-target and add active class for the first item

<div id="carousel" class="carousel slide" data-ride="carousel">
            <ol class="carousel-indicators">
                <li data-target="#carousel" data-slide-to="0"></li>
                <li data-target="#carousel" data-slide-to="1"></li>
                <li data-target="#carousel" data-slide-to="2"></li>
            </ol>
            <div class="carousel-inner">
                <div class="item active">
                    <img src="img/slide_1.png" alt="Slide 1">
                </div>
                <div class="item">
                    <img src="img/slide_2.png" alt="Slide 2">
                </div>
                <div class="item">
                    <img src="img/slide_3.png" alt="Slide 3">
                </div>
            </div>
            <a href="#carousel" class="left carousel-control" data-slide="prev">
                <span class="glyphicon glyphicon-chevron-left"></span>
            </a>
            <a href="#carousel" class="right carousel-control" data-slide="next">
                <span class="glyphicon glyphicon-chevron-right"></span>
            </a>
        </div>

How do you strip a character out of a column in SQL Server?

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')

In your instance it would be

UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')

Because there is no replacement (you want to get rid of it).

This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.

Changing website favicon dynamically

If you have the following HTML snippet:

<link id="favicon" rel="shortcut icon" type="image/png" href="favicon.png" />

You can change the favicon using Javascript by changing the HREF element on this link, for instance (assuming you're using JQuery):

$("#favicon").attr("href","favicon2.png");

You can also create a Canvas element and set the HREF as a ToDataURL() of the canvas, much like the Favicon Defender does.

React: Expected an assignment or function call and instead saw an expression

You use a function component:

const def = (props) => {
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>

};

In the function component, you have to write a return or just add parentheses. After the added return or parentheses your code should look like this:

const def = (props) => ({
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>
});

Get all unique values in a JavaScript array (remove duplicates)

For a array of strings:

function removeDuplicatesFromArray(arr) {
  const unique = {};
  arr.forEach((word) => {
    unique[word] = 1; // it doesn't really matter what goes here
  });
  return Object.keys(unique);
}

How to append to a file in Node?

You need to open it, then write to it.

var fs = require('fs'), str = 'string to append to file';
fs.open('filepath', 'a', 666, function( e, id ) {
  fs.write( id, 'string to append to file', null, 'utf8', function(){
    fs.close(id, function(){
      console.log('file closed');
    });
  });
});

Here's a few links that will help explain the parameters

open
write
close


EDIT: This answer is no longer valid, look into the new fs.appendFile method for appending.

Implementing IDisposable correctly

IDisposable exists to provide a means for you to clean up unmanaged resources that won't be cleaned up automatically by the Garbage Collector.

All of the resources that you are "cleaning up" are managed resources, and as such your Dispose method is accomplishing nothing. Your class shouldn't implement IDisposable at all. The Garbage Collector will take care of all of those fields just fine on its own.

Getting results between two dates in PostgreSQL

Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?

Saving image from PHP URL

$content = file_get_contents('http://example.com/image.php');
file_put_contents('/my/folder/flower.jpg', $content);

How to programmatically set the ForeColor of a label to its default?

DefaultForeColor is enough for this statement. This property gets the default foreground color of the control.

lblExample.ForeColor = DefaultForeColor;

How do I add more members to my ENUM-type column in MySQL?

FYI: A useful simulation tool - phpMyAdmin with Wampserver 3.0.6 - Preview SQL: I use 'Preview SQL' to see the SQL code that would be generated before you save the column with the change to ENUM. Preview SQL

Above you see that I have entered 'Ford','Toyota' into the ENUM but I am getting syntax ENUM(0) which is generating syntax error Query error 1064#

I then copy and paste and alter the SQL and run it through SQL with a positive result.

SQL changed

This is a quickfix that I use often and can also be used on existing ENUM values that need to be altered. Thought this might be useful.

How to add/subtract dates with JavaScript?

The JavaScript Date object can help here.

The first step is to convert those strings to Date instances. That's easily done:

var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10),        // Year
                  parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
                  parseInt(str.substring(3, 5), 10));    // Day

Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly 86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.

More on the MDN page on Date.

You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...

referenced before assignment error in python

I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!

-Sam

SQL Server query - Selecting COUNT(*) with DISTINCT

This is a good example where you want to get count of Pincode which stored in the last of address field

SELECT DISTINCT
    RIGHT (address, 6),
    count(*) AS count
FROM
    datafile
WHERE
    address IS NOT NULL
GROUP BY
    RIGHT (address, 6)

Show ImageView programmatically

int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);        
imageView.setImageResource(id);        
someLinearLayout.addView(imageView); 

How to tell if UIViewController's view is visible

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

Instead, take this simple approach which seems to work well in most, if not all cases:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

Regular Expression to match string starting with a specific word

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Is there a method that tells my program to quit?

Please note that the solutions based on sys.exit() or any Exception may not work in a multi-threaded environment.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted. (doc)

This answer from Alex Martelli for more details.

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

Use Ant for running program with command line arguments

What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:

In my build.xml:

<target name="printclasspath">
    <pathconvert property="classpathProp" refid="project.class.path"/>
    <echo>${classpathProp}</echo>
</target>

In another script called 'run.sh':

export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \  -f 7):build
java "$@"

It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.

I think it's a shame there's not some option in ant whereby you could do something like:

ant -- arg1 arg2 arg3

mpirun uses this type of syntax; ssh also can use this syntax I think.

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

What is Inversion of Control?

Let to say that we make some meeting in some hotel.

Many people, many carafes of water, many plastic cups.

When somebody want to drink, she fill cup, drink and throw cup on the floor.

After hour or something we have a floor covered of plastic cups and water.

Let invert control.

The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

and she all of time offers to guests drinking.

When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

meeting members will need glass of water but not piece of cake.

Example:-

public class MeetingMember {

    private GlassOfWater glassOfWater;

    ...

    public void setGlassOfWater(GlassOfWater glassOfWater){
        this.glassOfWater = glassOfWater;
    }
    //your glassOfWater object initialized and ready to use...
    //spring IoC  called setGlassOfWater method itself in order to
    //offer to meetingMember glassOfWater instance

}

Useful links:-

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If M2_HOME is configured to point to the Maven home directory then:

  1. Go to File -> Settings
  2. Search for Maven
  3. Select Runner
  4. Insert in the field VM Options the following string:

    Dmaven.multiModuleProjectDirectory=$M2_HOME
    

Click Apply and OK

Where is the web server root directory in WAMP?

Everything suggested by user "mins" is correct, and excellent information.

WAMP 2.5 provides a default Server Configuration display when you enter localhost into your browser. This maps to c:\wamp\www, as described in previous posts. Creating subdirectories under www will cause Projects to appear on this display. A click and you're in your project.

I have various projects under different directory structures, sometimes on shared drives which makes this centralized location of files inconvenient. Luckily, there is a second feature of WAMP 2.5, an Alias, which makes specifying the location of one (or more) disparate web directories quite easy. No editing of configuration files. Using the WAMP menu, choose Apache > Alias directories > Add an Alias.

WAMP has evolved nicely to provide support for a variety of developer preferences.

WAMP server, localhost is not working

You please change the port 80 to port 7080 or something difference. Dont use 8080. It might be busy in most case.

Updated Listen 80 to Listen:7080 and ServerName localhost to ServerName localhost:7080.

It will work fine.

How to format numbers as currency string?

function CurrencyFormatted(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

From WillMaster.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

In my case, I had duplicate IDs in the source table, so none of the proposals worked. I don't care about performance, it's just done once. To solve this I took the records one by one with a cursor to ignore the duplicates.

So here's the code example:

DECLARE @c1 AS VARCHAR(12);
DECLARE @c2 AS VARCHAR(250);
DECLARE @c3 AS VARCHAR(250);


DECLARE MY_cursor CURSOR STATIC FOR
Select
c1,
c2,
c3
from T2
where ....;

OPEN MY_cursor
FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3

WHILE @@FETCH_STATUS = 0
BEGIN
    if (select count(1) 
        from T1
        where a1 = @c1
        and a2 = @c2
        ) = 0 
            INSERT INTO T1
            values (@c1, @c2, @c3)

    FETCH NEXT FROM MY_cursor INTO @c1, @c2, @c3
END
CLOSE MY_cursor
DEALLOCATE MY_cursor

How to set the image from drawable dynamically in android?

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 

Syntax behind sorted(key=lambda: ...)

The variable left of the : is a parameter name. The use of variable on the right is making use of the parameter.

Means almost exactly the same as:

def some_method(variable):
  return variable[0]

AngularJS : Factory and Service?

Service vs Factory


enter image description here enter image description here

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Factory are a great way for communicating between controllers like sharing data.

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Cannot be injected in .config() function.

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Services are used for communication between controllers to share data

  • You can add properties and functions to a service object by using the this keyword

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • Cannot be injected in .config() function.

  • If you're using a class you could use the service provider

  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

Also Take a look at this beautiful stuffs

Confused about service vs factory

AngularJS Factory, Service and Provider

Angular.js: service vs provider vs factory?

Why is "except: pass" a bad programming practice?

The except:pass construct essentially silences any and all exceptional conditions that come up while the code covered in the try: block is being run.

What makes this bad practice is that it usually isn't what you really want. More often, some specific condition is coming up that you want to silence, and except:pass is too much of a blunt instrument. It will get the job done, but it will also mask other error conditions that you likely haven't anticipated, but may very well want to deal with in some other way.

What makes this particularly important in Python is that by the idioms of this language, exceptions are not necessarily errors. They're often used this way, of course, just as in most languages. But Python in particular has occasionally used them to implement an alternative exit path from some code tasks which isn't really part of the normal running case, but is still known to come up from time to time and may even be expected in most cases. SystemExit has already been mentioned as an old example, but the most common example nowadays may be StopIteration. Using exceptions this way caused a lot of controversy, especially when iterators and generators were first introduced to Python, but eventually the idea prevailed.

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

Martin Joiner's problem is caused by a misunderstanding of the <caption> tag.

The <caption> tag defines a table caption.

The <caption> tag must be the first child of the <table> tag.

You can specify only one caption per table.

Also, note that the scope attribute should be placed on a <th> element and not on a <tr> element.

The proper way to write a multi-header multi-tbody table would be something like this :

_x000D_
_x000D_
<table id="dinner_table">_x000D_
    <caption>This is the only correct place to put a caption.</caption>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">1</th>_x000D_
            <td>Fish</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">2</th>_x000D_
            <td>Chips</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">3</th>_x000D_
            <td>Peas</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">4</th>_x000D_
            <td>Gravy</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">5</th>_x000D_
            <td>Pizza</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">6</th>_x000D_
            <td>Salad</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">7</th>_x000D_
            <td>Oil</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">8</th>_x000D_
            <td>Bread</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

Can I safely delete contents of Xcode Derived data folder?

yes, safe to delete, my script searches and nukes every instance it finds, easily modified to a local directory

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'

for drive in Swap Media OSX_10.11.6/$HOME
do
   pushd /Volumes/${drive}  &> /dev/null
   gfind . -depth -name 'DerivedData'|xargs -I '{}' /bin/rm -fR '{}'
   popd &> /dev/null
done

Bash function to find newest file matching pattern

Unusual filenames (such as a file containing the valid \n character can wreak havoc with this kind of parsing. Here's a way to do it in Perl:

perl -le '@sorted = map {$_->[0]} 
                    sort {$a->[1] <=> $b->[1]} 
                    map {[$_, -M $_]} 
                    @ARGV;
          print $sorted[0]
' b2*

That's a Schwartzian transform used there.