Programs & Examples On #Notsupportedexception

Unsupported Media Type in postman

I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.

  • If your request is XML Request use XML(text/xml).

  • If your request is JSON Request use JSON(application/json)

Http Post request with content type application/x-www-form-urlencoded not working in Spring

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})

It would be helpful if you posted your code.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

Simply removing @RequestBody annotation solves the problem (tested on Spring Boot 2):

@RestController
public class MyController {

    @PostMapping
    public void method(@Valid RequestDto dto) {
       // method body ...
    }
}

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

You shouldn't send a request body with an HTTP GET request. You should modify addDepartment() so that it only supports POST, and POST your JSON to that endpoint. If you want to GET information about a department, you should create a separate controller method that does that (and does not require a request body).

Also, double-check your endpoint definitions since you have misspelled "reimbursement" in the $.ajax call.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

"This operation requires IIS integrated pipeline mode."

The way to fix this issue is not within IIS. I was trying to run my application within IIS Express within Visual Studio. I searched the web and some articles were saying to add an identity tag to the system.web tag. This is not the correct way.

The way I was able to solve this issue was to click on the project file and go to properties. Under managed pipeline, I changed the property value from classic to integrated.

This solved my issue.

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Spring Rest POST Json RequestBody Content type not supported

I had this problem when using java 9+ modules. I had to open the module in order for the com.fasterxml.jackson.databind to access the objects with reflection. Alternatively you could only open the package where the models are located if you have one.

Download image from the site in .NET/C#

Also possible to use DownloadData method

    private byte[] GetImage(string iconPath)
    {
        using (WebClient client = new WebClient())
        {
            byte[] pic = client.DownloadData(iconPath);
            //string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +@"\1.png";
            //File.WriteAllBytes(checkPath, pic);
            return pic;
        }
    }

How to properly override clone method?

The way your code works is pretty close to the "canonical" way to write it. I'd throw an AssertionError within the catch, though. It signals that that line should never be reached.

catch (CloneNotSupportedException e) {
    throw new AssertionError(e);
}

Serialize Class containing Dictionary member

I wanted a SerializableDictionary class that used xml attributes for key/value so I've adapted Paul Welter's class.

This produces xml like:

<Dictionary>
  <Item Key="Grass" Value="Green" />
  <Item Key="Snow" Value="White" />
  <Item Key="Sky" Value="Blue" />
</Dictionary>"

Code:

using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace DataTypes {
    [XmlRoot("Dictionary")]
    public class SerializableDictionary<TKey, TValue>
        : Dictionary<TKey, TValue>, IXmlSerializable {
        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema() {
            return null;
        }

        public void ReadXml(XmlReader reader) {
            XDocument doc = null;
            using (XmlReader subtreeReader = reader.ReadSubtree()) {
                doc = XDocument.Load(subtreeReader);
            }
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            foreach (XElement item in doc.Descendants(XName.Get("Item"))) {
                using(XmlReader itemReader =  item.CreateReader()) {
                    var kvp = serializer.Deserialize(itemReader) as SerializableKeyValuePair<TKey, TValue>;
                    this.Add(kvp.Key, kvp.Value);
                }
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer) {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            foreach (TKey key in this.Keys) {
                TValue value = this[key];
                var kvp = new SerializableKeyValuePair<TKey, TValue>(key, value);
                serializer.Serialize(writer, kvp, ns);
            }
        }
        #endregion

        [XmlRoot("Item")]
        public class SerializableKeyValuePair<TKey, TValue> {
            [XmlAttribute("Key")]
            public TKey Key;

            [XmlAttribute("Value")]
            public TValue Value;

            /// <summary>
            /// Default constructor
            /// </summary>
            public SerializableKeyValuePair() { }
        public SerializableKeyValuePair (TKey key, TValue value) {
            Key = key;
            Value = value;
        }
    }
}
}

Unit Tests:

using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DataTypes {
    [TestClass]
    public class SerializableDictionaryTests {
        [TestMethod]
        public void TestStringStringDict() {
            var dict = new SerializableDictionary<string, string>();
            dict.Add("Grass", "Green");
            dict.Add("Snow", "White");
            dict.Add("Sky", "Blue");
            dict.Add("Tomato", "Red");
            dict.Add("Coal", "Black");
            dict.Add("Mud", "Brown");

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(dict.Count, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<string, string>;
                Assert.AreEqual(dict["Grass"], outDict["Grass"]);
                Assert.AreEqual(dict["Snow"], outDict["Snow"]);
                Assert.AreEqual(dict["Sky"], outDict["Sky"]);
            }
        }

        [TestMethod]
        public void TestIntIntDict() {
            var dict = new SerializableDictionary<int, int>();
            dict.Add(4, 7);
            dict.Add(5, 9);
            dict.Add(7, 8);

            var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
            using (var stream = new MemoryStream()) {
                // Load memory stream with this objects xml representation
                XmlWriter xmlWriter = null;
                try {
                    xmlWriter = XmlWriter.Create(stream);
                    serializer.Serialize(xmlWriter, dict);
                } finally {
                    xmlWriter.Close();
                }

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);

                XDocument doc = XDocument.Load(stream);
                Assert.AreEqual("Dictionary", doc.Root.Name);
                Assert.AreEqual(3, doc.Root.Descendants().Count());

                // Rewind
                stream.Seek(0, SeekOrigin.Begin);
                var outDict = serializer.Deserialize(stream) as SerializableDictionary<int, int>;
                Assert.AreEqual(dict[4], outDict[4]);
                Assert.AreEqual(dict[5], outDict[5]);
                Assert.AreEqual(dict[7], outDict[7]);
            }
        }
    }
}

What's the best way to calculate the size of a directory in .NET?

DirectoryInfo dirInfo = new DirectoryInfo(@strDirPath);
long dirSize = await Task.Run(() => dirInfo.EnumerateFiles( "*", SearchOption.AllDirectories).Sum(file => file.Length));

Quick way to retrieve user information Active Directory

I'm not sure how much of your "slowness" will be due to the loop you're doing to find entries with particular attribute values, but you can remove this loop by being more specific with your filter. Try this page for some guidance ... Search Filter Syntax

How to inject Javascript in WebBrowser control?

If all you really want is to run javascript, this would be easiest (VB .Net):

MyWebBrowser.Navigate("javascript:function foo(){alert('hello');}foo();")

I guess that this wouldn't "inject" it but it'll run your function, if that's what you're after. (Just in case you've over-complicated the problem.) And if you can figure out how to inject in javascript, put that into the body of the function "foo" and let the javascript do the injection for you.

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

How to get the response of XMLHttpRequest?

I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

_x000D_
_x000D_
const url = "https://stackoverflow.com";
fetch(url)
    .then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );
_x000D_
_x000D_
_x000D_

In Node.js, you'll need to import fetch using:

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

If you want to use it synchronously (doesn't work in top scope):

const json = await fetch(url)
  .then(response => response.json())
  .catch((e) => {});

More Info:

Mozilla Documentation

Can I Use (95% Feb 2020)

Matt Walsh Tutorial

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.

DATA SOURCE=DSDSDS:1521/ORCL;

How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("12/01/2011", usDtfi).ToString(ukDtfi.ShortDatePattern);

This will do the trick ^^

Strip off URL parameter with PHP

<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>

This will remove the 'i' parameter from the URL. Change the 'i's to whatever you need.

MVC: How to Return a String as JSON

You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

And then return it's instance:

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}

Find and replace with a newline in Visual Studio Code

Also note, after hitting the regex icon, to actually replace \n text with a newline, I had to use \\n as search and \n as replace.

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

I had this issue with a facebook application that I was developing for a fan page tab. If anyone faces this issue with a facebook application then

1-goto https://developers.facebook.com

2-select the application that you are developing

3-make sure that all the link to your application has tailing slash /

my issue was in the https://developers.facebook.com->Apps->MYAPPNAME->settings->Page Tab->Secure Page Tab URL, Page Tab Edit URL, Page Tab URL hope this will help

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

In runtime problems like these firstly open logcat if you are using android studio, try to analyse trace tree, go to the beginning from where exception started to rise, since that is usually the source of the problem. Now check for two things:

  1. Check in device file explorer(on the bottom right) there exist a database created by you. mostly you find it in DATA -> DATA -> com.example.hpc.demo(your pakage name) -> DATABASE -> demo.db

  2. Check that in your helper class you have added required '/' for example like below
    DB_location = "data/data/" + mcontext.getPackageName() + "/database/";

React component initialize state from props

Update for React 16.3 alpha introduced static getDerivedStateFromProps(nextProps, prevState) (docs) as a replacement for componentWillReceiveProps.

