Programs & Examples On #Xmlnode

XML document unit (element, entity, attribute, text, comment, notation, even document or it's fragment).

What's the difference between an element and a node in XML?

A Node is a part of the DOM tree, an Element is a particular type of Node

e.g. <foo> This is Text </foo>

You have a foo Element, (which is also a Node, as Element inherits from Node) and a Text Node 'This is Text', that is a child of the foo Element/Node

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
{
    book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");

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");

how to get the attribute value of an xml node using java

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

how to use DEXtoJar

Follow the below steps to do so_

  1. Rename your APK file(e.g., rename your APK file to .zip Ex- test.apk -> test.zip) & extract resultant zip file.
  2. Copy your .dex file in to dex2jar folder.
  3. Run setclasspath.bat. This should be run because this data is used in the next step.
  4. Go to Windows Command prompt, change the folder path to the path of your dex2jar folder and run the command as follows: d2j-dex2jar.bat classes.dex
  5. enjoy!! Your jar file will be ready in the same folder with name classes_dex2jar.jar.

Hope this helps you and All reading this... :)

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

How to emulate GPS location in the Android Emulator?

No one here mentioned the built in solution of the emulator itself, so for future visitors, I'd like to share it with visuals.

First, run your Android Emulator and click on the menu button (3 dots) shown below:

emulator with menu button

Then from the left pane, select Location and change the coordinates according to your needs. After pressing Send button, changes will immediately take effect (I recommend you to open up Google Maps for better understanding).

enter image description here

Android Studio Version: 2.3.3

In addition, to make your different locations coming to your application in real time, you can use GPX file. It's very easy to create this file from Google Map direction link:

  1. Go to google map, choose a location, then press "Directions" and enter the second location.
  2. After route is created, copy a link from the browser
  3. Go to this website: https://mapstogpx.com and paste the link to "Let's Go" box
  4. Press the "Let's Go" button and GPX file will be downloaded

Use "Load GPS/KML" button to load the created file to your emulator, choose speed, and press green play button on the bottom. Locations will be sent in real time as shown on the picture below.

enter image description here

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

Fast query runs slow in SSRS

I had the same scenario occuring..Very basic report, the SP (which only takes in 1 param) was taking 5 seconds to bring back 10K records, yet the report would take 6 minutes to run. According to profiler and the RS ExecutionLogStorage table, the report was spending all it's time on the query. Brian S.'s comment led me to the solution..I simply added WITH RECOMPILE before the AS statement in the SP, and now the report time pretty much matches the SP execution time.

CSS Font "Helvetica Neue"

It's a default font on Macs, but rare on PCs. Since it's not technically web-safe, some people may have it and some people may not. If you want to use a font like that, without using @font-face, you may want to write it out several different ways because it might not work the same for everyone.

I like using a font stack that touches on all bases like this:

font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", 
  Helvetica, Arial, "Lucida Grande", sans-serif;

This recommended font-family stack is further described in this CSS-Tricks snippet Better Helvetica which uses a font-weight: 300; as well.

Passing Multiple route params in Angular2

OK realized a mistake .. it has to be /:id/:id2

Anyway didn't find this in any tutorial or other StackOverflow question.

@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
    onClick(){
        this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
    }
}

Python - use list as function parameters

Use an asterisk:

some_func(*params)

How to change href attribute using JavaScript after opening the link in a new window?

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

Make div scrollable

use overflow:auto property, If overflow is clipped, a scroll-bar should be added to see the rest of the content,and mention the height

DEMO

 .itemconfiguration
    {
        height: 440px;
        width: 215px;
        overflow: auto;
        float: left;
        position: relative;
        margin-left: -5px;
    }

How to use filter, map, and reduce in Python 3

One of the advantages of map, filter and reduce is how legible they become when you "chain" them together to do something complex. However, the built-in syntax isn't legible and is all "backwards". So, I suggest using the PyFunctional package (https://pypi.org/project/PyFunctional/). Here's a comparison of the two:

flight_destinations_dict = {'NY': {'London', 'Rome'}, 'Berlin': {'NY'}}

PyFunctional version

Very legible syntax. You can say:

"I have a sequence of flight destinations. Out of which I want to get the dict key if city is in the dict values. Finally, filter out the empty lists I created in the process."

from functional import seq  # PyFunctional package to allow easier syntax

def find_return_flights_PYFUNCTIONAL_SYNTAX(city, flight_destinations_dict):
    return seq(flight_destinations_dict.items()) \
        .map(lambda x: x[0] if city in x[1] else []) \
        .filter(lambda x: x != []) \

Default Python version

It's all backwards. You need to say:

"OK, so, there's a list. I want to filter empty lists out of it. Why? Because I first got the dict key if the city was in the dict values. Oh, the list I'm doing this to is flight_destinations_dict."

def find_return_flights_DEFAULT_SYNTAX(city, flight_destinations_dict):
    return list(
        filter(lambda x: x != [],
               map(lambda x: x[0] if city in x[1] else [], flight_destinations_dict.items())
               )
    )

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Viewing local storage contents on IE

Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:

  • Open Dev tools (F12)
  • Go to Debugger tab
  • Click the folder icon to show a list of resources - opens in a separate tab

Dev tools screenshot

How to enumerate an object's properties in Python?

for one-liners:

print vars(theObject)

design a stack such that getMinimum( ) should be O(1)

Let's assume the stack which we will be working on is this :

6 , minvalue=2
2 , minvalue=2
5 , minvalue=3
3 , minvalue=3
9 , minvalue=7
7 , minvalue=7
8 , minvalue=8

In the above representation the stack is only built by left value's the right value's [minvalue] is written only for illustration purpose which will be stored in one variable.

The actual Problem is when the value which is the minimun value get's removed at that point how can we know what is the next minimum element without iterating over the stack.

Like for example in our stack when 6 get's popped we know that ,this is not the minimum element because the minimum element is 2 ,so we can safely remove this without updating our min value.

But when we pop 2 ,we can see that the minimum value is 2 right now and if this get's popped out then we need to update the minimum value to 3.

Point1:

Now if you observe carefully we need to generate minvalue=3 from this particular state [2 , minvalue=2]. or if you go depperin the stack we need to generate minvalue=7 from this particular state [3 , minvalue=3] or if you go more depper in the stack then we need to generate minvalue=8 from this particular state[7 , minvalue=7]

Did you notice something in common in all of the above 3 cases the value which we need to generate depends upon two variable which are both equal. Correct. Why is this happening because when we push some element smaller then the current minvalue, then we basically push that element in the stack and updated the same number in minvalue also.

Point2:

So we are basically storing duplicate of the same number once in stack and once in minvalue variable. We need to focus on avoiding this duplication and store something useful data in the stack or the minvalue to generate the previous minimum as shown in CASES above.

Let's focus on what should we store in stack when the value to store in push is less than the minmumvalue. Let's name this variable y , so now our stack will look something like this:

6 , minvalue=2
y1 , minvalue=2
5 , minvalue=3
y2 , minvalue=3
9 , minvalue=7
y3 , minvalue=7
8 , minvalue=8

I have renamed them as y1,y2,y3 to avoid confusion that all of them will have same value.

Point3:

Now Let's try to find some constraint's over y1,y2and y3. Do you remember when exactly we need to update the minvalue while doing pop() ,only when we have popped the element which is equal to the minvalue. If we pop something greater than the minvalue then we don't have to update minvalue. So to trigger the update of minvalue, y1,y2&y3 should be smaller than there corresponding minvalue .[We are avoding equality to avoid duplicate[Point2]] so the constrain is [ y < minValue ].

Now let's come back to populate y ,we need to generate some value and put y at the time of push ,remember. Let's take the value which is coming for push to be x which is less that the prevMinvalue,and the value which we will actually push in stack to be y. So one thing is obvious that the newMinValue=x , and y < newMinvalue.

Now we need to calulate y(remember y can be anynumber which is less than newMinValue(x) so we need to find some number which can fulfill our constraint) with the help of prevMinvalue and x(newMinvalue).

Let's do the math:
    x < prevMinvalue [Given]
    x - prevMinvalue < 0 
    x - prevMinValue + x < 0 + x [Add x on both side]
    2*x - prevMinValue < x      
this is the y which we were looking for less than x(newMinValue).
y = 2*x - prevMinValue. 'or' y = 2*newMinValue - prevMinValue 'or' y = 2*curMinValue - prevMinValue [taking curMinValue=newMinValue].

So at the time of pushing x if it is less than prevMinvalue then we push y[2*x-prevMinValue] and update newMinValue = x .

And at the time of pop if the stack contains something less than the minValue then that's our trigger to update the minVAlue. We have to calculate prevMinValue from the curMinValue and y. y = 2*curMinValue - prevMinValue [Proved] prevMinVAlue = 2*curMinvalue - y .

2*curMinValue - y is the number which we need to update now to the prevMinValue.

Code for the same logic is shared below with O(1) time and O(1) space complexity.

// C++ program to implement a stack that supports 
// getMinimum() in O(1) time and O(1) extra space. 
#include <bits/stdc++.h> 
using namespace std; 

// A user defined stack that supports getMin() in 
// addition to push() and pop() 
struct MyStack 
{ 
    stack<int> s; 
    int minEle; 

    // Prints minimum element of MyStack 
    void getMin() 
    { 
        if (s.empty()) 
            cout << "Stack is empty\n"; 

        // variable minEle stores the minimum element 
        // in the stack. 
        else
            cout <<"Minimum Element in the stack is: "
                 << minEle << "\n"; 
    } 

    // Prints top element of MyStack 
    void peek() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty "; 
            return; 
        } 

        int t = s.top(); // Top element. 

        cout << "Top Most Element is: "; 

        // If t < minEle means minEle stores 
        // value of t. 
        (t < minEle)? cout << minEle: cout << t; 
    } 

    // Remove the top element from MyStack 
    void pop() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty\n"; 
            return; 
        } 

        cout << "Top Most Element Removed: "; 
        int t = s.top(); 
        s.pop(); 

        // Minimum will change as the minimum element 
        // of the stack is being removed. 
        if (t < minEle) 
        { 
            cout << minEle << "\n"; 
            minEle = 2*minEle - t; 
        } 

        else
            cout << t << "\n"; 
    } 

    // Removes top element from MyStack 
    void push(int x) 
    { 
        // Insert new number into the stack 
        if (s.empty()) 
        { 
            minEle = x; 
            s.push(x); 
            cout <<  "Number Inserted: " << x << "\n"; 
            return; 
        } 

        // If new number is less than minEle 
        if (x < minEle) 
        { 
            s.push(2*x - minEle); 
            minEle = x; 
        } 

        else
           s.push(x); 

        cout <<  "Number Inserted: " << x << "\n"; 
    } 
}; 

// Driver Code 
int main() 
{ 
    MyStack s; 
    s.push(3); 
    s.push(5); 
    s.getMin(); 
    s.push(2); 
    s.push(1); 
    s.getMin(); 
    s.pop(); 
    s.getMin(); 
    s.pop(); 
    s.peek(); 

    return 0; 
} 

Prevent browser caching of AJAX call result

Maybe you should look at $.ajax() instead (if you are using jQuery, which it looks like). Take a look at: http://docs.jquery.com/Ajax/jQuery.ajax#options and the option "cache".

Another approach would be to look at how you cache things on the server side.

How to get the nth occurrence in a string?

Shorter way and I think easier, without creating unnecessary strings.

const findNthOccurence = (string, nth, char) => {
  let index = 0
  for (let i = 0; i < nth; i += 1) {
    if (index !== -1) index = string.indexOf(char, index + 1)
  }
  return index
}

How to launch an EXE from Web page (asp.net)

if the applications are C#, you can use ClickOnce deployment, which is a good option if you can't guarentee the user will have the app, however you'll have to re-build the apps with deployment options and grab some boilerplate code from each project.

You can also use Javascript.

Or you can register an application to handle a new web protocol you can define. This could also be an "app selection" protocol, so each time an app is clicked it would link to a page on your new protocol, all handling of this protocol is then passed to your "selection app" which uses arguments to find and launch an app on the clients PC.

HTH

joining two select statements

SELECT *
FROM
  (First_query) AS ONE
LEFT OUTER JOIN
  (Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.

@invertedSpear's comment in that answer worked in firefox but not in any IE version.

So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if (fo) {
    hasFlash = true;
  }
} catch (e) {
  if (navigator.mimeTypes
        && navigator.mimeTypes['application/x-shockwave-flash'] != undefined
        && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
    hasFlash = true;
  }
}

DB query builder toArray() laravel 4

Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).

In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.

In this case, it might be more efficient to do:

DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::table('user')->where('name',=,'Jhon')->get();

That way, you won't waste time creating objects and then converting them back into arrays.

How to get row count using ResultSet in Java?

Following two options worked for me:

1) A function that returns the number of rows in your ResultSet.

private int resultSetCount(ResultSet resultSet) throws SQLException{
    try{
        int i = 0;
        while (resultSet.next()) {
            i++;
        }
        return i;
    } catch (Exception e){
       System.out.println("Error getting row count");
       e.printStackTrace();
    }
    return 0;
}

2) Create a second SQL statement with the COUNT option.

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

Adding three months to a date in PHP

This answer is not exactly to this question. But I will add this since this question still searchable for how to add/deduct period from date.

$date = new DateTime('now');
$date->modify('+3 month'); // or you can use '-90 day' for deduct
$date = $date->format('Y-m-d h:i:s');
echo $date;

pretty-print JSON using JavaScript

Couldn't find any solution that had good syntax highlighting for the console, so here's my 2p

Install & Add cli-highlight dependency

npm install cli-highlight --save

Define logjson globally

const highlight = require('cli-highlight').highlight
console.logjson = (obj) => console.log(
                               highlight( JSON.stringify(obj, null, 4), 
                                          { language: 'json', ignoreIllegals: true } ));

Use

console.logjson({foo: "bar", someArray: ["string1", "string2"]});

output

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

how to add or embed CKEditor in php page

Alternately, it could also be done as:

<?php
    include("ckeditor/ckeditor.php");
    $CKeditor = new CKeditor();
    $CKeditor->BasePath = 'ckeditor/';
    $CKeditor->editor('editor1');
?>

Note that the last line is having 'editor1' as name, it could be changed as per your requirement.

SQL Query for Student mark functionality

SELECT          subjectname,
                studentname 
FROM            student s 
INNER JOIN      mark m 
  ON            s.studid = m.studid 
INNER JOIN      subject su 
  ON            su.subjectid = m.subjectid 
INNER JOIN (
  SELECT        subjectid,
                max(value) AS maximum 
  FROM          mark 
  GROUP BY      subjectid
)               highmark h 
  ON            h.subjectid = m.subjectid 
  AND           h.maximum = m.value;

How do I find the current executable filename?

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

Send multiple checkbox data to PHP via jQuery ajax()

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

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How to quietly remove a directory with content in PowerShell

If you want to concatenate a variable with a fixed path and a string as the dynamic path into a whole path to remove the folder, you may need the following command:

$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse

In the variable $newPath the concatenate path is now: "C:\Users\myUserName\Desktop\Folder\SubFolder"

So you can remove several directories from the starting point ("C:\Users\myUserName\Desktop"), which is already defined and fixed in the variable $fixPath.

$fixPath = "C:\Users\myUserName\Desktop"
Remote-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

The module was expected to contain an assembly manifest

Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

C/C++ switch case with string

Typically, you would use a hash table and function object, both available in Boost, TR1 and C++0x.

void func1() {
}
std::unordered_map<std::string, std::function<void()>> hash_map;
hash_map["Value1"] = &func1;
// .... etc
hash_map[mystring]();

This is a little more overhead at runtime but a bajillion times more maintainable. Hash tables offer O(1) insertion, lookup, and etc, which makes them the same complexity as the assembly-style jump-table.

How to hide close button in WPF window?

Try adding a Closing event to the window. Add this code to the event handler.

e.Cancel = true;

This will prevent the window from closing. This has the same effect as hiding the close button.

Correct way to detach from a container without stopping it

The default way to detach from an interactive container is Ctrl+P Ctrl+Q, but you can override it when running a new container or attaching to existing container using the --detach-keys flag.

recursively use scp but excluding some folders

You can use extended globbing as in the example below:

#Enable extglob
shopt -s extglob