getDerivedStateFromProps is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. You may want to compare new and previous values if you only want to handle changes.

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

It is static, therefore it does not have direct access to this (however it does have access to prevState, which could store things normally attached to this e.g. refs)

edited to reflect @nerfologist's correction in comments

Is there a difference between using a dict literal and a dict constructor?

I think you have pointed out the most obvious difference. Apart from that,

the first doesn't need to lookup dict which should make it a tiny bit faster

the second looks up dict in locals() and then globals() and the finds the builtin, so you can switch the behaviour by defining a local called dict for example although I can't think of anywhere this would be a good idea apart from maybe when debugging

javac : command not found

Linux Mint 19.3

I installed Java Oracle manually, like this:

$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac

Cancel a UIView animation?

Sorry to resurrect this answer, but in iOS 10 things kinda changed, and now cancelling is possible and you can even cancel gracefully!

After iOS 10 you can cancel animations with UIViewPropertyAnimator!

UIViewPropertyAnimator(duration: 2, dampingRatio: 0.4, animations: {
    view.backgroundColor = .blue
})
animator.stopAnimation(true)

If you pass true it cancels the animation and it stops right where you cancelled it. The completion method will not be called. However, if you pass false you are responsible for finishing the animation:

animator.finishAnimation(.start)

You can finish your animation and stay in the current state (.current) or go to the initial state (.start) or to the end state (.end)

By the way, you can even pause and restart later...

animator.pauseAnimation()
animator.startAnimation()

Note: If you don't want an abrupt cancelling you can reverse your animation or even change your animation after you pause it!

How do you copy a record in a SQL table but swap out the unique id of the new row?

I know my answer is late to the party. But the way i solved is bit different than all the answers.

I had a situation, i need to clone a row in a table except few columns. Those few will have new values. This process should support automatically for future changes to the table. This implies, clone the record without specifying any column names.

My approach is to,

  1. Query Sys.Columns to get the full list of columns for the table and include the names of columns to skip in where clause.
  2. Convert that in to CSV as column names.
  3. Build Select ... Insert into script based on this.


declare @columnsToCopyValues varchar(max), @query varchar(max)
SET @columnsToCopyValues = ''

--Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2 Select @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2') Select @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues)) print @columnsToCopyValues