cp -rv !(./excludeme/*.jpg) /var/destination

How to convert Map keys to array?

OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:

The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

As you mentioned, you can easily create an instance of Map using new keyword... In your case:

let myMap = new Map().set('a', 1).set('b', 2);

So let's see...

The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...

Map has many methods which you can use, like set() which you already used to assign the key values...

One of them is keys() which returns all the keys...

In your case, it will return:

MapIterator {"a", "b"}

and you easily convert them to an Array using ES6 ways, like spread operator...

const b = [...myMap.keys()];

How do I get the file extension of a file in Java?

private String getFileExtension(File file) {
    String name = file.getName();
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf);
}

Get name of currently executing test in JUnit 4

Try this instead:

public class MyTest {
        @Rule
        public TestName testName = new TestName();

        @Rule
        public TestWatcher testWatcher = new TestWatcher() {
            @Override
            protected void starting(final Description description) {
                String methodName = description.getMethodName();
                String className = description.getClassName();
                className = className.substring(className.lastIndexOf('.') + 1);
                System.err.println("Starting JUnit-test: " + className + " " + methodName);
            }
        };

        @Test
        public void testA() {
                assertEquals("testA", testName.getMethodName());
        }

        @Test
        public void testB() {
                assertEquals("testB", testName.getMethodName());
        }
}

The output looks like this:

Starting JUnit-test: MyTest testA
Starting JUnit-test: MyTest testB

NOTE: This DOES NOT work if your test is a subclass of TestCase! The test runs but the @Rule code just never runs.

Core Data: Quickest way to delete all instances of an entity

In Swift 3.0

 func deleteAllRecords() {
        //delete all data
        let context = appDelegate.persistentContainer.viewContext

        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "YourClassName")
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

        do {
            try context.execute(deleteRequest)
            try context.save()
        } catch {
            print ("There was an error")
        }
    }

Conversion of System.Array to List

You can do like this basically:

int[] ints = new[] { 10, 20, 10, 34, 113 };

this is your array, and than you can call your new list like this:

 var newList = new List<int>(ints);

You can do this for complex object too.

What is the purpose of using WHERE 1=1 in SQL statements?

Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail.

It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

Set width to match constraints in ConstraintLayout

match_parent is not supported by ConstraintLayout. Set width to 0dp to let it match constraints.

Java SSLException: hostname in certificate didn't match

The concern is we should not use ALLOW_ALL_HOSTNAME_VERIFIER.

How about I implement my own hostname verifier?

class MyHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier
{
    @Override
    public boolean verify(String host, SSLSession session) {
        String sslHost = session.getPeerHost();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void verify(String host, SSLSocket ssl) throws IOException {
        String sslHost = ssl.getInetAddress().getHostName();
        System.out.println("Host=" + host);
        System.out.println("SSL Host=" + sslHost);    
        if (host.equals(sslHost)) {
            return;
        } else {
            throw new IOException("hostname in certificate didn't match: " + host + " != " + sslHost);
        }
    }

    @Override
    public void verify(String host, X509Certificate cert) throws SSLException {
        throw new SSLException("Hostname verification 1 not implemented");
    }

    @Override
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        throw new SSLException("Hostname verification 2 not implemented");
    }
}

Let's test against https://www.rideforrainbows.org/ which is hosted on a shared server.

public static void main (String[] args) throws Exception {
    //org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    //sf.setHostnameVerifier(new MyHostnameVerifier());
    //org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);

    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    //client.getConnectionManager().getSchemeRegistry().register(sch);
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

SSLException:

Exception in thread "main" javax.net.ssl.SSLException: hostname in certificate didn't match: www.rideforrainbows.org != stac.rt.sg OR stac.rt.sg OR www.stac.rt.sg
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:231)
...

Do with MyHostnameVerifier:

public static void main (String[] args) throws Exception {
    org.apache.http.conn.ssl.SSLSocketFactory sf = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
    sf.setHostnameVerifier(new MyHostnameVerifier());
    org.apache.http.conn.scheme.Scheme sch = new Scheme("https", 443, sf);

    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(sch);
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

Shows:

Host=www.rideforrainbows.org
SSL Host=www.rideforrainbows.org

At least I have the logic to compare (Host == SSL Host) and return true.

The above source code is working for httpclient-4.2.3.jar and httpclient-4.3.3.jar.

Android Studio gradle takes too long to build

Check disk usage in Windows OS ...

The problem can be related to this, in my case I had Windows 8 OS consuming a 100% disk usage.

Especially the Windows Search service, can be the most consuming. Disable it with:

cmd (Admin)

net.exe stop "Windows search"

Check this link 4 Tips to Fix 100% Disk Usage & Improve Windows Performance

"Could not find acceptable representation" using spring-boot-starter-web

If using @FeignClient, add e.g.

produces = "application/json"

to the @RequestMapping annotation

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Kill the previous instance of tomcat or the process that's running on 8080.

Go to terminal and do this:

lsof -i :8080

The output will be something like:

COMMAND   PID   USER      FD   TYPE  DEVICE SIZE/OFF NODE NAME
java    76746   YourName  57u  IPv6 0xd2a83c9c1e75      0t0    TCP *:http-alt (LISTEN)

Kill this process using it's PID:

kill 76746

Vue JS mounted()

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

Programmatically select a row in JTable

You use the available API of JTable and do not try to mess with the colors.

Some selection methods are available directly on the JTable (like the setRowSelectionInterval). If you want to have access to all selection-related logic, the selection model is the place to start looking

Angularjs loading screen on ajax request

Use angular-busy:

Add cgBusy as to your app / module:

angular.module('your_app', ['cgBusy']);

Add your promise to scope:

function MyCtrl($http, User) {
  //using $http
  this.isBusy = $http.get('...');
  //if you have a User class based on $resource
  this.isBusy = User.$save();
}

In your html template:

<div cg-busy="$ctrl.isBusy"></div>

How can I find the location of origin/master in git, and how do I change it?

1. Find out where Git thinks 'origin/master' is using git-remote

git remote show origin

..which will return something like..

* remote origin
  URL: [email protected]:~/something.git
  Remote branch merged with 'git pull' while on branch master
    master
  Tracked remote branch
    master

A remote is basically a link to a remote repository. When you do..

git remote add unfuddle [email protected]/myrepo.git
git push unfuddle

..git will push changes to that address you added. It's like a bookmark, for remote repositories.

When you run git status, it checks if the remote is missing commits (compared to your local repository), and if so, by how many commits. If you push all your changes to "origin", both will be in sync, so you wont get that message.

2. If it's somewhere else, how do I turn my laptop into the 'origin/master'?

There is no point in doing this. Say "origin" is renamed to "laptop" - you never want to do git push laptop from your laptop.

If you want to remove the origin remote, you do..

git remote rm origin

This wont delete anything (in terms of file-content/revisions-history). This will stop the "your branch is ahead by.." message, as it will no longer compare your repository with the remote (because it's gone!)

One thing to remember is that there is nothing special about origin, it's just a default name git uses.

Git does use origin by default when you do things like git push or git pull. So, if you have a remote you use a lot (Unfuddle, in your case), I would recommend adding unfuddle as "origin":

git remote rm origin
git remote add origin [email protected]:subdomain/abbreviation.git

or do the above in one command using set-url:

git remote set-url origin [email protected]:subdomain/abbreviation.git

Then you can simply do git push or git pull to update, instead of git push unfuddle master

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

If you not want include other function like 'ReDimPreserve' could use temporal matrix for resizing. On based to your code:

 Dim n As Integer, m As Integer, i as Long, j as Long
 Dim arrTemporal() as Variant

    n = 1
    m = 0
    Dim arrCity() As String
    ReDim arrCity(n, m)

    n = n + 1
    m = m + 1

    'VBA automatically adapts the size of the receiving matrix.
    arrTemporal = arrCity
    ReDim arrCity(n, m)

    'Loop for assign values to arrCity
    For i = 1 To UBound(arrTemporal , 1)
        For j = 1 To UBound(arrTemporal , 2)
            arrCity(i, j) = arrTemporal (i, j)
        Next
    Next

If you not declare of type VBA assume that is Variant.

Dim n as Integer, m As Integer

Efficiency of Java "Double Brace Initialization"?

I was researching this and decided to do a more in depth test than the one provided by the valid answer.

Here is the code: https://gist.github.com/4368924

and this is my conclusion

I was surprised to find that in most of the run tests the internal initiation was actually faster (almost double in some cases). When working with large numbers the benefit seems to fade away.

Interestingly, the case that creates 3 objects on the loop loses it's benefit rans out sooner than on the other cases. I am not sure why this is happening and more testing should be done to reach any conclusions. Creating concrete implementations may help to avoid the class definition to be reloaded (if that's what's happening)

However, it is clear that not much overhead it observed in most cases for the single item building, even with large numbers.

One set back would be the fact that each of the double brace initiations creates a new class file that adds a whole disk block to the size of our application (or about 1k when compressed). A small footprint, but if it's used in many places it could potentially have an impact. Use this 1000 times and you are potentially adding a whole MiB to you applicaiton, which may be concerning on an embedded environment.

My conclusion? It can be ok to use as long as it is not abused.

Let me know what you think :)

How to take last four characters from a varchar?

SUBSTR(column, LENGTH(column) - 3, 4)

LENGTH returns length of string and SUBSTR returns 4 characters from "the position length - 4"

utf-8 special characters not displaying

The problem is because your file are not with the same encoding. First run the following command in all your files:

file -i filename.* 

In order to fix the problem you have to change all your files to uft-8. You can do it with the command iconv:

iconv -f fromcode -t tocode filename > newfilename

Example:

iconv -f iso-8859-1 -t utf-8 index.html > fixed/index.html

After this you can run file -i fixedx/index.html and you will see that your file is now in uft-8

Resize UIImage by keeping Aspect ratio and width

Programmatically:

imageView.contentMode = UIViewContentModeScaleAspectFit;

Storyboard:

enter image description here

SQL 'like' vs '=' performance

It's a measureable difference.

Run the following:

Create Table #TempTester (id int, col1 varchar(20), value varchar(20))
go

INSERT INTO #TempTester (id, col1, value)
VALUES
(1, 'this is #1', 'abcdefghij')
GO

INSERT INTO #TempTester (id, col1, value)
VALUES
(2, 'this is #2', 'foob'),
(3, 'this is #3', 'abdefghic'),
(4, 'this is #4', 'other'),
(5, 'this is #5', 'zyx'),
(6, 'this is #6', 'zyx'),
(7, 'this is #7', 'zyx'),
(8, 'this is #8', 'klm'),
(9, 'this is #9', 'klm'),
(10, 'this is #10', 'zyx')
GO 10000

CREATE CLUSTERED INDEX ixId ON #TempTester(id)CREATE CLUSTERED INDEX ixId ON #TempTester(id)

CREATE NONCLUSTERED INDEX ixTesting ON #TempTester(value)

Then:

SET SHOWPLAN_XML ON

Then:

SELECT * FROM #TempTester WHERE value LIKE 'abc%'

SELECT * FROM #TempTester WHERE value = 'abcdefghij'

The resulting execution plan shows you that the cost of the first operation, the LIKE comparison, is about 10 times more expensive than the = comparison.

If you can use an = comparison, please do so.

How to write and save html file in python?

You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write():

html_str = """
<table border=1>
     <tr>
       <th>Number</th>
       <th>Square</th>
     </tr>
     <indent>
     <% for i in range(10): %>
       <tr>
         <td><%= i %></td>
         <td><%= i**2 %></td>
       </tr>
     </indent>
</table>
"""

Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()

Javascript split regex question

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());

jQuery - on change input text

Try this,

$('#kat').on('input',function(e){
 alert('Hello')
});

POST data with request module on Node.JS

If you're posting a json body, dont use the form parameter. Using form will make the arrays into field[0].attribute, field[1].attribute etc. Instead use body like so.

var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
request.post({
    url: 'https://api.site.com',
    body: jsonDataObj,
    json: true
  }, function(error, response, body){
  console.log(body);
});

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

For Linux users who can't use Microsoft Credential Manager. This is the only solution I found aside from using ssh. You need to generate the credentials in the repository view (See images below) get git credentials

And the result is: get Git credentials result

Copy the password!. Azure devops doesn't store it and you won't be able to see it again!

NB: As of 2020 Alternate credentials have been disabled check Microsoft blog

Automatically size JPanel inside JFrame

From my experience, I used GridLayout.

    thePanel.setLayout(new GridLayout(a,b,c,d));

a = row number, b = column number, c = horizontal gap, d = vertical gap.


For example, if I want to create panel with:

  • unlimited row (set a = 0)
  • 1 column (set b = 1)
  • vertical gap= 3 (set d = 3)

The code is below:

    thePanel.setLayout(new GridLayout(0,1,0,3));

This method is useful when you want to add JScrollPane to your JPanel. Size of the JPanel inside JScrollPane will automatically changes when you add some components on it, so the JScrollPane will automatically reset the scroll bar.

How set the android:gravity to TextView from Java side in Android

We can set layout gravity on any view like below way-

myView = findViewById(R.id.myView);
myView.setGravity(Gravity.CENTER_VERTICAL|Gravity.RIGHT);
 or
myView.setGravity(Gravity.BOTTOM);

This is equilent to below xml code

<...
 android:gravity="center_vertical|right"
 ...
 .../>

How to remove backslash on json_encode() function?

Simpler way would be

$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);

Execute Shell Script after post build in Jenkins

You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.

if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
  lastStableBuild = item.getLastStableBuild()
  lastStableDate = lastStableBuild.getTime()
  formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
  now = new Date()
  formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
  command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
  manager.listener.logger.println "FOB Command: ${command}"
  manager.listener.logger.println command.execute().text
}

(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)

how to print json data in console.log

Object

input_data: Object price-row_122: " 35.1 " quantity-row_122: "1" success: true

When should I use curly braces for ES6 import?

Summary ES6 modules:

Exports:

You have two types of exports:

  1. Named exports
  2. Default exports, a maximum one per module

Syntax:

// Module A
export const importantData_1 = 1;
export const importantData_2 = 2;
export default function foo () {}

Imports:

The type of export (i.e., named or default exports) affects how to import something:

  1. For a named export we have to use curly braces and the exact name as the declaration (i.e. variable, function, or class) which was exported.
  2. For a default export we can choose the name.

Syntax:

// Module B, imports from module A which is located in the same directory

import { importantData_1 , importantData_2  } from './A';  // For our named imports

// Syntax single named import:
// import { importantData_1 }

// For our default export (foo), the name choice is arbitrary
import ourFunction from './A';

Things of interest:

  1. Use a comma-separated list within curly braces with the matching name of the export for named export.
  2. Use a name of your choosing without curly braces for a default export.

Aliases:

Whenever you want to rename a named import this is possible via aliases. The syntax for this is the following:

import { importantData_1 as myData } from './A';

Now we have imported importantData_1, but the identifier is myData instead of importantData_1.

Get querystring from URL using jQuery

From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

This is what you need :)

The following code will return a JavaScript Object containing the URL parameters:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

For example, if you have the URL:

http://www.example.com/?me=myValue&name2=SomeOtherValue

This code will return:

{
    "me"    : "myValue",
    "name2" : "SomeOtherValue"
}

and you can do:

var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];

Using Java to pull data from a webpage?

Here's my solution using URL and try with resources phrase to catch the exceptions.

/**
 * Created by mona on 5/27/16.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadFromWeb {
    public static void readFromWeb(String webURL) throws IOException {
        URL url = new URL(webURL);
        InputStream is =  url.openStream();
        try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            throw new MalformedURLException("URL is malformed!!");
        }
        catch (IOException e) {
            e.printStackTrace();
            throw new IOException();
        }

    }
    public static void main(String[] args) throws IOException {
        String url = "https://madison.craigslist.org/search/sub";
        readFromWeb(url);
    }

}

You could additionally save it to file based on your needs or parse it using XML or HTML libraries.

long long int vs. long int vs. int64_t in C++

So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?

This is a good question or problem, but I suspect the answer is NO.

Also, a long int may not be a long long int.


# if __WORDSIZE == 64
typedef long int  int64_t;
# else
__extension__
typedef long long int  int64_t;
# endif

I believe this is libc. I suspect you want to go deeper.

In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:

int:           0
int64_t:       1
long int:      0
long long int: 1

32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long.

Microsoft documents the ranges at Data Type Ranges. The say the long long is equivalent to __int64.

However, the program resulting from a 64-bit GCC compile will output:

int:           0
int64_t:       1
long int:      1
long long int: 0

64-bit Linux uses the LP64 data model. Longs are 64-bit and long long are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64.

There's a ILP64 data model where everything is 64-bit. You have to do some extra work to get a definition for your word32 type. Also see papers like 64-Bit Programming Models: Why LP64?


But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...

Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive:

#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif

// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);

// Try it:
word64 val;
int res = rdrand64_step(&val);

It results in:

error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'

So, ignore LP64 and change it to:

typedef unsigned long long word64;

Then, wander over to a 64-bit ARM IoT gadget that defines LP64 and use NEON:

error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

How can I stop float left?

Just add overflow:hidden in the first div style. That should be enough.

Editing dictionary values in a foreach loop

You can't modify the keys nor the values directly in a ForEach, but you can modify their members. E.g., this should work:

public class State {
    public int Value;
}

...

Dictionary<string, State> colStates = new Dictionary<string,State>();

int OtherCount = 0;
foreach(string key in colStates.Keys)
{
    double  Percent = colStates[key].Value / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key].Value;
        colStates[key].Value = 0;
    }
}

colStates.Add("Other", new State { Value =  OtherCount } );

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Best shown by example. String. 192.168.1.1 and a greedy regex \b.+\b You might think this would give you the 1st octet but is actually matches against the whole string. Why? Because the.+ is greedy and a greedy match matches every character in 192.168.1.1 until it reaches the end of the string. This is the important bit! Now it starts to backtrack one character at a time until it finds a match for the 3rd token (\b).

If the string a 4GB text file and 192.168.1.1 was at the start you could easily see how this backtracking would cause an issue.

To make a regex non greedy (lazy) put a question mark after your greedy search e.g

*?
??
+?

What happens now is token 2 (+?) finds a match, regex moves along a character and then tries the next token (\b) rather than token 2 (+?). So it creeps along gingerly.

Filtering collections in C#

If your list is very big and you are filtering repeatedly - you can sort the original list on the filter attribute, binary search to find the start and end points.

Initial time O(n*log(n)) then O(log(n)).

Standard filtering will take O(n) each time.

How to set a background image in Xcode using swift?

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

How to override equals method in Java

@Override
public boolean equals(Object that){
  if(this == that) return true;//if both of them points the same address in memory

  if(!(that instanceof People)) return false; // if "that" is not a People or a childclass

  People thatPeople = (People)that; // than we can cast it to People safely

  return this.name.equals(thatPeople.name) && this.age == thatPeople.age;// if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
}

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div

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

GridView Hide Column by code

This helped for me

this.myGridview.Columns[0].Visible = false;

Here 0 is the column index i want to hide.

How to throw std::exceptions with variable messages?

Use string literal operator if C++14 (operator ""s)

using namespace std::string_literals;

throw std::exception("Could not load config file '"s + configfile + "'"s);

or define your own if in C++11. For instance

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, str + len);
}

Your throw statement will then look like this

throw std::exception("Could not load config file '"_s + configfile + "'"_s);

which looks nice and clean.

How to 'insert if not exists' in MySQL?

Solution:

INSERT INTO `table` (`value1`, `value2`) 
SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
WHERE NOT EXISTS (SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1) 

Explanation:

The innermost query

SELECT * FROM `table` 
      WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

used as the WHERE NOT EXISTS-condition detects if there already exists a row with the data to be inserted. After one row of this kind is found, the query may stop, hence the LIMIT 1 (micro-optimization, may be omitted).

The intermediate query

SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

represents the values to be inserted. DUAL refers to a special one row, one column table present by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On a MySQL-Server version 5.7.26 I got a valid query when omitting FROM DUAL, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS the intermediate query returns an empty result set if the innermost query found matching data.

The outer query

INSERT INTO `table` (`value1`, `value2`) 

inserts the data, if any is returned by the intermediate query.

Windows command for file size only

C:\>FORFILES  /C "cmd /c echo @fname @fsize"


C:\>FORFILES  /?

FORFILES [/P pathname] [/M searchmask] [/S]
         [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]

Description:
    Selects a file (or set of files) and executes a
    command on that file. This is helpful for batch jobs.

Parameter List:
    /P    pathname      Indicates the path to start searching.
                        The default folder is the current working
                        directory (.).

Releasing memory in Python

eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:

Why does it release 50.5mb in particular - what is the amount that is released based on?

What it's based on is, ultimately, a whole series of coincidences inside Python and malloc that are very hard to predict.

First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.

Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE, etc.

If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk or equivalent to shrink the data segment (very rare nowadays), or you've used munmap or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED for a MADV_FREE segment that you immediately unmap.)

But most programs don't directly allocate things out of memory pages; they use a malloc-style allocator. When you call free, the allocator can only release pages to the OS if you just happen to be freeing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.

CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.

So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString object, and the string buffer).

If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)

If you do deallocate a block of object storage, to know whether this causes a free call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloced region, and even then, it may not happen.)

If you do free a malloced region, to know whether this causes an munmap or equivalent (or brk), you have to know the internal state of the malloc, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc within an mmap segment, and even then, it may not happen.)

So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc unmap 50.5mb worth of pages when you did those one or more free calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.

So, the only useful answer to the question is "Because."

Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.

And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).

Convert all data frame character columns to factors

The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}

How npm start runs a server on port 8000

You can change the port in the console by running the following on Windows:

SET PORT=8000

For Mac, Linux or Windows WSL use the following:

export PORT=8000

The export sets the environment variable for the current shell and all child processes like npm that might use it.

If you want the environment variable to be set just for the npm process, precede the command with the environment variable like this (on Mac and Linux and Windows WSL):

PORT=8000 npm run start

How can I indent multiple lines in Xcode?

Danish Keyboard

Unindent: ? + ? + 8

Indent: ? + ? + 9

Switch php versions on commandline ubuntu 16.04

When installing laravel on Ubuntu 18.04, be default PHP 7.3.0RC3 install selected, but laravel and symfony will not install properly complaining about missin php-xml and php-zip, even though they are installed. You need to switch to php 7.1, using the instructions above or,

 sudo update-alternatives --set php /usr/bin/php7.1

now, running laravel new blog, will proceed correctly

Easier way to create circle div than using an image?

You can try the radial-gradient CSS function:

.circle {
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: #ffffff; /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, #ffffff 17%, #ff0a0a 19%, #ff2828 40%, #000000 41%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
}

Apply it to a div layer:

<div class="circle"></div>

Remove warning messages in PHP

Not exactly answering the question, but I think this is a better compromise in some situations:

I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was - a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:

printf('<div style="display:none">');
    ...Third-party stuff here...
printf('</div>');

Warning was still in page source as a reminder to me, but invisible to the client.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Convert a dataframe to a vector (by rows)

c(df$x, df$y)
# returns: 26 21 20 34 29 28

if the particular order is important then:

M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28 

Or more generally:

m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
  q = c(q, m[i,])
}

# returns 26 34 21 29 20 28

How to get a cross-origin resource sharing (CORS) post request working

If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…

For example in one <VirtualHost> that uses SSL add the two following directives:

SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth

Make sure the following apache modules are loaded (load them using a2enmod):

  • proxy
  • proxy_connect
  • proxy_http

Obviously you'll have to change your AJAX requests url in order to use the apache proxy…

Using GPU from a docker container?

Recent enhancements by NVIDIA have produced a much more robust way to do this.

Essentially they have found a way to avoid the need to install the CUDA/GPU driver inside the containers and have it match the host kernel module.

Instead, drivers are on the host and the containers don't need them. It requires a modified docker-cli right now.

This is great, because now containers are much more portable.

enter image description here

A quick test on Ubuntu:

# Install nvidia-docker and nvidia-docker-plugin
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb

# Test nvidia-smi
nvidia-docker run --rm nvidia/cuda nvidia-smi

For more details see: GPU-Enabled Docker Container and: https://github.com/NVIDIA/nvidia-docker

How to center an image horizontally and align it to the bottom of the container?

#header2
{
   display: table-cell;
   vertical-align: bottom;
   background-color:Red;
}


<div style="text-align:center; height:300px; width:50%;" id="header2">
<div class="right" id="header-content2">
  <p>this is a test</p>
</div>
</div>

Counting words in string

For those who want to use Lodash can use the _.words function:

_x000D_
_x000D_
var str = "Random String";_x000D_
var wordCount = _.size(_.words(str));_x000D_
console.log(wordCount);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

GitHub "fatal: remote origin already exists"

for using git you have to be

root

if not then use sudo

for removing origin :

git remote remove origin

for adding origin :

git remote add origin http://giturl

Understanding Python super() with __init__() methods

Super has no side effects

Base = ChildB

Base()

works as expected

Base = ChildA

Base()

gets into infinite recursion.

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

Spring Boot and multiple external configuration files

A modified version of @mxsb solution that allows us to define multiple files and in my case these are yml files.

In my application-dev.yml, I added this config that allows me to inject all the yml that have -dev.yml in them. This can be a list of specific files also. "classpath:/test/test.yml,classpath:/test2/test.yml"

application:
  properties:
    locations: "classpath*:/**/*-dev.yml"

This helps to get a properties map.

@Configuration

public class PropertiesConfig {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

@Value("${application.properties.locations}")
private String[] locations;

@Autowired
private ResourceLoader rl;

@Bean
Map<String, Properties> myProperties() {
    return stream(locations)
            .collect(toMap(filename -> filename, this::loadProperties));
}

private Properties loadProperties(final String filename) {

    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .forEach(propertySource -> {
                    Map source = ((MapPropertySource) propertySource).getSource();
                    properties.putAll(source);
                });

        return properties;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
}

However, if like in my case, I wanted to have to split yml files for each profile and load them and inject that directly into spring configuration before beans initialisation.

config
    - application.yml
    - application-dev.yml
    - application-prod.yml
management
    - management-dev.yml
    - management-prod.yml

... you get the idea

The component is slightly different

@Component
public class PropertiesConfigurer extends     PropertySourcesPlaceholderConfigurer
    implements EnvironmentAware, InitializingBean {

private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfigurer.class);

private String[] locations;

@Autowired
private ResourceLoader rl;
private Environment environment;

@Override
public void setEnvironment(Environment environment) {
    // save off Environment for later use
    this.environment = environment;
    super.setEnvironment(environment);
}

@Override
public void afterPropertiesSet() throws Exception {
    // Copy property sources to Environment
    MutablePropertySources envPropSources = ((ConfigurableEnvironment) environment).getPropertySources();
    envPropSources.forEach(propertySource -> {
        if (propertySource.containsProperty("application.properties.locations")) {
            locations = ((String) propertySource.getProperty("application.properties.locations")).split(",");
            stream(locations).forEach(filename -> loadProperties(filename).forEach(source ->{
                envPropSources.addFirst(source);
            }));
        }
    });
}


private List<PropertySource> loadProperties(final String filename) {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    try {
        final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
        final Properties properties = new Properties();
        return stream(possiblePropertiesResources)
                .filter(Resource::exists)
                .map(resource1 -> {
                    try {
                        return loader.load(resource1.getFilename(), resource1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).flatMap(l -> l.stream())
                .collect(Collectors.toList());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

}

SQL Server: Difference between PARTITION BY and GROUP BY

partition by doesn't actually roll up the data. It allows you to reset something on a per group basis. For example, you can get an ordinal column within a group by partitioning on the grouping field and using rownum() over the rows within that group. This gives you something that behaves a bit like an identity column that resets at the beginning of each group.

How do I change the text of a span element using JavaScript?

document.getElementById('myspan').innerHTML = 'newtext';

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

Matplotlib discrete colorbar

To set a values above or below the range of the colormap, you'll want to use the set_over and set_under methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the set_bad method. (Have a look at the documentation for the base colormap class: http://matplotlib.org/api/colors_api.html#matplotlib.colors.Colormap )

It sounds like you want something like this:

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x, y, z = np.random.random((3, 30))
z = z * 20 + 0.1

# Set some values in z to 0...
z[:5] = 0

cmap = plt.get_cmap('jet', 20)
cmap.set_under('gray')

fig, ax = plt.subplots()
cax = ax.scatter(x, y, c=z, s=100, cmap=cmap, vmin=0.1, vmax=z.max())
fig.colorbar(cax, extend='min')

plt.show()

enter image description here

Full Screen Theme for AppCompat

You can follow below step:-

AndoridMenifest.xml

<activity
            android:name=".ui.FullImageActivity"
            android:label="@string/title_activity_main"
            android:screenOrientation="landscape"
            android:theme="@style/DialogTheme">
        </activity>

Style.xml

<style name="DialogTheme" parent="android:Theme.Dialog">

    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">fill_parent</item>

   <!-- No backgrounds, titles or window float -->
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

FullImageActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    setContentView(R.layout.image_view);
     }

I hope it will help..Thanks!!

concatenate char array in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

Trigger standard HTML5 validation (form) without using submit button?

As stated in the other answers use event.preventDefault() to prevent form submitting.

To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)

(function( $ ){
    $.fn.isValid = function() {
        return document.getElementById(this[0].id).checkValidity();
    };
})( jQuery );

example usage

 $('#submitBtn').click( function(e){

        if ($('#registerForm').isValid()){
            // do the request
        } else {
            e.preventDefault();
        }
    });

Side-by-side plots with ggplot2

Yes, methinks you need to arrange your data appropriately. One way would be this:

X <- data.frame(x=rep(x,2),
                y=c(3*x+eps, 2*x+eps),
                case=rep(c("first","second"), each=100))

qplot(x, y, data=X, facets = . ~ case) + geom_smooth()

I am sure there are better tricks in plyr or reshape -- I am still not really up to speed on all these powerful packages by Hadley.

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)

PHP-FPM and Nginx: 502 Bad Gateway

In your NGINX vhost file, in location block which processes your PHP files (usually location ~ \.php$ {) through FastCGI, make sure you have next lines:

proxy_buffer_size          128k;
proxy_buffers              4 256k;
proxy_busy_buffers_size    256k;
fastcgi_buffer_size        16k;
fastcgi_buffers            4 16k;

After that don't forget to restart fpm and nginx.


Additional:

NGINX vhost paths

  • /etc/nginx/sites-enabled/ - Linux
  • '/usr/local/etc/nginx/sites-enabled/' - Mac

Restart NGINX:

  • sudo service nginx restart - Linux
  • brew service restart nginx - Mac

Restart FPM:

Determine fpm process name: - systemctl list-unit-files | grep fpm - Linux - brew services list | grep php - Mac

and then restart it with:

  • sudo service <service-name> restart - Linux
  • brew services restart <service-name> - Mac

Behaviour of increment and decrement operators in Python

In python 3.8+ you can do :

(a:=a+1) #same as ++a (increment, then return new value)
(a:=a+1)-1 #same as a++ (return the incremented value -1) (useless)

You can do a lot of thinks with this.

>>> a = 0
>>> while (a:=a+1) < 5:
    print(a)

    
1
2
3
4

Or if you want write somthing with more sophisticated syntaxe (the goal is not optimization):

>>> del a
>>> while (a := (a if 'a' in locals() else 0) + 1) < 5:
    print(a)

    
1
2
3
4

It will return 0 even if 'a' doesn't exist without errors, and then will set it to 1

invalid command code ., despite escaping periods, using sed

If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly and giving '' as argument to -i:

find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;

See this.

How do I resolve "Run-time error '429': ActiveX component can't create object"?

This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.

http://www.microsoft.com/en-ca/download/details.aspx?id=13255

QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"

In Subversion can I be a user other than my login name?

I believe if you use the file:// method to access your subversion repository, your changes are always performed under the user which accesses the repository. You need to use a method that supports authentication such as http:// or svn://.

See http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.serverconfig.choosing

Why can't I center with margin: 0 auto?

You need to define the width of the element you are centering, not the parent element.

#header ul {
    margin: 0 auto;
    width: 90%;
}

Edit: Ok, I've seen the testpage now, and here is how I think you want it:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

Git - Ignore node_modules folder everywhere

Create .gitignore file in root folder directly by code editor or by command

For Mac & Linux

 touch .gitignore 

For Windows

 echo >.gitignore 

open .gitignore declare folder or file name like this /foldername

How to revert multiple git commits?

Clean way which I found useful

git revert --no-commit HEAD~3..

This command reverts last 3 commits with only one commit.

Also doesn't rewrite history.

The .. helps create a range. Meaning HEAD~3.. is the same as HEAD~3..HEAD

Maintain the aspect ratio of a div with CSS

New in Chrome 88 and soon to follow in other browsers is the new CSS aspect-ratio property.

The aspect-ratio CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.

CSS Tricks Article

More Information

_x000D_
_x000D_
div {
  background: rebeccapurple;
  height:100px;
  margin:1em auto;
}

.square {
  aspect-ratio: 1 / 1;
  }
_x000D_
<div class="square">
  
</div>
_x000D_
_x000D_
_x000D_

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

How do I get an apk file from an Android device?

Try this one liner bash command to backup all your apps:

for package in $(adb shell pm list packages -3 | tr -d '\r' | sed 's/package://g'); do apk=$(adb shell pm path $package | tr -d '\r' | sed 's/package://g'); echo "Pulling $apk"; adb pull -p $apk "$package".apk; done

This command is derived from Firelord's script. I just renamed all apks to their package names for solving the issue with elcuco's script, i.e the same base.apk file getting overwritten on Android 6.0 "Marshmallow" and above.

Note that this command backs up only 3rd party apps, coz I don't see the point of backing up built-in apps. But if you wanna backup system apps too, just omit the -3 option.

Setting environment variables in Linux using Bash

export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR".

List Git aliases

I like @Thomas's answer, and I do some modifications.

features:

  • add color
  • and input parameter: to let the user choose command (from git config --get-regexp ^.)
  • add filter
# .gitconfig

[alias]
    show-cmd = "!f() { \
        sep="?" ;\
        name=${1:-alias};\
        echo -n -e '\\033[48;2;255;255;01m' ;\
        echo -n -e '\\033[38;2;255;0;01m' ;\
        echo "$name"; \
        echo -n -e '\\033[m' ;\
        git config --get-regexp ^$name\\..*$2+ | \
        cut -c 1-40 | \
        sed -e s/^$name.// \
        -e s/\\ /\\ $(printf $sep)--\\>\\ / | \
        column -t -s $(printf $sep) | \
        sort -k 1 ;\
    }; f"

USAGE

  1. git show-cmd list alias
  2. git show-cmd "" st list alias, and it should contain the string st
  3. git show-cmd i18n show i18n setting
  4. git show-cmd core editor show core setting, and it should contain editor

DEMO

enter image description here

It's working fine on windows too

Explanation

  • you can write the long script on .gitconfig use the syntax as below:

    [alias]
        your-cmd = "!f() { \
            \
        }; f"
    
  • name=${1:-alias} same as name = $1 if $1 else -alias

  • echo -n -e (see more echo)

    • -n = Do not output a trailing newline.
    • -e Enable interpretation of the following backslash-escaped
  • '\\033[38;2;255;0;01m' (see more SGR parameters)

    • \\033[48; : 48 means background color.
    • \\033[38;2;255;0;0m : 38 means fore color. 255;0;0 = Red
  • cut -c 1-40 To avoid your command is too long, so take 40 char only.

  • sed -e 's/be_replace_string/new_string/' replace string to new string. (if you want to put the special-char(such as space, > ...) should add \\ as the prefix.

  • column -t -s $(printf $sep) formats all lines into an evenly spaced column table.

  • sort -k 1 sorts all lines based on the value in the first column

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

You can used Lambda as "Lambda Proxy Integration" ,ref this [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python] , options avalible to this lambda are

For Nodejs Lambda 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables', and 'event.requestContext'

For Python Lambda event['headers']['parametername'] and so on

Egit rejected non-fast-forward

In the meantime (while you were updating your project), other commits have been made to the 'master' branch. Therefore, you must pull those changes first to be able to push your changes.

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

Is it better practice to use String.format over string Concatenation in Java?

I think we can go with MessageFormat.format as it should be good at both readability and also performance aspects.

I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat to explain the performance numbers.

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = "Hi " + i + "; Hi to you " + i * 2;
    }
    long end = System.currentTimeMillis();
    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
  }

Concatenation = 69 millisecond

Format = 1435 millisecond

MessageFormat = 200 millisecond

UPDATES:

As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

I replace the printf-style with the curly-brackets and I got something interesting results as below.

Concatenation = 69 millisecond
Format = 1107 millisecond
Format:curly-brackets = 416 millisecond
MessageFormat = 215 millisecond
MessageFormat:curly-brackets = 2517 millisecond

My Conclusion:
As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

How do I commit case-sensitive only filename changes in Git?

You can use git mv:

git mv -f OldFileNameCase newfilenamecase

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

That's easy! First, give your button an id such as <input type="button" value="I am a button!" id="myButton" /> Then, for height, and width, use CSS code:

.myButton {
    width: 100px;
    height: 100px;
}

You could also do this CSS:

input[type="button"] {
    width: 100px;
    height: 100px;
}

But that would affect all the buttons on the Page.

Working example - JSfiddle

onMeasure custom view explanation

actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:

  • EXACTLY match_parent is EXACTLY + size of the parent
  • AT_MOST wrap_content results in an AT_MOST MeasureSpec
  • UNSPECIFIED never triggered

In case of an horizontal scroll view, your code will work.

What's the difference between tilde(~) and caret(^) in package.json?

I would like to add the official npmjs documentation as well which describes all methods for version specificity including the ones referred to in the question -

https://docs.npmjs.com/files/package.json

https://docs.npmjs.com/misc/semver#x-ranges-12x-1x-12-

  • ~version "Approximately equivalent to version" See npm semver - Tilde Ranges & semver (7)
  • ^version "Compatible with version" See npm semver - Caret Ranges & semver (7)
  • version Must match version exactly
  • >version Must be greater than version
  • >=version etc
  • <version
  • <=version
  • 1.2.x 1.2.0, 1.2.1, etc., but not 1.3.0
  • http://sometarballurl (this may be the URL of a tarball which will be downloaded and installed locally
  • * Matches any version
  • latest Obtains latest release

The above list is not exhaustive. Other version specifiers include GitHub urls and GitHub user repo's, local paths and packages with specific npm tags

delete image from folder PHP

There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

Each image's display markup would contain a form something like this:

echo '<form method="post">';
  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
  echo '<input type="submit" value="Delete image" />';
echo '</form>';

...and at at the top of that same PHP file:

if (array_key_exists('delete_file', $_POST)) {
  $filename = $_POST['delete_file'];
  if (file_exists($filename)) {
    unlink($filename);
    echo 'File '.$filename.' has been deleted';
  } else {
    echo 'Could not delete '.$filename.', file does not exist';
  }
}
// existing code continues below...

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

Documentation and Related Reading

Can you remove elements from a std::list while iterating through it?

Use std::remove_if algorithm.

Edit:
Work with collections should be like:

  1. prepare collection.
  2. process collection.

Life will be easier if you won't mix this steps.

  1. std::remove_if. or list::remove_if ( if you know that you work with list and not with the TCollection )
  2. std::for_each

Sorting arrays in javascript by object key value

Here is yet another one-liner for you:

your_array.sort((a, b) => a.distance === b.distance ? 0 : a.distance > b.distance || -1);

how to hide keyboard after typing in EditText in android?

I use this method to remove keyboard from edit text:

 public static void hideKeyboard(Activity activity, IBinder binder) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (binder != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(binder, 0);//HIDE_NOT_ALWAYS
            inputManager.showSoftInputFromInputMethod(binder, 0);
        }
    }
}

And this method to remove keyboard from activity (not work in some cases - for example, when edittext, to wich is binded keyboard, lost focus, it won't work. But for other situations, it works great, and you do not have to care about element that holds the keyboard).

 public static void hideKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

Finish all activities at a time

You can store a boolean flag to represent if all activities should be finished or not (more preferred in your shared preferences) then onStart() method of each activity should have something like:

SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
boolean needToDestroyFlag=pref.getBoolean("destroyFlag", false);
if(needToDestroyFlag)
{
    finish();
}else
{
    //...
}

Obviously you can set this flag like below when ever you need to finish all activities (in the current activity) after doing so you can call finish() method on current activity that will result to terminate current activity and pop activities from stack up one by one, the onStart() method of each one executes and causes to terminate it:

SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean("destroyFlag", true);
editor.apply();

If you use the method that @letsnurture suggested, you'll be faced with the question asked by @gumuruh.

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

How to detect internet speed in JavaScript?

Even though this is old and answered, i´d like to share the solution i made out of it 2020

it comes with the flexibility to run at anytime and run a callback if greater and or smaller the specified mbps

you can start the test anywhere after you included the testConnectionSpeed Object by running the testConnectionSpeed.run(mbps, morefunction, lessfunction)

for example:

_x000D_
_x000D_
var testConnectionSpeed = {
  imageAddr : "https://upload.wikimedia.org/wikipedia/commons/a/a6/Brandenburger_Tor_abends.jpg", // this is just an example, you rather want an image hosted on your server
  downloadSize : 2707459, // this must match with the image above
  run:function(mbps_max,cb_gt,cb_lt){
    testConnectionSpeed.mbps_max = parseFloat(mbps_max) ? parseFloat(mbps_max) : 0;
    testConnectionSpeed.cb_gt = cb_gt;
    testConnectionSpeed.cb_lt = cb_lt;
    testConnectionSpeed.InitiateSpeedDetection();
  },
  InitiateSpeedDetection: function() {
    window.setTimeout(testConnectionSpeed.MeasureConnectionSpeed, 1);
  },
  result:function(){
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = testConnectionSpeed.downloadSize * 8;
    var speedBps = (bitsLoaded / duration).toFixed(2);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    if(speedMbps >= (testConnectionSpeed.max_mbps ? testConnectionSpeed.max_mbps : 1) ){
      testConnectionSpeed.cb_gt ? testConnectionSpeed.cb_gt(speedMbps) : false;
    }else {
      testConnectionSpeed.cb_lt ? testConnectionSpeed.cb_lt(speedMbps) : false;
    }
  },
  MeasureConnectionSpeed:function() {
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        testConnectionSpeed.result();
    }
    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = testConnectionSpeed.imageAddr + cacheBuster;
  }
}




// start test immediatly, you could also call this on any event or whenever you want
testConnectionSpeed.run(1.5, function(mbps){console.log(">= 1.5Mbps ("+mbps+"Mbps)")}, function(mbps){console.log("< 1.5Mbps("+mbps+"Mbps)")} )
_x000D_
_x000D_
_x000D_

I used this successfuly to load lowres media for slow internet connections. You have to play around a bit because on the one hand, the larger the image, the more reasonable the test, on the other hand the test will take way much longer for slow connection and in my case I especially did not want slow connection users to load lots of MBs.

How to add "active" class to wp_nav_menu() current menu item (simple way)

In header.php insert this code to show menu:

<?php
    wp_nav_menu(
        array(
            'theme_location' => 'menu-one',
            'walker' => new Custom_Walker_Nav_Menu_Top
        )
    );
?>

In functions.php use this:

class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $is_current_item = '';
        if(array_search('current-menu-item', $item->classes) != 0)
        {
            $is_current_item = ' class="active"';
        }
        echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
    }

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        echo '</a></li>';
    }
}

How do I remove an item from a stl vector with a certain value?

If you want to remove an item, the following will be a bit more efficient.

std::vector<int> v;


auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
    v.erase(it);

or you may avoid overhead of moving the items if the order does not matter to you:

std::vector<int> v;

auto it = std::find(v.begin(), v.end(), 5);

if (it != v.end()) {
  using std::swap;

  // swap the one to be removed with the last element
  // and remove the item at the end of the container
  // to prevent moving all items after '5' by one
  swap(*it, v.back());
  v.pop_back();
}

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

calling a java servlet from javascript

   function callServlet()


{
 document.getElementById("adminForm").action="./Administrator";
 document.getElementById("adminForm").method = "GET";
 document.getElementById("adminForm").submit();

}

<button type="submit"  onclick="callServlet()" align="center"> Register</button>

Is there a JavaScript strcmp()?

Javascript doesn't have it, as you point out.

A quick search came up with:

function strcmp ( str1, str2 ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1

    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}

from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/

Of course, you could just add localeCompare if needed:

if (typeof(String.prototype.localeCompare) === 'undefined') {
    String.prototype.localeCompare = function(str, locale, options) {
        return ((this == str) ? 0 : ((this > str) ? 1 : -1));
    };
}

And use str1.localeCompare(str2) everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales and options if you care about that.