Select @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''')

print @query exec (@query)

html button to send email

You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.

The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.

When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)

Solr vs. ElasticSearch

I only use Elastic-search. Since I found solr is very hard to start. Elastic-search's features:

  1. Easy to start, very few setting. Even a newbie can setup a cluster step by step.
  2. Simple Restful API which using NoSQL query. And many language libraries for easy accessing.
  3. Good document, you can read the book: . There is a web version on official website.

Python: How to get values of an array at certain index positions?

Although you ask about numpy arrays, you can get the same behavior for regular Python lists by using operator.itemgetter.

>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)

Inverse of matrix in R

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

Compare two dates with JavaScript

Hi Here is my code to compare dates . In my case i am doing a check to not allow to select past dates.

var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();

if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
    if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                        if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                                            isPastPickupDateSelected = false;
                                            return;
                                        }
                    }
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;

Float a div in top right corner without overlapping sibling header

Another problem solved by the rubber duck:

The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/ enter image description here

Change your HTML code to have the div before the header:

<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>

And keep your CSS to the simple div { float: right; }.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

ReactJS and images in public folder

To reference images in public there are two ways I know how to do it straight forward. One is like above from Homam Bahrani.

using

    <img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} /> 

And since this works you really don't need anything else but, this also works...

    <img src={window.location.origin + '/yourPathHere.jpg'} />

Find all elements with a certain attribute value in jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo: http://jsfiddle.net/mCuWS/

Why is it bad style to `rescue Exception => e` in Ruby?

That's a specific case of the rule that you shouldn't catch any exception you don't know how to handle. If you don't know how to handle it, it's always better to let some other part of the system catch and handle it.

Is there a simple way to remove multiple spaces in a string?

import re

Text = " You can select below trims for removing white space!!   BR Aliakbar     "
  # trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='') 
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='') 
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')  
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='') 

Result:

Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar Remove leading space:You can select below trims for removing white space!! BR Aliakbar
Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar Remove more than one space: You can select below trims for removing white space!! BR Aliakbar

Regex that matches integers in between whitespace or start/end of string only

Try /^(?:-?[1-9]\d*$)|(?:^0)$/.

It matches positive, negative numbers as well as zeros.

It doesn't match input like 00, -0, +0, -00, +00, 01.

Online testing available at http://rubular.com/r/FlnXVL6SOq

how do you pass images (bitmaps) between android activities using bundles?

Bitmap is Parcelable so you can add using [putExtra(String,Parcelable)][2] method, But not sure it is a best practice, If it is large size data it is better to store in a single place and use from both activities.

[2]: http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Parcelable)

How can I select the first day of a month in SQL?

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

X-Frame-Options Allow-From multiple domains

YES. This method allowed multiple domain.

VB.NET

response.headers.add("X-Frame-Options", "ALLOW-FROM " & request.urlreferer.tostring())

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

For me the problem was actually the describe function, which when provided an arrow function, causes mocha to miss the timeout, and behave not consistently. (Using ES6)

since no promise was rejected I was getting this error all the time for different tests that were failing inside the describe block

so this how it looks when not working properly:

describe('test', () => { 
 assert(...)
})

and this works using the anonymous function

describe('test', function() { 
 assert(...)
})

Hope it helps someone, my configuration for the above: (nodejs: 8.4.0, npm: 5.3.0, mocha: 3.3.0)

Proper way to empty a C-String

needs name of string and its length will zero all characters other methods might stop at the first zero they encounter

    void strClear(char p[],u8 len){u8 i=0; 
        if(len){while(i<len){p[i]=0;i++;}}
    }

Killing a process created with Python's subprocess.Popen()

Only use Popen kill method

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()

IllegalMonitorStateException on wait() call

Those who are using Java 7.0 or below version can refer the code which I used here and it works.

public class WaitTest {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void waitHere(long waitTime) {
        System.out.println("wait started...");
        lock.lock();
        try {
            condition.await(waitTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("wait ends here...");
    }

    public static void main(String[] args) {
        //Your Code
        new WaitTest().waitHere(10);
        //Your Code
    }

}

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Python 3 Float Decimal Points/Precision

Try this:

num = input("Please input your number: ")

num = float("%0.2f" % (num))

print(num)

I believe this is a lot simpler. For 1 decimal place use %0.1f. For 2 decimal places use %0.2f and so on.

Or, if you want to reduce it all to 2 lines:

num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)

Using Vim's tabs like buffers

I use buffers like tabs, using the BufExplorer plugin and a few macros:

" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>

" gz in command mode closes the current buffer
map gz :bdelete<cr>

" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>

With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Regular expression to match any character being repeated more than 10 times

A slightly more generic powershell example. In powershell 7, the match is highlighted including the last space (can you highlight in stack?).

'a b c d e f ' | select-string '([a-f] ){6,}'

a b c d e f 

How do I use cascade delete with SQL Server?

Use something like

ALTER TABLE T2
ADD CONSTRAINT fk_employee
FOREIGN KEY (employeeID)
REFERENCES T1 (employeeID)
ON DELETE CASCADE;

Fill in the correct column names and you should be set. As mark_s correctly stated, if you have already a foreign key constraint in place, you maybe need to delete the old one first and then create the new one.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

And why don't you try with this ??? :

var itemsMax = items.Where(x => x.Height == items.Max(y => y.Height));

OR more optimise :

var itemMaxHeight = items.Max(y => y.Height);
var itemsMax = items.Where(x => x.Height == itemMaxHeight);

mmm ?

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How to check if a file exists in a folder?

if (File.Exists(localUploadDirectory + "/" + fileName))
{                        
    `Your code here`
}

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

Is there a simple way to delete a list element by value?

This removes all instances of "-v" from the array sys.argv, and does not complain if no instances were found:

while "-v" in sys.argv:
    sys.argv.remove('-v')

You can see the code in action, in a file called speechToText.py:

$ python speechToText.py -v
['speechToText.py']

$ python speechToText.py -x
['speechToText.py', '-x']

$ python speechToText.py -v -v
['speechToText.py']

$ python speechToText.py -v -v -x
['speechToText.py', '-x']

Declaring variables inside or outside of a loop

Truly, the question stated above is an programming issue. How would you like to program your code? Where do you need the 'STR' to be accessed? There is no use of declaring a variable which is used locally as a global variable. Basics of programming I believe.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.

Reading a UTF8 CSV file with Python

Looking at the Latin-1 unicode table, I see the character code 00E9 "LATIN SMALL LETTER E WITH ACUTE". This is the accented character in your sample data. A simple test in Python shows that UTF-8 encoding for this character is different from the unicode (almost UTF-16) encoding.

>>> u'\u00e9'
u'\xe9'
>>> u'\u00e9'.encode('utf-8')
'\xc3\xa9'
>>> 

I suggest you try to encode("UTF-8") the unicode data before calling the special unicode_csv_reader(). Simply reading the data from a file might hide the encoding, so check the actual character values.

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

How to set selected value from Combobox?

I suspect something is not right when you are saving to the db. Do i understand your steps as:

  1. populate and bind
  2. user selects and item, hit and save.. then you save in the db
  3. now if you select another item it won't select?

got more code, especially when saving? where in your code are initializing and populating the bindinglist

Close popup window

You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :

window.open

then

window.close

will work. Or else not.

What is a daemon thread in Java?

Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads. example updating system for unix,unix is daemon process. child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method. so daemon thread or daemon process are basically responsible for managing resources. for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory. jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.

FloatingActionButton example with Support Library

If you already added all libraries and it still doesn't work use:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_add" 
/>

instead of:

<android.support.design.widget.FloatingActionButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:srcCompat="@drawable/ic_add"
 />

And all will work fine :)

IllegalArgumentException or NullPointerException for a null parameter?

If you choose to throw a NPE and you are using the argument in your method, it might be redundant and expensive to explicitly check for a null. I think the VM already does that for you.

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

Show a number to two decimal places

Here's another solution with strtok and str_pad:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')

How to print VARCHAR(MAX) using Print Statement?

Here's another version. This one extracts each substring to print from the main string instead of taking reducing the main string by 4000 on each loop (which might create a lot of very long strings under the hood - not sure).

CREATE PROCEDURE [Internal].[LongPrint]
    @msg nvarchar(max)
AS
BEGIN

    -- SET NOCOUNT ON reduces network overhead
    SET NOCOUNT ON;

    DECLARE @MsgLen int;
    DECLARE @CurrLineStartIdx int = 1;
    DECLARE @CurrLineEndIdx int;
    DECLARE @CurrLineLen int;   
    DECLARE @SkipCount int;

    -- Normalise line end characters.
    SET @msg = REPLACE(@msg, char(13) + char(10), char(10));
    SET @msg = REPLACE(@msg, char(13), char(10));

    -- Store length of the normalised string.
    SET @MsgLen = LEN(@msg);        

    -- Special case: Empty string.
    IF @MsgLen = 0
    BEGIN
        PRINT '';
        RETURN;
    END

    -- Find the end of next substring to print.
    SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg);
    IF @CurrLineEndIdx BETWEEN 1 AND 4000
    BEGIN
        SET @CurrLineEndIdx = @CurrLineEndIdx - 1
        SET @SkipCount = 2;
    END
    ELSE
    BEGIN
        SET @CurrLineEndIdx = 4000;
        SET @SkipCount = 1;
    END     

    -- Loop: Print current substring, identify next substring (a do-while pattern is preferable but TSQL doesn't have one).
    WHILE @CurrLineStartIdx < @MsgLen
    BEGIN
        -- Print substring.
        PRINT SUBSTRING(@msg, @CurrLineStartIdx, (@CurrLineEndIdx - @CurrLineStartIdx)+1);

        -- Move to start of next substring.
        SET @CurrLineStartIdx = @CurrLineEndIdx + @SkipCount;

        -- Find the end of next substring to print.
        SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg, @CurrLineStartIdx);
        SET @CurrLineLen = @CurrLineEndIdx - @CurrLineStartIdx;

        -- Find bounds of next substring to print.              
        IF @CurrLineLen BETWEEN 1 AND 4000
        BEGIN
            SET @CurrLineEndIdx = @CurrLineEndIdx - 1
            SET @SkipCount = 2;
        END
        ELSE
        BEGIN
            SET @CurrLineEndIdx = @CurrLineStartIdx + 4000;
            SET @SkipCount = 1;
        END
    END
END

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Getting one value from a tuple

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

iPhone UITextField - Change placeholder text color

For Xamarin.iOS developers, I found it from this document https://developer.xamarin.com/api/type/Foundation.NSAttributedString/

textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });

What is the symbol for whitespace in C?

To check a space symbol you can use the following approach

if ( c == ' ' ) { /*...*/ }

To check a space and/or a tab symbol (standard blank characters) you can use the following approach

#include <ctype.h>

//...

if ( isblank( c ) ) { /*...*/ }

To check a white space you can use the following approach

#include <ctype.h>

//...

if ( isspace( c ) ) { /*...*/ }

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

ImportError: No module named 'pygame'

go to python/scripts folder, open a command window to this path, type the following:

C:\python34\scripts> python -m pip install pygame

To test it, open python IDE and type

import pygame

print (pygame.ver)

It worked for me...

How to get the height of a body element

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

How to make script execution wait until jquery is loaded

It's a common issue, imagine you use a cool PHP templating engine, so you have your base layout:

HEADER
BODY ==> dynamic CONTENT/PAGE
FOOTER

And of course, you read somewhere it's better to load Javascript at the bottom of the page, so your dynamic content doesnot know who is jQuery (or the $).

Also you read somewhere it's good to inline small Javascript, so imagine you need jQuery in a page, baboom, $ is not defined (.. yet ^^).

I love the solution Facebook provides

window.fbAsyncInit = function() { alert('FB is ready !'); }

So as a lazy programmer (I should say a good programmer ^^), you can use an equivalent (within your page):

window.jqReady = function() {}

And add at the bottom of your layout, after jQuery include

if (window.hasOwnProperty('jqReady')) $(function() {window.jqReady();});

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

How to edit a text file in my terminal

Open the file again using vi. and then press " i " or press insert key ,

For save and quit

  Enter Esc    

and write the following command

  :wq

without save and quit

  :q!

Why fragments, and when to use fragments instead of activities?

A fragment lives inside an activity, while an activity lives by itself.

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

What is SOA "in plain english"?

what tends to happen in large organizations is that over time everything is either monolithic or disparate systems everywhere or a little of both. Someone eventually comes in and says we've got a mess. Now, you want to re-design (money to someone) everything to be oriented in a sort of monotlithic depends on who you pay paradigm but at the same time be able to add pieces and parts independently of the master/monolith.

So you buy Oracle's SOA and Oracle becomes the boss of all your parts. All the other players coming in have to work with SOA via a service (web service or whatever it has.) The Oracle monolith takes care of everything (monolith is not meant derogatory). Oh yeah, you got ASP.NET MVC on the front or something else.

main thing is moving things in and out of they system without impact and keeping the vendor Oracle SOA, Microsoft WCF, as the brains of it all. everything's all oop/ood like, fluid, things moving in and out with little to no impact, even human services, not just computers.

To me it just means a bunch of web services (or whatever we call them in the future) with a good front end. And if you own the database just hit the database and stop worrying about buzzwords. it's okay.

How to convert NSDate into unix timestamp iphone sdk?

Swift

Updated for Swift 3

// current date and time
let someDate = Date()

// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970

Notes

  • timeIntervalSince1970 returns TimeInterval, which is a typealias for Double.

  • If you wanted to go the other way you could do the following:

      let myDate = Date(timeIntervalSince1970: myTimeStamp)
    

Possible reasons for timeout when trying to access EC2 instance

Check out this help page on AWS docs:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectionTimeout You will probably find your solution there. for me this part did the fix:

[EC2-VPC] Check the route table for the subnet. You need a route that sends all traffic destined outside the VPC to the Internet gateway for the VPC.

  • Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

  • In the navigation pane, choose Internet Gateways. Verify that there is an Internet gateway attached to your VPC. Otherwise, choose Create Internet Gateway and follow the directions to create an Internet gateway, select the Internet gateway, and then choose Attach to VPC and follow the directions to attach it to your VPC.

  • In the navigation pane, choose Subnets, and then select your subnet.

  • On the Route Table tab, verify that there is a route with 0.0.0.0/0 as the destination and the Internet gateway for your VPC as the target. Otherwise, choose the ID of the route table (rtb-xxxxxxxx) to navigate to the Routes tab for the route table, choose Edit, Add another route, enter 0.0.0.0/0 in Destination, select your Internet gateway from Target, and then choose Save.

But I suggest you check out all the options the link above covers , you may find there the one or more issues that you got.

What do the makefile symbols $@ and $< mean?

in exemple if you want to compile sources but have objects in an different directory :

You need to do :

gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...

but with most of macros the result will be all objects followed by all sources, like :

gcc -c -o <all OBJ path> <all SRC path>

so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(

the solution is to use these special macros

$@ $<

this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)

$(OBJ):$(SRC)
   gcc -c -o $@ $< $(HEADERS) $(FLAGS)

it means :

    $@ = $(OBJ)
    $< = $(SRC)

but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC

ImportError: No module named 'bottle' - PyCharm

I am using Ubuntu 16.04. For me it was the incorrect interpretor, which was by default using the virtual interpretor from project.

So, make sure you select the correct one, as the pip install will install the package to system python interpretor.

enter image description here

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Scroll / Jump to id without jQuery

Maybe You should try scrollIntoView.

document.getElementById('id').scrollIntoView();

This will scroll to your Element.

What is a bus error?

mmap minimal POSIX 7 example

"Bus error" happens when the kernel sends SIGBUS to a process.

A minimal example that produces it because ftruncate was forgotten:

#include <fcntl.h> /* O_ constants */
#include <unistd.h> /* ftruncate */
#include <sys/mman.h> /* mmap */

int main() {
    int fd;
    int *map;
    int size = sizeof(int);
    char *name = "/a";

    shm_unlink(name);
    fd = shm_open(name, O_RDWR | O_CREAT, (mode_t)0600);
    /* THIS is the cause of the problem. */
    /*ftruncate(fd, size);*/
    map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    /* This is what generates the SIGBUS. */
    *map = 0;
}

Run with:

gcc -std=c99 main.c -lrt
./a.out

Tested in Ubuntu 14.04.

POSIX describes SIGBUS as:

Access to an undefined portion of a memory object.

The mmap spec says that:

References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.

And shm_open says that it generates objects of size 0:

The shared memory object has a size of zero.

So at *map = 0 we are touching past the end of the allocated object.

Unaligned stack memory accesses in ARMv8 aarch64

This was mentioned at: What is a bus error? for SPARC, but here I will provide a more reproducible example.

All you need is a freestanding aarch64 program:

.global _start
_start:
asm_main_after_prologue:
    /* misalign the stack out of 16-bit boundary */
    add sp, sp, #-4
    /* access the stack */
    ldr w0, [sp]

    /* exit syscall in case SIGBUS does not happen */
    mov x0, 0
    mov x8, 93
    svc 0

That program then raises SIGBUS on Ubuntu 18.04 aarch64, Linux kernel 4.15.0 in a ThunderX2 server machine.

Unfortunately, I can't reproduce it on QEMU v4.0.0 user mode, I'm not sure why.

The fault appears to be optional and controlled by the SCTLR_ELx.SA and SCTLR_EL1.SA0 fields, I have summarized the related docs a bit further here.

jQuery’s .bind() vs. .on()

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

jQuery API documentation for .bind()

Getting the folder name from a path

It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.

For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

JRE installation directory in Windows

Look the answer to my previous question here

c:\> for %i in (java.exe) do @echo.   %~$PATH:i
C:\WINDOWS\system32\java.exe

Remove category & tag base from WordPress url - without a plugin

updated answer:

other solution:
In wp-includes/rewrite.php file, you'll see the code:
$this->category_structure = $this->front . 'category/'; just copy whole function, put in your functions.php and hook it. just change the above line with:
$this->category_structure = $this->front . '/';

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

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

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

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

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

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

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

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

Selecting text in an element (akin to highlighting with your mouse)

For any tag one can select all text inside that tag by this short and simple code. It will highlight the entire tag area with yellow colour and select text inside it on single click.

document.onclick = function(event) {
    var range, selection;
event.target.style.backgroundColor = 'yellow';
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(event.target);
        selection.removeAllRanges();
        selection.addRange(range);
};

Can't connect to MySQL server on 'localhost' (10061) after Installation

I had the same issue and basically resolved it by pointing to a specific port number that my MySQL server was running on. Below is the command. Please edit the code to fit your case i.e your port number,your mysql server username,your password.

    mysql -u root -pYourMysqlRootPassword -P3307 

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

Make Bootstrap's Carousel both center AND responsive?

On Boostrap 4 simply add mx-auto to your carousel image class.

<div class="carousel-item">
  <img class="d-block mx-auto" src="http://placehold.it/600x400" />
</div> 

Combine with the samples from the bootstrap carousel documentation as desired.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

SQL Server 2008: TOP 10 and distinct together

The easy option is to use group by and select min/max for all other fields

SELECT TOP 10 
    p.id, 
    max(pl.nm),
    max(pl.val),
    max(pl.txt_val)
from 
    dm.labs pl
join 
    mas_data.patients p    
on 
    pl.id = p.id
  where 
    pl.nm like '%LDL%'
and 
    val is not null
group by 
    p.id

This can get quite tedious for wide table so the other option is to use rank over and partiion

SELECT TOP 10 
    p.id, 
     pl.nm, 
     pl.val, 
   pl.txt_val, 
    rank() over(partition by p.id order by p.id) as Rank
from 
    dm.labs pl
join 
    mas_data.patients p    
on 
    pl.id = p.id
  where 
    pl.nm like '%LDL%'
and 
    val is not null
and
    Rank = 1

How to convert/parse from String to char in java?

You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String. If the string is 1 character long, just take that character by calling .charAt(0) (or .First() in C#).

Import module from subfolder

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the 'targetClass.py' file inside the Generic-Class-Folder file to use the function named "functionExecute" in 'targetClass.py' file

What command I did?

  • from 'testFile.py', wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong......

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)

Display only 10 characters of a long string?

var example = "I am too long string";
var result;

// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add

Result variable contains "I am too l..."

SQL Server procedure declare a list

You could declare a variable as a temporary table like this:

declare @myList table (Id int)

Which means you can use the insert statement to populate it with values:

insert into @myList values (1), (2), (5), (7), (10)

Then your select statement can use either the in statement:

select * from DBTable
where id in (select Id from @myList)

Or you could join to the temporary table like this:

select *
from DBTable d
join @myList t on t.Id = d.Id

And if you do something like this a lot then you could consider defining a user-defined table type so you could then declare your variable like this:

declare @myList dbo.MyTableType

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

For me the problem was the <base href="https://domain.ext/"> tag.

After removing, it was OK. Cannot really understand why it was a problem.

Get the current date in java.sql.Date format

A java.util.Date is not a java.sql.Date. It's the other way around. A java.sql.Date is a java.util.Date.

You'll need to convert it to a java.sql.Date by using the constructor that takes a long that a java.util.Date can supply.

java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

Python pandas insert list into a cell

I've got a solution that's pretty simple to implement.

Make a temporary class just to wrap the list object and later call the value from the class.

Here's a practical example:

  1. Let's say you want to insert list object into the dataframe.
df = pd.DataFrame([
    {'a': 1},
    {'a': 2},
    {'a': 3},
])

df.loc[:, 'b'] = [
    [1,2,4,2,], 
    [1,2,], 
    [4,5,6]
] # This works. Because the list has the same length as the rows of the dataframe

df.loc[:, 'c'] = [1,2,4,5,3] # This does not work. 

>>> ValueError: Must have equal len keys and value when setting with an iterable

## To force pandas to have list as value in each cell, wrap the list with a temporary class.

class Fake(object):
    def __init__(self, li_obj):
        self.obj = li_obj

df.loc[:, 'c'] = Fake([1,2,5,3,5,7,]) # This works. 

df.c = df.c.apply(lambda x: x.obj) # Now extract the value from the class. This works. 

Creating a fake class to do this might look like a hassle but it can have some practical applications. For an example you can use this with apply when the return value is list.

Pandas would normally refuse to insert list into a cell but if you use this method, you can force the insert.

C pass int array pointer as parameter into a function

Make use of *(B) instead of *B[0]. Here, *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

#include <stdio.h>

int func(int *B){
    *B = 5;     
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

I was with the same problem in devices with SDK < 22, but for me the reason is the MultiDex, the MultiDex.install must be in the attachBaseContext method.

If you are using MultiDex, try this:

public class YourApplication extends Application {

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this); //initialize other plugins 

    }
}

app/build.gradle:

android {

    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "com.test.app"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }

....
}

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])

        compile 'com.android.support:appcompat-v7:24.2.1'
        ...
        compile 'com.google.firebase:firebase-messaging:9.6.1'
        compile 'com.google.android.gms:play-services:9.6.1'
        compile 'com.android.support:multidex:1.0.1'

    }
...

Where is git.exe located?

It seems like git.exe can be found in different places depending on how it was installed, the version, and version of Windows.

I installed Git-2.6.3-64-bit.exe (cleand install; just git, not the Github Desktop client) on Windows 10 Pro N. This is the default location:

%USERPROFILE%\AppData\Local\Programs\Git\mingw64\bin\git.exe

and

%USERPROFILE%\AppData\Local\Programs\Git\bin

How do I check if a variable is of a certain type (compare two types) in C?

As other people have already said this isn't supported in the C language. You could however check the size of a variable using the sizeof() function. This may help you determine if two variables can store the same type of data.

Before you do that, read the comments below.

Play sound on button click android

there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.

Nice!

MediaActionSound

A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs

use like:

fun playBeepSound() {
    val sound = MediaActionSound()
    sound.play(MediaActionSound.START_VIDEO_RECORDING)
}

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

declare @T int

set @T = 10455836
--set @T = 421151

select (@T / 1000000) % 100 as hour,
       (@T / 10000) % 100 as minute,
       (@T / 100) % 100 as second,
       (@T % 100) * 10 as millisecond

select dateadd(hour, (@T / 1000000) % 100,
       dateadd(minute, (@T / 10000) % 100,
       dateadd(second, (@T / 100) % 100,
       dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))  

Result:

hour        minute      second      millisecond
----------- ----------- ----------- -----------
10          45          58          360

(1 row(s) affected)


----------------
10:45:58.36

(1 row(s) affected)

Node.js: for each … in not working

for those used to php:

//add this function
function foreach(arr, func){
  for(var i in arr){
    func(i, arr[i]);
  }
}

usage:

foreach(myArray, function(i, v){
  //run code here
});

similar to php version:

foreach(myArray as i=>v){
  //run code here
}

Git merge without auto commit

Note the output while doing the merge - it is saying Fast Forward

In such situations, you want to do:

git merge v1.0 --no-commit --no-ff

JQuery wait for page to finish loading before starting the slideshow?

The $(document).ready mechanism is meant to fire after the DOM has been loaded successfully but makes no guarantees as to the state of the images referenced by the page.

When in doubt, fall back on the good ol' window.onload event:

window.onload = function()
{
  //your code here
};

Now, this is obviously slower than the jQuery approach. However, you can compromise somewhere in between:

$(document).ready
(
  function()
  {
    var img = document.getElementById("myImage");

    var intervalId = setInterval(
                        function()
                        {
                          if(img.complete)
                          {
                            clearInterval(intervalId);
                            //now we can start rotating the header
                          }
                        },
                        50);
  }
);

To explain a bit:

  1. we grab the DOM element of the image whose image we want completely loaded

  2. we then set an interval to fire every 50 milliseconds.

  3. if, during one of these intervals, the complete attribute of this image is set to true, the interval is cleared and the rotate operation is safe to start.

How to set environment variables in Python?

Environment variables must be strings, so use

os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use:

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.

How can I color Python logging output?

The bit I had trouble with was setting up the formatter properly:

class ColouredFormatter(logging.Formatter):    
    def __init__(self, msg):
        logging.Formatter.__init__(self, msg)
        self._init_colour = _get_colour()

    def close(self):
        # restore the colour information to what it was
        _set_colour(self._init_colour)

    def format(self, record):        
        # Add your own colourer based on the other examples
        _set_colour( LOG_LEVEL_COLOUR[record.levelno] )
        return logging.Formatter.format(self, record)         

def init():
    # Set up the formatter. Needs to be first thing done.
    rootLogger = logging.getLogger()
    hdlr = logging.StreamHandler()
    fmt = ColouredFormatter('%(message)s')
    hdlr.setFormatter(fmt)
    rootLogger.addHandler(hdlr)

And then to use:

import coloured_log
import logging

coloured_log.init()
logging.info("info")    
logging.debug("debug")    

coloured_log.close()    # restore colours

java.util.NoSuchElementException - Scanner reading user input

the reason of the exception has been explained already, however the suggested solution isn't really the best.

You should create a class that keeps a Scanner as private using Singleton Pattern, that makes that scanner unique on your code.

Then you can implement the methods you need or you can create a getScanner ( not recommended ) and you can control it with a private boolean, something like alreadyClosed.

If you are not aware how to use Singleton Pattern, here's a example:

public class Reader {
    
    
    private Scanner reader;
    private static Reader singleton = null;
    private boolean alreadyClosed;
    
    private Reader() {
        alreadyClosed = false;
        reader = new Scanner(System.in);
    }
    
    public static Reader getInstance() {
        if(singleton == null) {
            singleton = new Reader();
        }
        return singleton;
    }
    
    public int nextInt() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextInt();
        }
        throw new AlreadyClosedException(); //Custom exception
    }
    
    public double nextDouble() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextDouble();
        }
        throw new AlreadyClosedException();
    }
    
    public String nextLine() throws AlreadyClosedException {
        if(!alreadyClosed) {
            return reader.nextLine();
        }
        throw new AlreadyClosedException();
    }
    
    public void close() {
        alreadyClosed = true;
        reader.close();
    }   
}

Oracle Add 1 hour in SQL

To add/subtract from a DATE, you have 2 options :

Method #1 : The easiest way is to use + and - to add/subtract days, hours, minutes, seconds, etc.. from a DATE, and ADD_MONTHS() function to add/subtract months and years from a DATE. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS() and no add_years(), because from months, you can get years (1 year = 12 months).

Let's try them :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')             FROM dual;        -- prints current date:    19-OCT-2019 20:42:02 
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS')    FROM dual;        -- prints date + 1 hour:   19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS')  FROM dual;        -- prints date + 1 minute: 19-OCT-2019 20:43:02 
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 second: 19-OCT-2019 20:42:03 
-- Same goes for subtraction.

SELECT SYSDATE                  FROM dual;       -- prints current date:     19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1)   FROM dual;       -- prints date + 1 month:   19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12)  FROM dual;       -- prints date + 1 year:    19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3)  FROM dual;       -- prints date - 3 months:  19-JUL-19

Method #2 : Using INTERVALs, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..) Examples :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')                                        FROM dual;        -- prints current date:                 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS')                  FROM dual;        -- prints date + 1 hour:                19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 minute:              19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 second:              19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 hour and 5 minutes:  19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS')        FROM dual;        -- prints date + 3 days and 1 hour:     22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS')      FROM dual;        -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15

Changing Locale within the app itself

Through the original question is not exactly about the locale itself all other locale related questions are referencing to this one. That's why I wanted to clarify the issue here. I used this question as a starting point for my own locale switching code and found out that the method is not exactly correct. It works, but only until any configuration change (e.g. screen rotation) and only in that particular Activity. Playing with a code for a while I have ended up with the following approach:

I have extended android.app.Application and added the following code:

public class MyApplication extends Application
{
    private Locale locale = null;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        if (locale != null)
        {
            newConfig.locale = locale;
            Locale.setDefault(locale);
            getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        Configuration config = getBaseContext().getResources().getConfiguration();

        String lang = settings.getString(getString(R.string.pref_locale), "");
        if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
        {
            locale = new Locale(lang);
            Locale.setDefault(locale);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        }
    }
}

This code ensures that every Activity will have custom locale set and it will not be reset on rotation and other events.

I have also spent a lot of time trying to make the preference change to be applied immediately but didn't succeed: the language changed correctly on Activity restart, but number formats and other locale properties were not applied until full application restart.

Changes to AndroidManifest.xml

Don't forget to add android:configChanges="layoutDirection|locale" to every activity at AndroidManifest, as well as the android:name=".MyApplication" to the <application> element.

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

UITableViewCell, show delete button on swipe

I had a problem which I have just managed to solve so I am sharing it as it may help someone.

I have a UITableView and added the methods shown to enable swipe to delete:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.

It turns out that adding the following line to viewDidLoad was the issue:

self.tableView.allowsMultipleSelectionDuringEditing = YES;

With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.

The fix:

Add the following method to your viewController:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    self.tableView.allowsMultipleSelectionDuringEditing = editing; 
    [super setEditing:editing animated:animated];
}

Then in your method that puts the table into editing mode (from a button press for example) you should use:

[self setEditing:YES animated:YES];

instead of:

[self.tableView setEditing:YES animated:YES];

This means that multiselect is only enabled when the table is in editing mode.

node.js string.replace doesn't work?

Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

Binding multiple events to a listener (without JQuery)?

In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:

/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
  var events = eventNames.split(' ');
  for (var i=0, iLen=events.length; i<iLen; i++) {
    element.addEventListener(events[i], listener, false);
  }
}

addListenerMulti(window, 'mousemove touchmove', function(){…});

Hopefully it shows the concept.

Edit 2016-02-25

Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:

function addListenerMulti(el, s, fn) {
  s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}

A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.

How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

OR

Using CSV writer :

import csv
with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

This is an old thread but I was surprised nobody mentioned grep. The -A option allows specifying a number of lines to print after a search match and the -B option includes lines before a match. The following command would output 10 lines before and 10 lines after occurrences of "my search string" in the file "mylogfile.log":

grep -A 10 -B 10 "my search string" mylogfile.log

If there are multiple matches within a large file the output can rapidly get unwieldy. Two helpful options are -n which tells grep to include line numbers and --color which highlights the matched text in the output.

If there is more than file to be searched grep allows multiple files to be listed separated by spaces. Wildcards can also be used. Putting it all together:

grep -A 10 -B 10 -n --color "my search string" *.log someOtherFile.txt

jQuery 1.9 .live() is not a function

Forward port of .live() for jQuery >= 1.9 Avoids refactoring JS dependencies on .live() Uses optimized DOM selector context

/** 
 * Forward port jQuery.live()
 * Wrapper for newer jQuery.on()
 * Uses optimized selector context 
 * Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
  jQuery.fn.extend({
      live: function (event, callback) {
         if (this.selector) {
              jQuery(document).on(event, this.selector, callback);
          }
      }
  });
}

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

0xE0434352 is the exception code for all .NET exceptions so that won't tell you much. How did you got this exception code? The event log?

Your best bet is to use a debugger to get more information. If the Visual Studio debugger won't help you, then you might need to check out WinDbg with SOS. See here and here for an introduction. Let it break on the exception, and see if you can get more information on the why.

If you suspect it is an issue when loading assemblies you might want to check out the Fusion Log.

An example of how to use getopts in bash

"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.

So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.

Update 08-04-2020: I've added support for hyphens e.g. "--package-name".

Usage: "./script.sh package install --package "name with space" --build --archive"

# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
  PREVIOUS_ITEM=''
  COUNT=0
  for CURRENT_ITEM in "${@}"
  do
    if [[ ${CURRENT_ITEM} == "--"* ]]; then
      printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
    else
      if [[ $PREVIOUS_ITEM == "--"* ]]; then
        printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
      else
        printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
      fi
    fi

    PREVIOUS_ITEM="${CURRENT_ITEM}"
    (( COUNT++ ))
  done
}

# Format argument.
function formatArgument() {
  ARGUMENT="${1^^}" # Capitalize.
  ARGUMENT="${ARGUMENT/--/}" # Remove "--".
  ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
  echo "${ARGUMENT}"
}

SQL Update Multiple Fields FROM via a SELECT Statement

you can use update from...

something like:

update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...

Replacing objects in array

Considering that the accepted answer is probably inefficient for large arrays, O(nm), I usually prefer this approach, O(2n + 2m):

function mergeArrays(arr1 = [], arr2 = []){
    //Creates an object map of id to object in arr1
    const arr1Map = arr1.reduce((acc, o) => {
        acc[o.id] = o;
        return acc;
    }, {});
    //Updates the object with corresponding id in arr1Map from arr2, 
    //creates a new object if none exists (upsert)
    arr2.forEach(o => {
        arr1Map[o.id] = o;
    });

    //Return the merged values in arr1Map as an array
    return Object.values(arr1Map);
}

Unit test:

it('Merges two arrays using id as the key', () => {
   var arr1 = [{id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'}];
   var arr2 = [{id:'124',name:'ttt'}, {id:'45',name:'yyy'}];
   const actual = mergeArrays(arr1, arr2);
   const expected = [{id:'124',name:'ttt'}, {id:'589',name:'www'}, {id:'45',name:'yyy'}, {id:'567',name:'rrr'}];
   expect(actual.sort((a, b) => (a.id < b.id)? -1: 1)).toEqual(expected.sort((a, b) => (a.id < b.id)? -1: 1));
})

How to get the python.exe location programmatically?

I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe

which gives this value on my machine:

C:\Python25\Python.exe

You just read the registry key to get the location.

However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.

How to solve '...is a 'type', which is not valid in the given context'? (C#)

Change

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS = new CERas.CERAS(); 
    } 

to

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS c = new CERas.CERAS(); 
    } 

Or if you wish to use it later again

change it to

using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WinApp_WMI2 
{ 
    public partial class Form1 : Form 
    { 
        CERas.CERAS m_CERAS;

        public Form1() 
        { 
            InitializeComponent(); 
        } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
        m_CERAS = new CERas.CERAS(); 
    } 
} 


}

How to pass a single object[] to a params object[]

One option is you can wrap it into another array:

Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });

Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:

Foo((object) new object[]{ (object)"1", (object)"2" });

Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:

void Foo(object[] item)
{
    // Somehow don't duplicate Foo(object[]) and
    // Foo(params object[]) without making an infinite
    // recursive call... maybe something like
    // FooImpl(params object[] items) and then this
    // could invoke it via:
    // FooImpl(new object[] { item });
}

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

In my case the problem was - I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder - and that made a collision with settings.py. Just renamed that Settings folder - and everything worked.

Why is there no String.Empty in Java?

Use org.apache.commons.lang.StringUtils.EMPTY

Free easy way to draw graphs and charts in C++?

My favourite has always been gnuplot. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is a C++ API.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

How to add a list item to an existing unordered list?

How about using "after" instead of "append".

$("#content ul li:last").after('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

".after()" can insert content, specified by the parameter, after each element in the set of matched elements.

Using onBackPressed() in Android Fragments

Why don't you want to use the back stack? If there is an underlying problem or confusion maybe we can clear it up for you.

If you want to stick with your requirement just override your Activity's onBackPressed() method and call whatever method you're calling when the back arrow in your ActionBar gets clicked.

EDIT: How to solve the "black screen" fragment back stack problem:

You can get around that issue by adding a backstack listener to the fragment manager. That listener checks if the fragment back stack is empty and finishes the Activity accordingly:

You can set that listener in your Activity's onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentManager fm = getFragmentManager();
    fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if(getFragmentManager().getBackStackEntryCount() == 0) finish();
        }
    });
}

App.settings - the Angular way?

Here's my two solutions for this

1. Store in json files

Just make a json file and get in your component by $http.get() method. If I was need this very low then it's good and quick.

2. Store by using data services

If you want to store and use in all components or having large usage then it's better to use data service. Like this :

  1. Just create static folder inside src/app folder.

  2. Create a file named as fuels.ts into static folder. You can store other static files here also. Let define your data like this. Assuming you having fuels data.

__

export const Fuels {

   Fuel: [
    { "id": 1, "type": "A" },
    { "id": 2, "type": "B" },
    { "id": 3, "type": "C" },
    { "id": 4, "type": "D" },
   ];
   }
  1. Create a file name static.services.ts

__

import { Injectable } from "@angular/core";
import { Fuels } from "./static/fuels";

@Injectable()
export class StaticService {

  constructor() { }

  getFuelData(): Fuels[] {
    return Fuels;
  }
 }`
  1. Now You can make this available for every module

just import in app.module.ts file like this and change in providers

import { StaticService } from './static.services';

providers: [StaticService]

Now use this as StaticService in any module.

That's All.

How to create EditText with cross(x) button at end of it?

This is a kotlin solution. Put this helper method in some kotlin file-

fun EditText.setupClearButtonWithAction() {

    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear else 0
            setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
    })

    setOnTouchListener(View.OnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= (this.right - this.compoundPaddingRight)) {
                this.setText("")
                return@OnTouchListener true
            }
        }
        return@OnTouchListener false
    })
}

And then use it as following in the onCreate method and you should be good to go-

yourEditText.setupClearButtonWithAction()

BTW, you have to add R.drawable.ic_clear or the clear icon at first. This one is from google- https://material.io/tools/icons/?icon=clear&style=baseline

Change Schema Name Of Table In SQL

Be very very careful renaming objects in sql. You can cause dependencies to fail if you are not fully away with what you are doing. Having said that this works easily(too much so) for renaming things provided you have access proper on the environment:

exec sp_rename 'Nameofobject', 'ReNameofobject'

MySQL FULL JOIN?

Various types of joins, for illustration

There are a couple of methods for full mysql FULL [OUTER] JOIN.

  1. UNION a left join and right join. UNION will remove duplicates by performing an ORDER BY operation. So depending on your data, it may not be performant.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION 
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
    
  2. UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION ALL
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
       WHERE A.key IS NULL
    

How to find tags with only certain attributes - BeautifulSoup

The easiest way to do this is with the new CSS style select method:

soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:

Output

PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

Function pointer to member function

Call member function on string command

#include <iostream>
#include <string>


class A 
{
public: 
    void call();
private:
    void printH();
    void command(std::string a, std::string b, void (A::*func)());
};

void A::printH()
{
    std::cout<< "H\n";
}

void A::call()
{
    command("a","a", &A::printH);
}

void A::command(std::string a, std::string b, void (A::*func)())
{
    if(a == b)
    {
        (this->*func)();
    }
}

int main()
{
    A a;
    a.call();
    return 0;
}

Pay attention to (this->*func)(); and the way to declare the function pointer with class name void (A::*func)()

How to rename files and folder in Amazon S3?

There is one software where you can play with the s3 bucket for performing different kinds of operation.

Software Name: S3 Browser

S3 Browser is a freeware Windows client for Amazon S3 and Amazon CloudFront. Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. Amazon CloudFront is a content delivery network (CDN). It can be used to deliver your files using a global network of edge locations.


If it's only single time then you can use the command line to perform these operations:

(1) Rename the folder in the same bucket:

s3cmd --access_key={access_key} --secret_key={secret_key} mv s3://bucket/folder1/* s3://bucket/folder2/

(2) Rename the Bucket:

s3cmd --access_key={access_key} --secret_key={secret_key} mv s3://bucket1/folder/* s3://bucket2/folder/

Where,

{access_key} = Your valid access key for s3 client

{secret_key} = Your valid scret key for s3 client

It's working fine without any problem.

Thanks

Delete branches in Bitbucket

For deleting branch from Bitbucket,

  1. Go to Overview (Your repository > branches in the left sidebar)
  2. Click the number of branches (that should show you the list of branches)
  3. Click on the branch that you want to delete
  4. On top right corner, click the 3 dots (besides Merge button).
  5. There is the option of "Delete Branch" if you have rights.

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

Assign output of a program to a variable using a MS batch file

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM Prefer backtick usage for command output reading:
REM ENABLEDELAYEDEXPANSION is required for actualized
REM  outer variables within for's scope;
REM within for's scope, access to modified 
REM outer variable is done via !...! syntax.

SET CHP=C:\Windows\System32\chcp.com

FOR /F "usebackq tokens=1,2,3" %%i IN (`%CHP%`) DO (
    IF "%%i" == "Aktive" IF "%%j" == "Codepage:" (
        SET SELCP=%%k
        SET SELCP=!SELCP:~0,-1!
    )
)
echo actual codepage [%SELCP%]

ENDLOCAL

How do I read from parameters.yml in a controller in symfony2?

I send you an example with swiftmailer:

parameters.yml

recipients: [email1, email2, email3]

services:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

the class of the service:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

How to read request body in an asp.net core webapi controller?

A clearer solution, works in ASP.Net Core 2.1 / 3.1

Filter class

using Microsoft.AspNetCore.Authorization;
// For ASP.NET 2.1
using Microsoft.AspNetCore.Http.Internal;
// For ASP.NET 3.1
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

public class ReadableBodyStreamAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // For ASP.NET 2.1
        // context.HttpContext.Request.EnableRewind();
        // For ASP.NET 3.1
        // context.HttpContext.Request.EnableBuffering();
    }
}

In an Controller

[HttpPost]
[ReadableBodyStream]
public string SomePostMethod()
{
    //Note: if you're late and body has already been read, you may need this next line
    //Note2: if "Note" is true and Body was read using StreamReader too, then it may be necessary to set "leaveOpen: true" for that stream.
    HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

    using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
    {
        string body = stream.ReadToEnd();
        // body = "param=somevalue&param2=someothervalue"
    }
}

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

Is Visual Studio Community a 30 day trial?

In my case, I already was signed in. So I had to sign out and sign in again.

In spanish Cerrar Sesion is sign out.

screenshot

Get push notification while App in foreground iOS

Here is the code to receive Push Notification when app in active state (foreground or open). UNUserNotificationCenter documentation

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}

If you need to access userInfo of notification use code: notification.request.content.userInfo

What languages are Windows, Mac OS X and Linux written in?

Linux: C. Some parts in assembly.

[...] It's mostly in C, but most people wouldn't call what I write C. It uses every conceivable feature of the 386 I could find, as it was also a project to teach me about the 386. As already mentioned, it uses a MMU, for both paging (not to disk yet) and segmentation. It's the segmentation that makes it REALLY 386 dependent (every task has a 64Mb segment for code & data - max 64 tasks in 4Gb. Anybody who needs more than 64Mb/task - tough cookies). [...] Some of my "C"-files (specifically mm.c) are almost as much assembler as C. [...] Unlike minix, I also happen to LIKE interrupts, so interrupts are handled without trying to hide the reason behind them. (Source)

Mac OS X: Cocoa mostly in Objective-C. Kernel written in C, some parts in assembly.

Mac OS X, at the kernel layer, is mostly an older, free operating system called BSD (specifically, it’s Darwin, a sort of hybrid of BSD, Mach, and a few other things)... almost entirely C, with a bit of assembler thrown in. (Source)

Much of Cocoa is implemented in Objective-C, an object-oriented language that is compiled to run at incredible speed, yet employes a truly dynamic runtime making it uniquely flexible. Because Objective-C is a superset of C, it is easy to mix C and even C++ into your Cocoa applications. (Source)

Windows: C, C++, C#. Some parts in assembler.

We use almost entirely C, C++, and C# for Windows. Some areas of code are hand tuned/hand written assembly. (Source)

Unix: C. Some parts in assembly. (Source)

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Any way to break if statement in PHP?

No.

But how about:

$a="test";
if("test"==$a)
{
  if ($someOtherCondition)
  {
    echo "yes";
  }
}
echo "finish";

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

installing JDK8 on Windows XP - advapi32.dll error

This happens because Oracle dropped support for Windows XP (which doesn't have RegDeleteKeyExA used by the installer in its ADVAPI32.DLL by the way) as described in http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-July/009005.html. Yet while the official support for XP has ended, the Java binaries are still (as of Java 8u20 EA b05 at least) XP-compatible - only the installer isn't...

Because of that, the solution is actually quite easy:

  1. get 7-Zip (or any other good unpacker), unpack the distribution .exe manually, it has one .zip file inside of it (tools.zip), extract it too,

  2. use unpack200 from JDK8 to unpack all .pack files to .jar files (older unpacks won't work properly); JAVA_HOME environment variable should be set to your Java unpack root, e.g. "C:\Program Files\Java\jdk8" - you can specify it implicitly by e.g.

    SET JAVA_HOME=C:\Program Files\Java\jdk8
    
    • Unpack all files with a single command (in batch file):

      FOR /R %%f IN (*.pack) DO "%JAVA_HOME%\bin\unpack200.exe" -r -v "%%f" "%%~pf%%~nf.jar"
      
    • Unpack all files with a single command (command line from JRE root):

      FOR /R %f IN (*.pack) DO "bin\unpack200.exe" -r -v "%f" "%~pf%~nf.jar"
      
    • Unpack by manually locating the files and unpacking them one-by-one:

      %JAVA_HOME%\bin\unpack200 -r packname.pack packname.jar
      

    where packname is for example rt

  3. point the tool you want to use (e.g. Netbeans) to the %JAVA_HOME% and you're good to go.

Note: you probably shouldn't do this just to use Java 8 in your web browser or for any similar reason (installing JRE 8 comes to mind); security flaws in early updates of major Java version releases are (mind me) legendary, and adding to that no real support for neither XP nor Java 8 on XP only makes matters much worse. Not to mention you usually don't need Java in your browser (see e.g. http://nakedsecurity.sophos.com/2013/01/15/disable-java-browsers-homeland-security/ - the topic is already covered on many pages, just Google it if you require further info). In any case, AFAIK the only thing required to apply this procedure to JRE is to change some of the paths specified above from \bin\ to \lib\ (the file placement in installer directory tree is a bit different) - yet I strongly advise against doing it.

See also: How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?, JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

Class file has wrong version 52.0, should be 50.0

In your IntelliJ idea find tools.jar replace it with tools.jar from yout JDK8

Split string based on regex

Your question contains the string literal "\b[A-Z]{2,}\b", but that \b will mean backspace, because there is no r-modifier.

Try: r"\b[A-Z]{2,}\b".

Hide div after a few seconds

There's a really simple way to do this.

The problem is that .delay only effects animations, so what you need to do is make .hide() act like an animation by giving it a duration.

$("#whatever").delay().hide(1);

By giving it a nice short duration, it appears to be instant just like the regular .hide function.

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

How to get the first non-null value in Java?

If there are only two variables to check and you're using Guava, you can use MoreObjects.firstNonNull(T first, T second).

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

Best practices for copying files with Maven

I've had very good experience with copy-maven-plugin. It has a much more convenient and concise syntax in comparison to maven-resources-plugin.

Fix CSS hover on iPhone/iPad/iPod

  1. Assigning an event listener to the target element seems to work. (Works with 'click', at least.) CSS hover on ios works only if an event listener is assigned

  2. Wrapping the target element in an a[href=trivial] also seems to work. https://stackoverflow.com/a/28792519/1378390

A related note/diagram on mobile Safari's algorithm for handling clicks and other events is here: Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users?

Django Multiple Choice Field / Checkbox Select Multiple

ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.

Table-level backup

Create new filegroup, put this table on it, and backup this filegroup only.

How to find the privileges and roles granted to a user in Oracle?

Look at http://docs.oracle.com/cd/B10501_01/server.920/a96521/privs.htm#15665

Check USER_SYS_PRIVS, USER_TAB_PRIVS, USER_ROLE_PRIVS tables with these select statements

SELECT * FROM USER_SYS_PRIVS; 
SELECT * FROM USER_TAB_PRIVS; 
SELECT * FROM USER_ROLE_PRIVS;

When is "java.io.IOException:Connection reset by peer" thrown?

For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java

// The remote forcibly closed the connection, cancel

// the selection key and close the channel.

    private void read(SelectionKey key) throws IOException {
            SocketChannel socketChannel = (SocketChannel) key.channel();

            // Clear out our read buffer so it's ready for new data
            this.readBuffer.clear();

            // Attempt to read off the channel
            int numRead;
            try {
                numRead = socketChannel.read(this.readBuffer);
            } catch (IOException e) {
                // The remote forcibly closed the connection, cancel
                // the selection key and close the channel.
                key.cancel();
                socketChannel.close();
                return;
            }

            if (numRead == -1) {
                // Remote entity shut the socket down cleanly. Do the
                // same from our end and cancel the channel.
                key.channel().close();
                key.cancel();
                return;
            }
...

How to make sure that string is valid JSON using JSON.NET

Here is a TryParse extension method based on Habib's answer:

public static bool TryParse(this string strInput, out JToken output)
{
    if (String.IsNullOrWhiteSpace(strInput))
    {
        output = null;
        return false;
    }
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            output = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            //optional: LogError(jex);
            output = null;
            return false;
        }
        catch (Exception ex) //some other exception
        {
            //optional: LogError(ex);
            output = null;
            return false;
        }
    }
    else
    {
        output = null;
        return false;
    }
}

Usage:

JToken jToken;
if (strJson.TryParse(out jToken))
{
    // work with jToken
}
else
{
    // not valid json
}

Extension methods must be defined in a non-generic static class

A work-around for people who are experiencing a bug like Nathan:

The on-the-fly compiler seems to have a problem with this Extension Method error... adding static didn't help me either.

I'd like to know what causes the bug?

But the work-around is to write a new Extension class (not nested) even in same file and re-build.

Figured that this thread is getting enough views that it's worth passing on (the limited) solution I found. Most people probably tried adding 'static' before google-ing for a solution! and I didn't see this work-around fix anywhere else.

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

CodeIgniter - return only one row?

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Bash tool to get nth line from a file

The fastest solution for big files is always tail|head, provided that the two distances:

  • from the start of the file to the starting line. Lets call it S
  • the distance from the last line to the end of the file. Be it E

are known. Then, we could use this:

mycount="$E"; (( E > S )) && mycount="+$S"
howmany="$(( endline - startline + 1 ))"
tail -n "$mycount"| head -n "$howmany"

howmany is just the count of lines required.

Some more detail in https://unix.stackexchange.com/a/216614/79743

HTML text input allow only numeric input

Use this DOM

<input type='text' onkeypress='validate(event)' />

And this script

function validate(evt) {
  var theEvent = evt || window.event;

  // Handle paste
  if (theEvent.type === 'paste') {
      key = event.clipboardData.getData('text/plain');
  } else {
  // Handle key press
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode(key);
  }
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

Get encoding of a file in Windows

Looking for a Node.js/npm solution? Try encoding-checker:

npm install -g encoding-checker

Usage

Usage: encoding-checker [-p pattern] [-i encoding] [-v]
 
Options:
  --help                 Show help                                     [boolean]
  --version              Show version number                           [boolean]
  --pattern, -p, -d                                               [default: "*"]
  --ignore-encoding, -i                                            [default: ""]
  --verbose, -v                                                 [default: false]

Examples

Get encoding of all files in current directory:

encoding-checker

Return encoding of all md files in current directory:

encoding-checker -p "*.md"

Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):

encoding-checker -p "**"

For more examples refer to the npm docu or the official repository.

Android: why is there no maxHeight for a View?

Have you tried using the layout_weight value? If you set one it to a value greater than 0, it will stretch that view into the remaining space available.

If you had multiple views that needed to be stretched, then the value will become a weight between them.

So if you had two views both set to a layout_weight value of 1, then they would both stretch to fill in the space but they would both stretch to an equal amount of space. If you set one of them to the value of 2, then it would stretch twice as much as the other view.

Some more info here listed under Linear Layout.

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

The property 'value' does not exist on value of type 'HTMLElement'

A quick fix for this is use [ ] to select the attribute.

function greet(elementId) {
    var inputValue = document.getElementById(elementId)["value"];
    if(inputValue.trim() == "") {
        inputValue = "World";
    }
    document.getElementById("greet").innerText = greeter(inputValue);
}

I just try few methods and find out this solution,
I don't know what's the problem behind your original script.

For reference you may refer to Tomasz Nurkiewicz's post.

How to set Sqlite3 to be case insensitive when string comparing?

Another option that may or may not make sense in your case, is to actually have a separate column with pre-lowerscored values of your existing column. This can be populated using the SQLite function LOWER(), and you can then perform matching on this column instead.

Obviously, it adds redundancy and a potential for inconsistency, but if your data is static it might be a suitable option.

Vue 2 - Mutating props vue-warn

According to the VueJs 2.0, you should not mutate a prop inside the component. They are only mutated by their parents. Therefore, you should define variables in data with different names and keep them updated by watching actual props. In case the list prop is changed by a parent, you can parse it and assign it to mutableList. Here is a complete solution.

Vue.component('task', {
    template: ´<ul>
                  <li v-for="item in mutableList">
                      {{item.name}}
                  </li>
              </ul>´,
    props: ['list'],
    data: function () {
        return {
            mutableList = JSON.parse(this.list);
        }
    },
    watch:{
        list: function(){
            this.mutableList = JSON.parse(this.list);
        }
    }
});

It uses mutableList to render your template, thus you keep your list prop safe in the component.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

UIButton action in table view cell

Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

mysql is not recognised as an internal or external command,operable program or batch

In my case, it turned out to be a simple case of spacing.

Turns out, i had a space inserted after the last ; and before ""C:\Program Files\MySQL\MySQL Server 5.7" For this very simple reason, no matter what i did, MySql was still not being recognized.

Once i eliminated the spaces before and after path, it worked perfectly.

In retrospect, seems like a very obvious answer, but nobody's mentioned it anywhere.

Also, i'm new to this whole windows thing, so please excuse me if it sounds very simple.

What is the difference between parseInt() and Number()?

parseInt converts to a integer number, that is, it strips decimals. Number does not convert to integer.

Android studio doesn't list my phone under "Choose Device"

In my case, android studio selectively doesnt recognize my device for projects with COMPILE AND TARGET SDKVERSION 29 under the app level build.gradle.

I fixed this either by downloading 'sources for android 29' which comes up after clicking the 'show package details' under the sdk manager tab or by reducing the compile and targetsdkversions to 28

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

Calculate distance between 2 GPS coordinates

This is version from "Henry Vilinskiy" adapted for MySQL and Kilometers:

CREATE FUNCTION `CalculateDistanceInKm`(
  fromLatitude float,
  fromLongitude float,
  toLatitude float, 
  toLongitude float
) RETURNS float
BEGIN
  declare distance float;

  select 
    6367 * ACOS(
            round(
              COS(RADIANS(90-fromLatitude)) *
                COS(RADIANS(90-toLatitude)) +
                SIN(RADIANS(90-fromLatitude)) *
                SIN(RADIANS(90-toLatitude)) *
                COS(RADIANS(fromLongitude-toLongitude))
              ,15)
            )
    into distance;

  return  round(distance,3);
END;

How to serve up a JSON response using Go?

You can set your content-type header so clients know to expect json

w.Header().Set("Content-Type", "application/json")

Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Raise an error manually in T-SQL to jump to BEGIN CATCH block

you can use raiserror. Read more details here

--from MSDN

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

EDIT If you are using SQL Server 2012+ you can use throw clause. Here are the details.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I have tried this code and it works well for both null and empty situations :

'<%# (Eval("item")=="" || Eval("item")==null) ? "0" : Eval("item")%>'

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to import popper.js?

add popper**.js** as dependency instead of popper (only): see the difference in bold.

yarn add popper.js , instead of yarn add popper

it makes the difference.

and include the script according your needs:

as html or the library access as a dependency in SPA applications like react or angular

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Java, How do I get current index/key in "for each" loop

Keep track of your index: That's how it is done in Java:

 int index = 0;
    for (Element song: question){
        // Do whatever
         index++;
    }