How to read a file and write into a text file?

If you want to do it line by line:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

Is there a combination of "LIKE" and "IN" in SQL?

I'm working with SQl Server and Oracle here but I'm interested if this is possible in any RDBMS at all.

Teradata supports LIKE ALL/ANY syntax:

ALL every string in the list.
ANY any string in the list.

+-------------------------------------------------------------------+
¦      THIS expression …       ¦ IS equivalent to this expression … ¦
+------------------------------+------------------------------------¦
¦ x LIKE ALL ('A%','%B','%C%') ¦ x LIKE 'A%'                        ¦
¦                              ¦ AND x LIKE '%B'                    ¦
¦                              ¦ AND x LIKE '%C%'                   ¦
¦                              ¦                                    ¦
¦ x LIKE ANY ('A%','%B','%C%') ¦ x LIKE 'A%'                        ¦
¦                              ¦ OR x LIKE '%B'                     ¦
¦                              ¦ OR x LIKE '%C%'                    ¦
+-------------------------------------------------------------------+

EDIT:

jOOQ version 3.12.0 supports that syntax:

Add synthetic [NOT] LIKE ANY and [NOT] LIKE ALL operators

A lot of times, SQL users would like to be able to combine LIKE and IN predicates, as in:

SELECT *
FROM customer
WHERE last_name [ NOT ] LIKE ANY ('A%', 'E%') [ ESCAPE '!' ]

The workaround is to manually expand the predicate to the equivalent

SELECT *
FROM customer
WHERE last_name LIKE 'A%'
OR last_name LIKE 'E%'

jOOQ could support such a synthetic predicate out of the box.


PostgreSQL LIKE/ILIKE ANY (ARRAY[]):

SELECT *
FROM t
WHERE c LIKE ANY (ARRAY['A%', '%B']);

SELECT *
FROM t
WHERE c LIKE ANY ('{"Do%", "%at"}');

db<>fiddle demo


Snowflake also supports LIKE ANY/LIKE ALL matching:

LIKE ANY/ALL

Allows case-sensitive matching of strings based on comparison with one or more patterns.

<subject> LIKE ANY (<pattern1> [, <pattern2> ... ] ) [ ESCAPE <escape_char> ]

Example:

SELECT * 
FROM like_example 
WHERE subject LIKE ANY ('%Jo%oe%','T%e')
-- WHERE subject LIKE ALL ('%Jo%oe%','J%e')

npm ERR! network getaddrinfo ENOTFOUND

Instead of setting the proxy usingnpm config set http_proxy=http://address:8080 go to ~/.npmrc and remove the proxy config. This resolved my issue.

Why is php not running?

Check out the apache config files. For Debian/Ubuntu theyre in /etc/apache2/sites-available/ for RedHat/CentOS/etc they're in /etc/httpd/conf.d/. If you've just installed it, the file in there is probably named default.

Make sure that the config file in there is pointing to the correct folder and then make sure your scripts are located there.

The line you're looking for in those files is DocumentRoot /path/to/directory.

For a blank install, your php files most likely needs to be in /var/www/.

What you'll also need to do is find your php.ini file, probably located at /etc/php5/apache2/php.ini or /etc/php.ini and find the entry for display_errors and switch it to On.

How to use BigInteger?

java.math.BigInteger is an immutable class so we can not assign new object in the location of already assigned object. But you can create new object to assign new value like:

sum = sum.add(BigInteger.valueOf(i));

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

I have tried everything, and finally deleting the -vm options worked for me.

How to make a parent div auto size to the width of its children divs

Your interior <div> elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-block instead of width:auto on the container div. Or possibly float:left the container and also apply overflow:auto. Depends on what you're after exactly.

How to set time to 24 hour format in Calendar

tl;dr

LocalTime.parse( "10:30" )  // Parsed as 24-hour time.

java.time

Avoid the troublesome old date-time classes such as Date and Calendar that are now supplanted by the java.time classes.

LocalTime

The java.time classes provide a way to represent the time-of-day without a date and without a time zone: LocalTime

LocalTime lt = LocalTime.of( 10 , 30 );  // 10:30 AM.
LocalTime lt = LocalTime.of( 22 , 30 );  // 22:30 is 10:30 PM.

ISO 8601

The java.time classes use standard ISO 8601 formats by default when generating and parsing strings. These formats use 24-hour time.

String output = lt.toString();

LocalTime.of( 10 , 30 ).toString() : 10:30

LocalTime.of( 22 , 30 ).toString() : 22:30

So parsing 10:30 will be interpreted as 10:30 AM.

LocalTime lt = LocalTime.parse( "10:30" );  // 10:30 AM.

DateTimeFormatter

If you need to generate or parse strings in 12-hour click format with AM/PM, use the DateTimeFormatter class. Tip: make a habit of specifying a Locale.

Importing Excel into a DataTable Quickly

MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.

Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:

ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];

If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Same as the other answers (disabled isn't sent to the server, readonly is) but some browsers prevent highlighting of a disabled form, while read-only can still be highlighted (and copied).

http://www.w3schools.com/tags/att_input_disabled.asp

http://www.w3schools.com/tags/att_input_readonly.asp

A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.

WCF Service Returning "Method Not Allowed"

The basic intrinsic types (e.g. byte, int, string, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.

So, a silly question (but I have to ask it...): is UploadedFile marked as a [DataContract]? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].

Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)

A tremendous resource for WCF development is what we know in our shop as "the fish book": Programming WCF Services by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.

Date to milliseconds and back to date in Swift

I don't understand why you're doing anything with strings...

extension Date {
    var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }

    init(milliseconds:Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }
}


Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)

How to change the background color on a Java panel?

setBackground() is the right method to use. Did you repaint after you changed it? If you change it before you make the panel (or its containing frame) visible it should work

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

VC++ fatal error LNK1168: cannot open filename.exe for writing

FINALLY THE BEST WAY WORKED PERFECTLY FOR ME

None of the solutions in this page worked for me EXCEPT THE FOLLOWING

Below the comment sections of the second answer, try the following :

Adding to my above comment, Task Manager does not display the filename.exe process but Resource Monitor does, so I'm able to kill it from there which solves the issue without having to reboot. – A__ Jun 19 '19 at 21:23

Draw text in OpenGL ES

I have been looking for this for a few hours, this was the first article i came accross and although it has the best answer, the most popular answers i think are off the mark. Certainly for what i needed. weichsel's and shakazed's answers were right on the button but a bit obscured in the articles. To put you right to the project. Here: Just create a new Android project based on existing sample. Choose ApiDemos:

Look under the source folder

ApiDemos/src/com/example/android/apis/graphics/spritetext

And you will find everything you need.

redirect COPY of stdout to log file from within bash script itself

Bash 4 has a coproc command which establishes a named pipe to a command and allows you to communicate through it.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.

Now I have an extra step before attempting the resize operation, which is to do the assertion myself:

def getSizedFrame(width, height):
"""Function to return an image with the size I want"""    
    s, img = self.cam.read()

    # Only process valid image frames
    if s:
            img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
    return s, img

Now I don't see the error.

Using node.js as a simple web server

Express function sendFile does exactly what you need, and since you want web server functionality from node, express comes as natural choice and then serving static files becomes as easy as :

res.sendFile('/path_to_your/index.html')

read more here : https://expressjs.com/en/api.html#res.sendFile

A small example with express web server for node:

var express = require('express');
var app = express();
var path = require('path');

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8080);

run this, and navigate to http://localhost:8080

To expand on this to allow you to serve static files like css and images, here's another example :

var express = require('express');
var app = express();
var path = require('path');

app.use(express.static(__dirname + '/css'));

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8080);

so create a subfolder called css, put your static content in it, and it will be available to your index.html for easy reference like :

<link type="text/css" rel="stylesheet" href="/css/style.css" />

Notice relative path in href!

voila!

Angular 2 / 4 / 5 not working in IE11

In polyfills.ts

import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';

import 'core-js/es6/array';
import 'core-js/es7/array';

import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/weak-set';
import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
 import 'classlist.js';  // Run `npm install --save classlist.js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';

/**
 * Required to support Web Animations `@angular/animation`.
 * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
 **/
import 'web-animations-js';  // Run `npm install --save web-animations-js`.

DISTINCT for only one column

Try This

;With Tab AS (SELECT DISTINCT Email FROM  Products)
SELECT Email,ROW_NUMBER() OVER(ORDER BY Email ASC) AS  Id FROM Tab
ORDER BY Email ASC

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

How do I create a constant in Python?

well.. even though this is outdated, let me add my 2 cents here :-)

class ConstDict(dict):
    def __init__(self, *args, **kwargs):
        super(ConstDict, self).__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        if key in self:
            raise ValueError("Value %s already exists" % (key))
        super(ConstDict, self).__setitem__(key, value)

Instead of ValueError to break, you can prevent any update happening there. One advantage of this is that you can add constants dynamically in the program but you cannot change once a constant is set. Also you can add any rule or whatsoever before setting a constant(something like key must be a string or a lower case string or upper case string and so on before setting the key)

However, I do not see any importance of setting constants in Python. No optimizations can happen like in C and hence it is something that is not required, I guess.

Simulate Keypress With jQuery

I believe this is what you're looking for:

var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);

From here.

Detect application heap size in Android

The official API is:

This was introduced in 2.0 where larger memory devices appeared. You can assume that devices running prior versions of the OS are using the original memory class (16).

Laravel 5.5 ajax call 419 (unknown status)

Use this in the head section:

<meta name="csrf-token" content="{{ csrf_token() }}">

and get the csrf token in ajax:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }
});

Please refer Laravel Documentation csrf_token

from list of integers, get number closest to a given value

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

How to unpack pkl file?

Handy one-liner

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

Will print __str__ for the pickled object.

The generic problem of visualizing an object is of course undefined, so if __str__ is not enough, you will need a custom script.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

For me, the cause of the error message

No tests found for given includes

was having inadvertently added a .java test file under my src/test/kotlin test directory. Upon moving the file to the correct directory, src/test/java, the test executed as expected again.

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

How to enable file upload on React's Material UI simple input?

Just the same as what should be but change the button component to be label like so

<form id='uploadForm'
      action='http://localhost:8000/upload'
      method='post'
      encType="multipart/form-data">
    <input type="file" id="sampleFile" style="display: none;" />
    <Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button> 
</form>

How can I read a large text file line by line using Java?

You can read file data line by line as below:

String fileLoc = "fileLocationInTheDisk";

List<String> lines = Files.lines(Path.of(fileLoc), StandardCharsets.UTF_8).collect(Collectors.toList());

Create a pointer to two-dimensional array

You want a pointer to the first element, so;

static uint8_t l_matrix[10][20];

void test(){
   uint8_t *matrix_ptr = l_matrix[0]; //wrong idea 
}

Parsing JSON with Unix tools

i used this to extract video duration from ffprobe json output :

MOVIE_INFO=`ffprobe "path/to/movie.mp4"  -show_streams -show_format -print_format json -v quiet` 
MOVIE_SECONDS=`echo "$MOVIE_INFO"|grep -w \"duration\" |tail -1 | cut -d\" -f4 |cut -d \. -f 1`

it can be used to extract value from any json :

value=`echo "$jsondata"|grep -w \"key_name\" |tail -1 | cut -d\" -f4

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

INNER JOIN same table

Your query should work fine, but you have to use the alias parent to show the values of the parent table like this:

select 
  CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
  CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.