Programs & Examples On #Defensive programming

Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software. Defensive programming techniques are used especially when a piece of software could be misused mischievously or inadvertently to catastrophic effect.

Plot multiple lines (data series) each with unique color in R

If your data is in wide format matplot is made for this and often forgotten about:

 dat <- matrix(runif(40,1,20),ncol=4) # make data
 matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
 legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend

There is also the added bonus for those unfamiliar with things like ggplot that most of the plotting paramters such as pch etc. are the same using matplot() as plot(). enter image description here

Connect Bluestacks to Android Studio

world !

No need to do execute batch command. With the current version, just run BLUESTACKS before ANDROID STUDIO

What's is the difference between train, validation and test set, in neural networks?

In simple words define Training set, Test set, Validation set

Training set: Is used for finding Nearest neighbors. Validation set: Is for finding different k which is applying to train set. Test set: Is used for finding the maximum accuracy and unseen data in future.

How do I use WPF bindings with RelativeSource?

I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.

How do I execute a PowerShell script automatically using Windows task scheduler?

In my case, my script has parameters, so I set:

Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

How to debug Google Apps Script (aka where does Logger.log log to?)

The dev console will log errors thrown by the app script, so you can just throw an error to get it logged as a normal console.log. It will stop execution, but it might still be useful for step by step debugging.

throw Error('hello world!');

will show up in the console similarly to console.log('hello world')

Convert a String to int?

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

What is the scope of variables in JavaScript?

Here's an example:

<script>

var globalVariable = 7; //==window.globalVariable

function aGlobal( param ) { //==window.aGlobal(); 
                            //param is only accessible in this function
  var scopedToFunction = {
    //can't be accessed outside of this function

    nested : 3 //accessible by: scopedToFunction.nested
  };

  anotherGlobal = {
    //global because there's no `var`
  }; 

}

</script>

You'll want to investigate closures, and how to use them to make private members.

How to execute a JavaScript function when I have its name as a string

One more detail on Jason and Alex's posts. I found it helpful to add a default value to context. Just put context = context == undefined? window:context; at the beginning of the function. You can change window to whatever your preferred context is, and then you won't need to pass in the same variable each time you call this in your default context.

Entity Framework Migrations renaming tables and columns

If you don't like writing/changing the required code in the Migration class manually, you can follow a two-step approach which automatically make the RenameColumn code which is required:

Step One Use the ColumnAttribute to introduce the new column name and then add-migration (e.g. Add-Migration ColumnChanged)

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Group_Id{get;set}
}

Step-Two change the property name and again apply to same migration (e.g. Add-Migration ColumnChanged -force) in the Package Manager Console

public class ReportPages
{
    [Column("Section_Id")]                 //Section_Id
    public int Section_Id{get;set}
}

If you look at the Migration class you can see the automatically code generated is RenameColumn.

Issue with background color and Google Chrome

Simple, correct, solution - define the background image and colour in html, not body. Unless you've defined a specific height (not a percentage) in the body, its height will be assumed to be as tall as required to hold all content. so your background styling should go into html, which is the entire html document, not just the body. Simples.

Replace Div with another Div

HTML

<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>

JavaScript

jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));

Using an authorization header with Fetch in React Native

It turns out, I was using the fetch method incorrectly.

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

I was wrapping the intended object within a second object, which did not get me any desired result.

Here's how it looks on a high level:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

I structured my object as such:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

How to load images dynamically (or lazily) when users scrolls them into view

There is a pretty nice infinite scroll plugin here

I've never programmed one myself, but I would imagine this is how it works.

  1. An event is bound to the the window scrolling

    $(window).scroll(myInfinteScrollFunction);
    
  2. The called function checks if scroll top is greater than the window size

    function myInfiniteScrollFunction() {  
        if($(window).scrollTop() == $(window).height())  
        makeAjaxRequest();  
    }
    
  3. An AJAX request is made, specifying which result # to start at, how many to grab, and any other parameters necessary for the data pull.

    $.ajax({
        type: "POST",
        url:  "myAjaxFile.php",
        data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" },
        success: myInfiniteLoadFunction(msg)
    });
    
  4. The ajax returns some (most-likely JSON formatted) content, and passes them into the loadnig function.

Hope that makes sense.

AWK to print field $2 first, then field $1

A couple of general tips (besides the DOS line ending issue):

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

Try:

awk -F'|' '{print $2" "$1}' foo 

This will output:

com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

How do I revert my changes to a git submodule?

my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):

git submodule foreach 'git checkout master && git reset --hard $sha1'

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

Is there any kind of hash code function in JavaScript?

In ECMAScript 6 there's now a Set that works how you'd like: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

It's already available in the latest Chrome, FF, and IE11.

VBA - Range.Row.Count

You should use UsedRange instead like so:

Sub test()
    Dim sh As Worksheet
    Dim rn As Range
    Set sh = ThisWorkbook.Sheets("Sheet1")

    Dim k As Long

    Set rn = sh.UsedRange
    k = rn.Rows.Count + rn.Row - 1
End Sub

The + rn.Row - 1 part is because the UsedRange only starts at the first row and column used, so if you have something in row 3 to 10, but rows 1 and 2 is empty, rn.Rows.Count would be 8

What is the difference between Linear search and Binary search?

For a clear understanding, please take a look at my codepen implementations https://codepen.io/serdarsenay/pen/XELWqN

Biggest difference is the need to sort your sample before applying binary search, therefore for most "normal sized" (meaning to be argued) samples will be quicker to search with a linear search algorithm.

Here is the javascript code, for html and css and full running example please refer to above codepen link.

var unsortedhaystack = [];
var haystack = [];
function init() {
  unsortedhaystack = document.getElementById("haystack").value.split(' ');
}
function sortHaystack() {
  var t = timer('sort benchmark');
  haystack = unsortedhaystack.sort();
  t.stop();
}

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

function lineerSearch() {
  init();
  var t = timer('lineerSearch benchmark');
  var input = this.event.target.value;
  for(var i = 0;i<unsortedhaystack.length - 1;i++) {
    if (unsortedhaystack[i] === input) {
      document.getElementById('result').innerHTML = 'result is... "' + unsortedhaystack[i] + '", on index: ' + i + ' of the unsorted array. Found' + ' within ' + i + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return unsortedhaystack[i]; 
    }
  }
}

function binarySearch () {
  init();
  sortHaystack();
  var t = timer('binarySearch benchmark');
  var firstIndex = 0;
  var lastIndex = haystack.length-1;
  var input = this.event.target.value;

  //currently point in the half of the array
  var currentIndex = (haystack.length-1)/2 | 0;
  var iterations = 0;

  while (firstIndex <= lastIndex) {
    currentIndex = (firstIndex + lastIndex)/2 | 0;
    iterations++;
    if (haystack[currentIndex]  < input) {
      firstIndex = currentIndex + 1;
      //console.log(currentIndex + " added, fI:"+firstIndex+", lI: "+lastIndex);
    } else if (haystack[currentIndex] > input) {
      lastIndex = currentIndex - 1;
      //console.log(currentIndex + " substracted, fI:"+firstIndex+", lI: "+lastIndex);
    } else {
      document.getElementById('result').innerHTML = 'result is... "' + haystack[currentIndex] + '", on index: ' + currentIndex + ' of the sorted array. Found' + ' within ' + iterations + ' iterations';
      console.log(document.getElementById('result').innerHTML);
      t.stop(); 
      return true;
    }
  }
}

How to disable editing of elements in combobox for c#?

This is another method I use because changing DropDownSyle to DropDownList makes it look 3D and sometimes its just plain ugly.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

Uninstall old versions of Ruby gems

# remove all old versions of the gem
gem cleanup rjb

# choose which ones you want to remove
gem uninstall rjb

# remove version 1.1.9 only
gem uninstall rjb --version 1.1.9

# remove all versions less than 1.3.4
gem uninstall rjb --version '<1.3.4'

How to set Status Bar Style in Swift 3

[UPDATED] For Xcode 10+ & Swift 4.2+

This is the preferred method for iOS 7 and higher

In your application's Info.plist, set View controller-based status bar appearance to YES.

Override preferredStatusBarStyle (Apple docs) in each of your view controllers. For example:

override var preferredStatusBarStyle: UIStatusBarStyle {     
      return .lightContent
}

If you have preferredStatusBarStyle returning a different preferred status bar style based on something that changes inside of your view controller (for example, whether the scroll position or whether a displayed image is dark), then you will want to call setNeedsStatusBarAppearanceUpdate() when that state changes.

iOS before version 7, deprecated method

Apple has deprecated this, so it will be removed in the future. Use the above method so that you don't have to rewrite it when the next iOS version is released.

If your application will support In your application's Info.plist, set View controller-based status bar appearance to NO.

In appDelegate.swift, the didFinishLaunchingWithOptions function, add:

UIApplication.shared.statusBarStyle = .lightContent

For Navigation Controller

If you use a navigation controller and you want the preferred status bar style of each view controller to be used and set View controller-based status bar appearance to YES in your application's info.plist

extension UINavigationController {
   open override var preferredStatusBarStyle: UIStatusBarStyle {
      return topViewController?.preferredStatusBarStyle ?? .default
   }
}

Cannot find JavaScriptSerializer in .Net 4.0

Check if you included the .net 4 version of System.Web.Extensions - there's a 3.5 version as well, but I don't think that one works.

These steps work for me:

  1. Create a new console application
  2. Change the target to .net 4 instead of Client Profile
  3. Add a reference to System.Web.Extensions (4.0)
  4. Have access to JavaScriptSerializer in Program.cs now :-)

CodeIgniter : Unable to load the requested file:

An Error Was Encountered Unable to load the requested file:

Sometimes we face this error because the requested file doesn't exist in that directory.

Suppose we have a folder home in views directory and trying to load home_view.php file as:

$this->load->view('home/home_view', $data);// $data is array

If home_view.php file doesn't exist in views/home directory then it will raise an error.

An Error Was Encountered Unable to load the requested file: home\home_view.php

So how to fix this error go to views/home and check the home_view.php file exist if not then create it.

Android ListView not refreshing after notifyDataSetChanged

Try this

@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}

Why javascript getTime() is not a function?

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

Multi-select dropdown list in ASP.NET

Try this server control which inherits directly from CheckBoxList (free, open source): http://dropdowncheckboxes.codeplex.com/

ITSAppUsesNonExemptEncryption export compliance while internal testing?

There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:

Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15

Consumer applications

  • piracy and theft prevention for software or music;
  • music, movies, tunes/music, digital photos – players, recorders and organizers
  • games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
  • LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
  • printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
  • household utilities and appliances

Business / systems applications: systems operations, integration and control. Some examples

  • business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery

  • transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.

  • industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC

  • medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality

  • applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology

Research /scientific /analytical. Some examples:

  • business process management (BPM) – business process abstraction and modeling

  • scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)

  • data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)

Secure intellectual property delivery and installation. Some examples

  • software download auto-installers and updaters

  • license key product protection and similar purchase validation

  • software and hardware design IP protection

  • computer aided design (CAD) software and other drafting tools

Note: These regulations are also true for testing your app using TestFlight

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

I am trying to contribute with another solution for the single insertion problem with the pre-9.5 versions of PostgreSQL. The idea is simply to try to perform first the insertion, and in case the record is already present, to update it:

do $$
begin 
  insert into testtable(id, somedata) values(2,'Joe');
exception when unique_violation then
  update testtable set somedata = 'Joe' where id = 2;
end $$;

Note that this solution can be applied only if there are no deletions of rows of the table.

I do not know about the efficiency of this solution, but it seems to me reasonable enough.

Converting HTML element to string in JavaScript / JQuery

What you want is the outer HTML, not the inner HTML :

$('<some element/>')[0].outerHTML;

How to start rails server?

Make sure you're in the right directory when you start the server

sites>yoursite> rails s

.NET Format a string with fixed spaces

This will give you exactly the strings that you asked for:

string s = "String goes here";
string lineAlignedRight  = String.Format("{0,27}", s);
string lineAlignedCenter = String.Format("{0,-27}",
    String.Format("{0," + ((27 + s.Length) / 2).ToString() +  "}", s));
string lineAlignedLeft   = String.Format("{0,-27}", s);

iOS Simulator to test website on Mac

You could also download Xcode to your mac and use iPhone simulator.

Cutting the videos based on start and end time using ffmpeg

You probably do not have a keyframe at the 3 second mark. Because non-keyframes encode differences from other frames, they require all of the data starting with the previous keyframe.

With the mp4 container it is possible to cut at a non-keyframe without re-encoding using an edit list. In other words, if the closest keyframe before 3s is at 0s then it will copy the video starting at 0s and use an edit list to tell the player to start playing 3 seconds in.

If you are using the latest ffmpeg from git master it will do this using an edit list when invoked using the command that you provided. If this is not working for you then you are probably either using an older version of ffmpeg, or your player does not support edit lists. Some players will ignore the edit list and always play all of the media in the file from beginning to end.

If you want to cut precisely starting at a non-keyframe and want it to play starting at the desired point on a player that does not support edit lists, or want to ensure that the cut portion is not actually in the output file (for example if it contains confidential information), then you can do that by re-encoding so that there will be a keyframe precisely at the desired start time. Re-encoding is the default if you do not specify copy. For example:

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4

When re-encoding you may also wish to include additional quality-related options or a particular AAC encoder. For details, see ffmpeg's x264 Encoding Guide for video and AAC Encoding Guide for audio.

Also, the -t option specifies a duration, not an end time. The above command will encode 8s of video starting at 3s. To start at 3s and end at 8s use -t 5. If you are using a current version of ffmpeg you can also replace -t with -to in the above command to end at the specified time.

How to disable scrolling temporarily?

Site I have inherited, had a scroll on links. To disable this scroll on click on specific button temporary, this worked for me:

$(document).ready(function() {      
    $('button.class-name').click(function(event) {
        disableScroll();
        setTimeout(enableScroll, 500);  
    });
});


function disableScroll() {
    scrollTop =  window.pageYOffset || document.documentElement.scrollTop; 
    scrollLeft =  window.pageXOffset || document.documentElement.scrollLeft, 

    window.onscroll = function() { 
            window.scrollTo(scrollLeft, scrollTop); 
    };
}

function enableScroll() { 
    window.onscroll = function() {}; 
} 

How do you find all subclasses of a given class in Java?

If you intend to load all subclassess of given class which are in the same package, you can do so:

public static List<Class> loadAllSubClasses(Class pClazz) throws IOException, ClassNotFoundException {
    ClassLoader classLoader = pClazz.getClassLoader();
    assert classLoader != null;
    String packageName = pClazz.getPackage().getName();
    String dirPath = packageName.replace(".", "/");
    Enumeration<URL> srcList = classLoader.getResources(dirPath);

    List<Class> subClassList = new ArrayList<>();
    while (srcList.hasMoreElements()) {
        File dirFile = new File(srcList.nextElement().getFile());
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (File file : files) {
                String subClassName = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                if (! subClassName.equals(pClazz.getName())) {
                    subClassList.add(Class.forName(subClassName));
                }
            }
        }
    }

    return subClassList;
}

How do I set a path in Visual Studio?

You have a couple of options:

  • You can add the path to the DLLs to the Executable files settings under Tools > Options > Projects and Solutions > VC++ Directories (but only for building, for executing or debugging here)
  • You can add them in your global PATH environment variable
  • You can start Visual Studio using a batch file as I described here and manipulate the path in that one
  • You can copy the DLLs into the executable file's directory :-)

What is the difference between == and equals() in Java?

The == operator tests whether two variables have the same references (aka pointer to a memory address).

String foo = new String("abc");
String bar = new String("abc");

if(foo==bar)
// False (The objects are not the same)

bar = foo;

if(foo==bar)
// True (Now the objects are the same)

Whereas the equals() method tests whether two variables refer to objects that have the same state (values).

String foo = new String("abc");
String bar = new String("abc");

if(foo.equals(bar))
// True (The objects are identical but not same)

Cheers :-)

How to define a preprocessor symbol in Xcode

It's under "GCC 4.2 Preprocessing" (or just put "prepro" in the search box)...

...however, for the life of me I can't get it to work.

I have my standard Debug and Release configurations, and I want to define DEBUG=1 in the debugging configuration. But after adding it as a value:

(in the settings window) > Preprocessor Macros : DEBUG=1

#if DEBUG
    printf("DEBUG is set!");
#endif 

...never prints/gets called. It's driving me crazy...

How to npm install to a specified directory?

As of npm version 3.8.6, you can use

npm install --prefix ./install/here <package>

to install in the specified directory. NPM automatically creates node_modules folder even when a node_modules directory already exists in the higher up hierarchy. You can also have a package.json in the current directory and then install it in the specified directory using --prefix option:

npm install --prefix ./install/here

As of npm 6.0.0, you can use

npm install --prefix ./install/here ./

to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.

NOTE: NPM honours the path that you've specified through the --prefix option. It resolves as per npm documentation on folders, only when npm install is used without the --prefix option.

Add data dynamically to an Array

There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:

$array = array();

Add to an array:

$array[] = "item"; // for your $arr1 
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");

Remove from an array:

$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);

There are plenty more ways, these are just some examples.

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

Can I add an image to an ASP.NET button?

You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.

Style="background-image:url('Image/1.png');"

You can change image location with using

background-repeat

properties. So you can write a button like below:

<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>

How do I configure Apache 2 to run Perl CGI scripts?

As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2 and mod-perl via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.

How to bring a window to the front?

Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.

Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).

That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:

if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();

(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).

While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.

I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.

2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront method do this (in conjunction with modified code from what is above):

setVisible(true);
toFront();
requestFocus();
repaint();

...

public @Override void toFront() {
    int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;

    super.setExtendedState(sta);
    super.setAlwaysOnTop(true);
    super.toFront();
    super.requestFocus();
    super.setAlwaysOnTop(false);
}

As of Java 8_20, this code seems to be working fine.

How do I load the contents of a text file into a javascript variable?

When working with jQuery, instead of using jQuery.get, e.g.

jQuery.get("foo.txt", undefined, function(data) {
    alert(data);
}, "html").done(function() {
    alert("second success");
}).fail(function(jqXHR, textStatus) {
    alert(textStatus);
}).always(function() {
    alert("finished");
});

you could use .load which gives you a much more condensed form:

$("#myelement").load("foo.txt");

.load gives you also the option to load partial pages which can come in handy, see api.jquery.com/load/.

HEAD and ORIG_HEAD in Git

From man 7 gitrevisions:

HEAD names the commit on which you based the changes in the working tree. FETCH_HEAD records the branch which you fetched from a remote repository with your last git fetch invocation. ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them. MERGE_HEAD records the commit(s) which you are merging into your branch when you run git merge. CHERRY_PICK_HEAD records the commit which you are cherry-picking when you run git cherry-pick.

how to make a full screen div, and prevent size to be changed by content?

#fullDiv {
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
    overflow: hidden;
    position: fixed;
}

jQuery show for 5 seconds then hide

You can use the below effect to animate, you can change the values as per your requirements

$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow'); 

Mime type for WOFF fonts?

I know this post is kind of old but after spending many hours on trying to make the fonts work on my nginx local machine and trying a tons of solutions i finally got the one that worked for me like a charm.

location ~* \.(eot|otf|ttf|woff|woff2)$ {
    add_header Access-Control-Allow-Origin *;
}

Inside the parenthesis you can put the extensions of your fonts or generally the files that you want to load. For example i used it for fonts and for images(png,jpg etc etc) as well so don't get confused that this solution applies only for fonts.

Just put it into your nginx config file, restart and i hope it works also for you!

IntelliJ: Never use wildcard imports

This applies for "Intellij Idea- 2020.1.2" on window

Navigate to "IntelliJ IDEA->File->Settings->Editor->Code Style->java".

enter image description here

Is it possible to create static classes in PHP (like in C#)?

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

What is an opaque response, and what purpose does it serve?

There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html

SVN repository backup strategies

there are 2 main methods to backup a svn server, first is hotcopy that will create a copy of your repository files, the main problem with this approach is that it saves data about the underlying file system, so you may have some difficulties trying to repostore this kind of backup in another svn server kind or another machine. there is another type of backup called dump, this backup wont save any information of the underlying file system and its potable to any kind of SVN server based in tigiris.org subversion.

about the backup tool you can use the svnadmin tool(it is able to do hotcopy and dump) from the command prompt, this console resides in the same directory where your svn server lives or you can google for svn backup tools.

my recommendation is that you do both kinds of backups and get them out of the office to your email acount, amazon s3 service, ftp, or azure services, that way you will have a securityy backup without having to host the svn server somewhere out of your office.

Where do I find the current C or C++ standard documents?

Although not an actual standard, there is an amendment to ISO C (C89/90) called C94/95, or Normative Addendum 1. It was integrated into C99, although some compilers such as Clang allow you to specifiy -std=c94 on the command line. ISO/IEC 9899:1990/Amd 1:1995 can be purchased for a hefty price from SAI GLOBAL (PDF or hard copy).

A summary of the document can be found here.

When the (then draft) ANSI C Standard was being considered for adoption of an International Standard in 1990, there were several objections because it didn't address internationalization issues. Because the Standard had already been several years in the making, it was agreed that a few changes would be made to provide the basis (for example, the functions in subclause 7.10.7 were added), and work would be carried out separately to provide proper internationalization of the Standard. This work has culminated in Normative Addendum 1.

Normative Addendum 1 embodies C's reaction to both the limitations and promises of international character sets. Digraphs and the header were meant to improve the appearance of C programs written in national variants of ISO 646 without, e.g., { or } characters. On the other end of the spectrum, the facilities connected to and extend the old Standard's barely adequate basis into a complete and consistent set of utilities for handling wide characters and multibyte strings.

This document summarizes Normative Addendum 1. It is intended to quickly inform readers who are already familiar with the Standard; it does not, and cannot, introduce the complex subject matter behind NA1, nor can it replace the original document as a reference manual. (Nevertheless, it tries to be as accurate as possible, and its author would like to hear about any errors or omissions.)

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

I managed to load an application.properties file in external path while using -jar option.

The key was PropertiesLauncher.

To use PropertiesLauncher, pom.xml file must be changed like this:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>  <!-- added -->
                <layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
            </configuration>
        </plugin>
    </plugins>
</build>

For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)

After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.

Now, I can run the jar as follows(in Windows):

java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar

Note that the application jar file is included in loader.path.

Now an application.properties file in C:\My\External\Dir\config is loaded.

As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.

As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.

What's the difference between "Layers" and "Tiers"?

Logical layers are merely a way of organizing your code. Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when we’re talking about layers, we’re only talking about logical organization of code. In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.

Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.

Source: Rockford Lhotka, Should all apps be n-tier?

Append to the end of a Char array in C++

There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.

What you're looking for is either std::vector to simulate a dynamic array, or better yet a std::string.

std::string first ("The dog jumps ");
std::string second ("over the log");
std::cout << first + second << std::endl;

How to run a method every X seconds

Use Timer for every second...

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        //your method
    }
}, 0, 1000);//put here time 1000 milliseconds=1 second

Is there way to use two PHP versions in XAMPP?

I do stuck with same problem at time of installing magento2 while it require ~7.3.0 but I have 7.4.1. So, I downgraded php version using this method.

Step 1: Download Php version from here nts version https://windows.php.net/downloads/releases/archives/ and paste this version to c:\xampp\ as named 'php71'

Step 2: Setup Virtual Host Environment and do some other changes. Go to "c:\xampp/\pache\conf\extra\httpd-vhosts.conf" and put code snippet at the end of line

<VirtualHost 127.0.0.1:80>
    DocumentRoot "C:/xampp/htdocs/magento/crashcourse/"
    ServerName magento2.test
    <Directory "C:/xampp/htdocs/magento/crashcourse/">
        Require all granted    
    </Directory>
    <FilesMatch "\.php$">
        SetHandler application/x-httpd-php71-cgi
    </FilesMatch>
</VirtualHost>

GO to "C:\Windows\System32\drivers\etc\hosts" then edit the file with using admin privileges then add the code at end of line.

127.0.0.1 magento2.test

Go to you Apache Config file "c:/xampp/apache/conf/extra/httpd-xampp.conf" and paste below code at end of the line

ScriptAlias /php71 "C:/xampp/php71"
Action application/x-httpd-php71-cgi /php71/php-cgi.exe
<Directory "C:/xampp/php71">
    AllowOverride None
    Options None
    Require all denied
    <Files "php-cgi.exe">
        Require all granted
    </Files>
    SetEnv PHPRC "C:/xampp/php71"
</Directory>

Now, all set. Go to url: http://magento2.test all work fine!

How should a model be structured in MVC?

In Web-"MVC" you can do whatever you please.

The original concept (1) described the model as the business logic. It should represent the application state and enforce some data consistency. That approach is often described as "fat model".

Most PHP frameworks follow a more shallow approach, where the model is just a database interface. But at the very least these models should still validate the incoming data and relations.

Either way, you're not very far off if you separate the SQL stuff or database calls into another layer. This way you only need to concern yourself with the real data/behaviour, not with the actual storage API. (It's however unreasonable to overdo it. You'll e.g. never be able to replace a database backend with a filestorage if that wasn't designed ahead.)

Display PDF within web browser

instead of using iframe and depending on the third party`think about using flexpaper, or pdf.js.

I used PDF.js, it works fine for me. Here is the demo.

Composer: The requested PHP extension ext-intl * is missing from your system

To enable intl extension follow the instructions below.

You need enable extension by uncommenting the following line extension=php_intl.dll in the C:\xampp\php\php.ini file. Once you uncomment the extension=php_intl.dll, then you must restart apache server using XAMPP control panel.

//about line 998
;extension=php_intl.dll 
change as
extension=php_intl.dll

(Note: php.ini file mostly in the following directory C:\xampp\php)

Restart xampp

How to properly export an ES6 class in Node 4?

Use

// aspect-type.js
class AspectType {

}

export default AspectType;

Then to import it

// some-other-file.js
import AspectType from './aspect-type';

Read http://babeljs.io/docs/learn-es2015/#modules for more details

Check if checkbox is checked with jQuery

You can try this:

<script>
function checkAllCheckBox(value)
{
   if($('#select_all_').is(':checked')){
   $(".check_").attr ( "checked" ,"checked" );
    }
    else
    {
        $(".check_").removeAttr('checked');
    }

 }

</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />


<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

jQuery: Uncheck other checkbox on one checked

$('.cw2').change(function () {
    if ($('input.cw2').filter(':checked').length >= 1) {
        $('input.cw2').not(this).prop('checked', false);
    } 
});


$('td, input').prop(function (){
    $(this).css({ 'background-color': '#DFD8D1' });
    $(this).addClass('changed');
});

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

java.net.SocketTimeoutException: Read timed out under Tomcat

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.

Get the value of a dropdown in jQuery

The best way is to use:

$("#yourid option:selected").text();

Depending on the requirement, you could also use this way:

var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()

YAML equivalent of array of objects in JSON

TL;DR

You want this:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.

JSON to YAML

Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Parsing this and converting it back to JSON yields the expected result:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

Laravel where on relationship object

With multiple joins, use something like this code:

$someId = 44;
Event::with(["owner", "participants" => function($q) use($someId){
    $q->where('participants.IdUser', '=', 1);
    //$q->where('some other field', $someId);
}])

What is the difference between canonical name, simple name and class name in Java Class?

this is best document I found describing getName(), getSimpleName(), getCanonicalName()

https://javahowtodoit.wordpress.com/2014/09/09/java-lang-class-what-is-the-difference-between-class-getname-class-getcanonicalname-and-class-getsimplename/

// Primitive type
int.class.getName();          // -> int
int.class.getCanonicalName(); // -> int
int.class.getSimpleName();    // -> int

// Standard class
Integer.class.getName();          // -> java.lang.Integer
Integer.class.getCanonicalName(); // -> java.lang.Integer
Integer.class.getSimpleName();    // -> Integer

// Inner class
Map.Entry.class.getName();          // -> java.util.Map$Entry
Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
Map.Entry.class.getSimpleName();    // -> Entry     

// Anonymous inner class
Class<?> anonymousInnerClass = new Cloneable() {}.getClass();
anonymousInnerClass.getName();          // -> somepackage.SomeClass$1
anonymousInnerClass.getCanonicalName(); // -> null
anonymousInnerClass.getSimpleName();    // -> // An empty string

// Array of primitives
Class<?> primitiveArrayClass = new int[0].getClass();
primitiveArrayClass.getName();          // -> [I
primitiveArrayClass.getCanonicalName(); // -> int[]
primitiveArrayClass.getSimpleName();    // -> int[]

// Array of objects
Class<?> objectArrayClass = new Integer[0].getClass();
objectArrayClass.getName();          // -> [Ljava.lang.Integer;
objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
objectArrayClass.getSimpleName();    // -> Integer[]

Interfaces — What's the point?

If I am working on an API to draw shapes, I may want to use DirectX or graphic calls, or OpenGL. So, I will create an interface, which will abstract my implementation from what you call.

So you call a factory method: MyInterface i = MyGraphics.getInstance(). Then, you have a contract, so you know what functions you can expect in MyInterface. So, you can call i.drawRectangle or i.drawCube and know that if you swap one library out for another, that the functions are supported.

This becomes more important if you are using Dependency Injection, as then you can, in an XML file, swap implementations out.

So, you may have one crypto library that can be exported that is for general use, and another that is for sale only to American companies, and the difference is in that you change a config file, and the rest of the program isn't changed.

This is used a great deal with collections in .NET, as you should just use, for example, List variables, and don't worry whether it was an ArrayList or LinkedList.

As long as you code to the interface then the developer can change the actual implementation and the rest of the program is left unchanged.

This is also useful when unit testing, as you can mock out entire interfaces, so, I don't have to go to a database, but to a mocked out implementation that just returns static data, so I can test my method without worrying if the database is down for maintenance or not.

Call method when home button pressed

use onPause() method to do what you want to do on home button.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

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

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

How to set root password to null

Wanted to put my own 2cents in here bcuz the above answers did not work for me. On centos 7, mysql community v8, shell is bash.

The correct commands would be as follows:

# start mysql without password checking
systemctl stop mysqld 2>/dev/null
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables" &&
systemctl start mysqld

# set default password to nothing
mysql -u root mysql <<- 'EOF'
    FLUSH PRIVILEGES;
    UNINSTALL COMPONENT 'file://component_validate_password';
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '';
    FLUSH PRIVILEGES;
    INSTALL COMPONENT 'file://component_validate_password';
EOF

# restart mysql normally
systemctl restart mysqld

then you can login without password:

mysql -u root

How exactly does <script defer="defer"> work?

A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async

The defer and async attributes must not be specified if the src attribute is not present.


There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.


The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.


If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:

The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

How to place a file on classpath in Eclipse?

Just to add. If you right-click on an eclipse project and select Properties, select the Java Build Path link on the left. Then select the Source Tab. You'll see a list of all the java source folders. You can even add your own. By default the {project}/src folder is the classpath folder.

How best to determine if an argument is not sent to the JavaScript function

There are significant differences. Let's set up some test cases:

var unused; // value will be undefined
Test("test1", "some value");
Test("test2");
Test("test3", unused);
Test("test4", null);
Test("test5", 0);
Test("test6", "");

With the first method you describe, only the second test will use the default value. The second method will default all but the first (as JS will convert undefined, null, 0, and "" into the boolean false. And if you were to use Tom's method, only the fourth test will use the default!

Which method you choose really depends on your intended behavior. If values other than undefined are allowable for argument2, then you'll probably want some variation on the first; if a non-zero, non-null, non-empty value is desired, then the second method is ideal - indeed, it is often used to quickly eliminate such a wide range of values from consideration.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Do I commit the package-lock.json file created by npm 5?

To the people complaining about the noise when doing git diff:

git diff -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'

What I did was use an alias:

alias gd="git diff --ignore-all-space --ignore-space-at-eol --ignore-space-change --ignore-blank-lines -- . ':(exclude)*package-lock.json' -- . ':(exclude)*yarn.lock'"

To ignore package-lock.json in diffs for the entire repository (everyone using it), you can add this to .gitattributes:

package-lock.json binary
yarn.lock binary

This will result in diffs that show "Binary files a/package-lock.json and b/package-lock.json differ whenever the package lock file was changed. Additionally, some Git services (notably GitLab, but not GitHub) will also exclude these files (no more 10k lines changed!) from the diffs when viewing online when doing this.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

Disable if there is any anti-virus extension is installed on the browser. In my case, the anti-virus extension was the culprit.

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

WhatsApp API (java/python)

WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI

Hope this helps

What does the PHP error message "Notice: Use of undefined constant" mean?

Insert single quotes.

Example

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']); 

How to get the unix timestamp in C#

There is a ToUnixTimeMilliseconds for DateTimeOffset in System

You can write similar method for DateTime:

public static long ToUnixTimeSeconds(this DateTime value)
{
    return value.Ticks / 10000000L - 62135596800L;
}

10000000L - converting ticks to seconds

62135596800L - converting 01.01.01 to 01.01.1978

There is no problem with Utc and leaks

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

As far as the best algorithm goes you probably have it right. I would recommend that you unravel the recursive function and use a stack of your own (remember a stack overflow is the end of the world in a .Net 2.0+ app, the exception can not be caught IIRC).

The most important thing is that if you are using it in any form of a UI put it on a worker thread that signals the UI thread with updates.

Scatter plots in Pandas/Pyplot: How to plot by category

This is simple to do with Seaborn (pip install seaborn) as a oneliner

sns.scatterplot(x_vars="one", y_vars="two", data=df, hue="key1") :

import seaborn as sns
import pandas as pd
import numpy as np
np.random.seed(1974)

df = pd.DataFrame(
    np.random.normal(10, 1, 30).reshape(10, 3),
    index=pd.date_range('2010-01-01', freq='M', periods=10),
    columns=('one', 'two', 'three'))
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8)

sns.scatterplot(x="one", y="two", data=df, hue="key1")

enter image description here

Here is the dataframe for reference:

enter image description here

Since you have three variable columns in your data, you may want to plot all pairwise dimensions with:

sns.pairplot(vars=["one","two","three"], data=df, hue="key1")

enter image description here

https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/ is another option.

How to convert the following json string to java object?

Check out Google's Gson: http://code.google.com/p/google-gson/

From their website:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.

Laravel Eloquent get results grouped by days

You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:

Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
    ->groupBy('date')
    ->get();

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

My issue with the loading of that bundle file was a bad symlink. So check the link, and replace it with a fresh one if needed. Everything fell into place at that point. Not sure how that happened, but it did. First time that a syntax error happened like that.

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Set environment variables from file of key/value pairs

Here's my variant:

  with_env() {
    (set -a && . ./.env && "$@")
  }

compared with the previous solutions:

  • it does not leak variables outside scope (values from .env are not exposed to caller)
  • does not clobber set options
  • returns exit code of the executed command
  • uses posix compatible set -a
  • uses . instead of source to avoid bashism
  • command is not invoked if .env loading fails
with_env rails console

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Why can't static methods be abstract in Java?

I also asked the same question , here is why

Since Abstract class says, it will not give implementation and allow subclass to give it

so Subclass has to override the methods of Superclass ,

RULE NO 1 - A static method cannot be overridden

Because static members and methods are compile time elements , that is why Overloading(Compile time Polymorphism) of static methods are allowed rather then Overriding (Runtime Polymorphism)

So , they cant be Abstract .

There is no thing like abstract static <--- Not allowed in Java Universe

Initializing a two dimensional std::vector

Let's say you want to initialize 2D vector, m*n, with initial value to be 0

we could do this

#include<iostream>
int main(){ 
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

Any way to break if statement in PHP?

No, there is no way to "break" an if block like you would inside loops.:(
So turn your test into a switch !

I wonder why nobody encouraged you to use switch statement since (even if you haven't to many test cases)
Do you think it's too verbose?

I would definitely go for it here

  switch($a){
    case 'test':
        # do stuff here ...
        if(/* Reason why you may break */){
           break; # this will prevent executing "echo 'yes';" statement
        }
        echo 'yes';  # ...           
        break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
    # default:
        # something else here  ..
        # break;
  }

To me Exceptions are meant to raise errors and not really to control execution flaw.
If the break behaviour you are trying to set is not about unexpected error(s), Exception handling is not the right solution here :/.

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String satr=scanner.nextLine();
    String newString = "";
    for (int i = 0; i < satr.length(); i++) {
        if (Character.isUpperCase(satr.charAt(i))) {
            newString+=Character.toLowerCase(satr.charAt(i));
        }else newString += Character.toUpperCase(satr.charAt(i));
    }
    System.out.println(newString);
}

Updating a JSON object using Javascript

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

How to reference static assets within vue javascript

A better solution would be

Adding some good practices and safity to @acdcjunior's answer, to use @ instead of ./

In JavaScript

require("@/assets/images/user-img-placeholder.png")

In JSX Template

<img src="@/assets/images/user-img-placeholder.png"/>

using @ points to the src directory.

using ~ points to the project root, which makes it easier to access the node_modules and other root level resources

Excel telling me my blank cells aren't blank

This works with numbers.

If your range is O8:O20, then in a nearby empty range (e.g. T8:T20) enter =O8/1 and fill down. This will give you a result of #VALUE for the 'empty' cells and your original number will remain as it was.

Then with the range T8:20 selected (CTL-* if it's not already) hit F5 and choose Special. From the Special dialogue, choose Errors and click OK. This will deselect your actual numbers leaving only the #VALUE cells selected. Delete them and you will have actual empty cells. Copy T8:T20 and paste back over O8:O20.

Essentially, since blank cells doesn't work, you need to convert the 'empty' cells into something that the Go To Special can latch on to. Any action that would convert into #VALUE would work, and other 'error' types should be supported as well.

Javascript to stop HTML5 video playback on modal window close

I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;

<script>
     var video = document.getElementById("myVideoPlayer");
     function stopVideo(){
          video.pause();
          video.currentTime = 0;
     }
</script>

Now you can use stopVideo() method to stop HTML5 video. Like,

$("#stop").on('click', function(){
    stopVideo();
});

limit text length in php and provide 'Read more' link

I have combine two different answers:

  1. Limit the characters
  2. Complete HTML missing tags

    $string = strip_tags($strHTML);
    $yourText = $strHTML;
    if (strlen($string) > 350) {
        $stringCut = substr($post->body, 0, 350);
        $doc = new DOMDocument();
        $doc->loadHTML($stringCut);
        $yourText = $doc->saveHTML();
    }
    $yourText."...<a href=''>View More</a>"
    

How to make a hyperlink in telegram without using bots?

In the new desktop versions, you can add hyperlink by pressing ctrl + k and typing links.

Applying an ellipsis to multiline text

May be this can help you guys. Multi Line Ellipses with tooltip hover. https://codepen.io/Anugraha123/pen/WOBdOb

<div>
     <p class="cards-values">Lorem ipsum dolor sit amet,   consectetur adipiscing elit. Nunc aliquet lorem commodo, semper mauris nec, suscipit nisi. Nullam laoreet massa sit amet leo malesuada imperdiet eu a augue. Sed ac diam quis ante congue volutpat non vitae sem. Vivamus a felis id dui aliquam tempus
      </p>
      <span class="tooltip"></span>
</div>

jQuery Date Picker - disable past dates

By setting startDate: new Date()

$('.date-picker').datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 1,
    ...
    startDate: new Date(),
});

Generate sha256 with OpenSSL and C++

Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:

char *str2sha256( const char *str, int length ) {
  int n;
  SHA256_CTX c;
  unsigned char digest[ SHA256_DIGEST_LENGTH ];
  char *out = (char*) malloc( 33 );

  SHA256_Init( &c );

  while ( length > 0 ) {
    if ( length > 512 ) SHA256_Update( &c, str, 512 );
    else SHA256_Update( &c, str, length );

    length -= 512;
    str += 512;
  }

  SHA256_Final ( digest, &c );

  for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
    snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );

  return out;
}

WCF Service, the type provided as the service attribute values…could not be found

I changed the output path of the service. it should be inside bin folder of the service project. Once I put the output path back to bin, it worked.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

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

It means what type of response you want to send to client, some content types like :

 res.setContentType("image/gif");
 res.setContentType("application/pdf");
 res.setContentType("application/zip");

Console output in a Qt GUI app?

No way to output a message to console when using QT += gui.

fprintf(stderr, ...) also can't print output.

Use QMessageBox instead to show the message.

PDO Prepared Inserts multiple rows in single query

Multiple Values Insert with PDO Prepared Statements

Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts.

$datafields = array('fielda', 'fieldb', ... );

$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);

more data values or you probably have a loop that populates data.

With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.

insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....

That is basically how we want the insert statement to look like.

Now, the code:

function placeholders($text, $count=0, $separator=","){
    $result = array();
    if($count > 0){
        for($x=0; $x<$count; $x++){
            $result[] = $text;
        }
    }

    return implode($separator, $result);
}

$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
    $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    $insert_values = array_merge($insert_values, array_values($d));
}

$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " .
       implode(',', $question_marks);

$stmt = $pdo->prepare ($sql);
$stmt->execute($insert_values);
$pdo->commit();

Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.

Generating random whole numbers in JavaScript in a specific range?

The other answers don't account for the perfectly reasonable parameters of 0 and 1. Instead you should use the round instead of ceil or floor:

function randomNumber(minimum, maximum){
    return Math.round( Math.random() * (maximum - minimum) + minimum);
}

console.log(randomNumber(0,1));  # 0 1 1 0 1 0
console.log(randomNumber(5,6));  # 5 6 6 5 5 6
console.log(randomNumber(3,-1)); # 1 3 1 -1 -1 -1

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

First check your imports, when you use session, transaction it should be org.hibernate and remove @Transactinal annotation. and most important in Entity class if you have used @GeneratedValue(strategy=GenerationType.AUTO) or any other then at the time of model object creation/entity object creation should not create id. final conclusion is if you want pass id filed i.e PK then remove @GeneratedValue from entity class.

ERROR Android emulator gets killed

goto tools>android>sdkmanager and update emulator and install related API level.It worked for me

Border length smaller than div width?

I did something like this in my project. I would like to share it here. You can add another div as a child and give it a border with small width and place it left, centre or right with usual CSS

HTML code:

    <div>
        content 
        <div class ="ac-brdr"></div>
    </div>

CSS as below:

   .active {
    color: magneta;
  }
   .active .ac-brdr {
        width: 20px;
        margin: 0 auto;
        border-bottom: 1px solid magneta;
  }

How do I float a div to the center?

Give the DIV a specific with in percentage or pixels and center it using CSS margin property.

HTML

<div id="my-main-div"></div>

CSS

#my-main-div { margin: 0 auto; }

enjoy :)

How to set-up a favicon?

With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.

You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.

You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).

One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :

<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">

In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">

How to coerce a list object to type 'double'

If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).

display HTML page after loading complete

put an overlay on the page

#loading-mask {
    background-color: white;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999;
}

and then delete that element in a window.onload handler or, hide it

window.onload=function() {
    document.getElementById('loading-mask').style.display='none';
}

Of course you should use your javascript library (jquery,prototype..) specific onload handler if you are using a library.

cocoapods - 'pod install' takes forever

you can run

pod install --verbose 

to see what's going on behind the scenes.. at least you'll know where it's stuck at (it could be a git clone operation that's taking too long because of your slow network etc)

to have an even better idea of why it seems to be stuck (running verbose can get you something like this

-> Installing Typhoon (2.2.1)
 > GitHub download
 > Creating cache git repo (~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92)
 > Cloning to Pods folder
       $ /usr/bin/git clone https://github.com/typhoon-framework/Typhoon.git ~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92 --mirror
       Cloning into bare repository '~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92'...

is to find out the size of the git repo you're cloning.. if you're cloning from github.. you can use this format:

/repos/:user/:repo

so, for example, to find out about the above repo type

https://api.github.com/repos/typhoon-framework/Typhoon

and the returned JSON will have a size key, value. so the above returned

"size": 94014,

which is approx 90mb. no wonder it's taking forever! (btw.. by the time I wrote this.. it just finished.. ha!)


update: one common thing that cocoa pods do before it even starts downloading the dependencies listed in your podfile, is to download/update its own repo (they call it Setting up Cocoapods Master repo.. look at this:

pod install --verbose

Analyzing dependencies

Updating spec repositories
  $ /usr/bin/git rev-parse  >/dev/null 2>&1
  $ /usr/bin/git ls-remote
  From https://github.com/CocoaPods/Specs.git
  09b0e7431ab82063d467296904a85d72ed40cd73  HEAD
  ..

the bad news is that if you follow the above procedure to find out how big the cocoa pod repo is.. you'll get this: "size": 614373,.. which is a lot.

so to get a more accurate way of knowing how long it takes to just install your own repo.. you can set up the cocoa pods master repo separately by using pod setup:

$ pod help setup
Usage:

$ pod setup

  Creates a directory at `~/.cocoapods/repos` which will hold your spec-repos.
  This is where it will create a clone of the public `master` spec-repo from:

      https://github.com/CocoaPods/Specs

  If the clone already exists, it will ensure that it is up-to-date.

then running pod install

How to Call a JS function using OnClick event

You could use addEventListener to add as many listeners as you want.

  document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 

Also add script tag after the element to make sure Save element is loaded at the time when script runs

Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 
});

example

Converting string to tuple without splitting characters

You can use the following solution:

s="jack"

tup=tuple(s.split(" "))

output=('jack')

Debug JavaScript in Eclipse

JavaScript is executed in the browser, which is pretty far removed from Eclipse. Eclipse would have to somehow hook into the browser's JavaScript engine to debug it. Therefore there's no built-in debugging of JavaScript via Eclipse, since JS isn't really its main focus anyways.

However, there are plug-ins which you can install to do JavaScript debugging. I believe the main one is the AJAX Toolkit Framework (ATF). It embeds a Mozilla browser in Eclipse in order to do its debugging, so it won't be able to handle cross-browser complications that typically arise when writing JavaScript, but it will certainly help.

Unfinished Stubbing Detected in Mockito

You're nesting mocking inside of mocking. You're calling getSomeList(), which does some mocking, before you've finished the mocking for MyMainModel. Mockito doesn't like it when you do this.

Replace

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}

with

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    List<SomeModel> someModelList = getSomeList();
    Mockito.when(mainModel.getList()).thenReturn(someModelList);
}

To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.

Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when method reads the last of these invocations off the list and records this invocation in the OngoingStubbing object it returns.

The line

Mockito.when(mainModel.getList()).thenReturn(someModelList);

causes the following interactions with Mockito:

  • Mock method mainModel.getList() is called,
  • Static method when is called,
  • Method thenReturn is called on the OngoingStubbing object returned by the when method.

The thenReturn method can then instruct the mock it received via the OngoingStubbing method to handle any suitable call to the getList method to return someModelList.

In fact, as Mockito can't see your code, you can also write your mocking as follows:

mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);

This style is somewhat less clear to read, especially since in this case the null has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.

However, the line

Mockito.when(mainModel.getList()).thenReturn(getSomeList());

causes the following interactions with Mockito:

  1. Mock method mainModel.getList() is called,
  2. Static method when is called,
  3. A new mock of SomeModel is created (inside getSomeList()),
  4. Mock method model.getName() is called,

At this point Mockito gets confused. It thought you were mocking mainModel.getList(), but now you're telling it you want to mock the model.getName() method. To Mockito, it looks like you're doing the following:

when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);

This looks silly to Mockito as it can't be sure what you're doing with mainModel.getList().

Note that we did not get to the thenReturn method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList() method.

Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.

Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:

3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

In Git, what is the difference between origin/master vs origin master?

I suggest merging develop and master with that command

git checkout master

git merge --commit --no-ff --no-edit develop

For more information, check https://git-scm.com/docs/git-merge

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.

Be sure you fully understand the security issues before using this as a solution.

You can add below code in /config/mail.php ( tested and worked on laravel 5.1, 5.2, 5.4 )

'stream' => [
   'ssl' => [
      'allow_self_signed' => true,
      'verify_peer' => false,
      'verify_peer_name' => false,
   ],
],

How to select specified node within Xpath node sets by index with Selenium?

This is a FAQ:

//someName[3]

means: all someName elements in the document, that are the third someName child of their parent -- there may be many such elements.

What you want is exactly the 3rd someName element:

(//someName)[3]

Explanation: the [] has a higher precedence (priority) than //. Remember always to put expressions of the type //someName in brackets when you need to specify the Nth node of their selected node-list.

Efficient iteration with index in Scala

Actually, scala has old Java-style loops with index:

scala> val xs = Array("first","second","third")
xs: Array[java.lang.String] = Array(first, second, third)

scala> for (i <- 0 until xs.length)
     | println("String # " + i + " is "+ xs(i))

String # 0 is first
String # 1 is second
String # 2 is third

Where 0 until xs.length or 0.until(xs.length) is a RichInt method which returns Range suitable for looping.

Also, you can try loop with to:

scala> for (i <- 0 to xs.length-1)
     | println("String # " + i + " is "+ xs(i))
String # 0 is first
String # 1 is second
String # 2 is third

Best way to check function arguments?

The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.

The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.

TortoiseSVN icons overlay not showing after updating to Windows 10

If you are using other version control software, it may be in conflict. In my case, uninstalling Plastic SCM restored Tortoise SVN icons.

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

Add comma to numbers every three digits

@Paul Creasey had the simplest solution as the regex, but here it is as a simple jQuery plugin:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

You could then use it like this:

$("span.numbers").digits();

The Role Manager feature has not been enabled

You can do this by reading from the boolean property at:

System.Web.Security.Roles.Enabled

This is a direct read from the enabled attribute of the roleManager element in the web.config:

<configuration>
  <system.web>
    <roleManager enabled="true" />
  </system.web>
</configuration>


Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

How do I set up curl to permanently use a proxy?

Many UNIX programs respect the http_proxy environment variable, curl included. The format curl accepts is [protocol://]<host>[:port].

In your shell configuration:

export http_proxy http://proxy.server.com:3128

For proxying HTTPS requests, set https_proxy as well.

Curl also allows you to set this in your .curlrc file (_curlrc on Windows), which you might consider more permanent:

http_proxy=http://proxy.server.com:3128

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

How do I add a ToolTip to a control?

Drag a tooltip control from the toolbox onto your form. You don't really need to give it any properties other than a name. Then, in the properties of the control you wish to have a tooltip on, look for a new property with the name of the tooltip control you just added. It will by default give you a tooltip when the cursor hovers the control.

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

How to set 24-hours format for date on java?

tl;dr

The modern approach uses java.time classes.

Instant.now()                                        // Capture current moment in UTC.
       .truncatedTo( ChronoUnit.SECONDS )            // Lop off any fractional second.
       .plus( 8 , ChronoUnit.HOURS )                 // Add eight hours.
       .atZone( ZoneId.of( "America/Montreal" ) )    // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
       .format(                                      // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
           DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
                            .withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated. 
       )                                             // Returns a `String` object.

23/01/2017 15:34:56

java.time

FYI, the old Calendar and Date classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).

Instant

Capture the current moment in UTC with the Instant class.

Instant instantNow = Instant.now();

instant.toString(): 2017-01-23T12:34:56.789Z

If you want only whole seconds, without any fraction of a second, truncate.

Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );

instant.toString(): 2017-01-23T12:34:56Z

Math

The Instant class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit enum, an implementation of TemporalUnit.

instant = instant.plus( 8 , ChronoUnit.HOURS );

instant.toString(): 2017-01-23T20:34:56Z

ZonedDateTime

To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]

Generate string

You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter object.

Note that case matters in the letters of your formatting pattern. The Question’s code had hh which is for 12-hour time while uppercase HH is 24-hour time (0-23) in both java.time.DateTimeFormatter as well as the legacy java.text.SimpleDateFormat.

The formatting codes in java.time are similar to those in the legacy SimpleDateFormat but not exactly the same. Carefully study the class doc. Here, HH happens to work identically.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );

Automatic localization

Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String text by calling DateTimeFormatter.ofLocalizedDateTime.

And, by the way, be aware that time zone and Locale have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.

Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" );  // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
                                       .withLocale( Locale.CANADA_FRENCH );  // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );

instant.toString(): 2017-01-23T12:34:56Z

zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]

output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande


About java.time

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

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

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

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

Where to obtain the java.time classes?


Joda-Time

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

Joda-Time makes this kind of work much easier.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );

System.out.println( "laterAsText: " + laterAsText );

When run…

laterAsText: 19/12/2013 02:50:18

Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

It's all based on your requirement. if you are developing a small scale app and covers only specific region (target audience), you can choose BIGINT to store only numbers since VARCHAR consumes more byte than BIGINT ( having optimal memory usage design matters ). but if you are developing a large scale app and targets global users and you have enough database capabilities to store data, you can definitely choose VARCHAR.

Check if object value exists within a Javascript array of objects and if not add a new object to array

Let's assume we have an array of objects and you want to check if value of name is defined like this,

let persons = [ {"name" : "test1"},{"name": "test2"}];

if(persons.some(person => person.name == 'test1')) {
    ... here your code in case person.name is defined and available
}

Returning a value even if no result

You could include count(id). That will always return.

select count(field1), field1 from table where id = 123 limit 1;

http://sqlfiddle.com/#!2/64c76/4

Make an existing Git branch track a remote branch?

Make sure you run :

git config push.default tracking

to be able to push trouble free

How to loop through all the properties of a class?

Here's another way to do it, using a LINQ lambda:

C#:

SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));

VB.NET:

SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))

How to determine equality for two JavaScript objects?

Short functional deepEqual implementation:

function deepEqual(x, y) {
  return (x && y && typeof x === 'object' && typeof y === 'object') ?
    (Object.keys(x).length === Object.keys(y).length) &&
      Object.keys(x).reduce(function(isEqual, key) {
        return isEqual && deepEqual(x[key], y[key]);
      }, true) : (x === y);
}

Edit: version 2, using jib's suggestion and ES6 arrow functions:

function deepEqual(x, y) {
  const ok = Object.keys, tx = typeof x, ty = typeof y;
  return x && y && tx === 'object' && tx === ty ? (
    ok(x).length === ok(y).length &&
      ok(x).every(key => deepEqual(x[key], y[key]))
  ) : (x === y);
}

Laravel migration table field's type change

The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.

I had to it like this:

public function up()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn  LONGTEXT;');
}

public function down()
{
    DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}

This could be a Doctrine issue. More information here.

Another way to do it is to use the string() method, and set the value to the text type max length:

    Schema::table('mytable', function ($table) {
        // Will set the type to LONGTEXT.
        $table->string('mycolumn', 4294967295)->change();
    });

How to validate an e-mail address in swift?

Since there are so many weird top level domain name now, I stop checking the length of the top domain...

Here is what I use:

extension String {

    func isEmail() -> Bool {
        let emailRegEx = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"
        return NSPredicate(format:"SELF MATCHES %@", emailRegEx).evaluateWithObject(self)
    } 
}

How do I activate C++ 11 in CMake?

I think just these two lines are enough.

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

What's the correct way to communicate between controllers in AngularJS?

Since defineProperty has browser compatibility issue, I think we can think about using a service.

angular.module('myservice', [], function($provide) {
    $provide.factory('msgBus', ['$rootScope', function($rootScope) {
        var msgBus = {};
        msgBus.emitMsg = function(msg) {
        $rootScope.$emit(msg);
        };
        msgBus.onMsg = function(msg, scope, func) {
            var unbind = $rootScope.$on(msg, func);
            scope.$on('$destroy', unbind);
        };
        return msgBus;
    }]);
});

and use it in controller like this:

  • controller 1

    function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.emitMsg('somemsg')
        }
    }
    
  • controller 2

    function($scope, msgBus) {
        msgBus.onMsg('somemsg', $scope, function() {
            // your logic
        });
    }
    

Limiting Python input strings to certain characters and lengths

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

print "Your input was:", input_str

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

OK, here are the things that come into mind:

  • Your WCF service presumably running on IIS must be running under the security context that has the privilege that calls the Web Service. You need to make sure in the app pool with a user that is a domain user - ideally a dedicated user.
  • You can not use impersonation to use user's security token to pass back to ASMX using impersonation since my WCF web service calls another ASMX web service, installed on a **different** web server
  • Try changing Ntlm to Windows and test again.

OK, a few words on impersonation. Basically it is a known issue that you cannot use the impersonation tokens that you got to one server, to pass to another server. The reason seems to be that the token is a kind of a hash using user's password and valid for the machine generated from so it cannot be used from the middle server.


UPDATE

Delegation is possible under WCF (i.e. forwarding impersonation from a server to another server). Look at this topic here.

css padding is not working in outlook

Avoid paddings and margins in newsletters, some email clients will ignore this properties.

You can use empty tr and td as was suggested (but this will result in a lot of html), or you can use borders with the same border color as the background of the email. so, instead of padding-top: 40px you can use border-top: 40px solid #ffffff (assuming that the background color of the email is #ffffff)

I've tested this solution in gmail (and gmail for business), yahoo mail, outlook web, outlook desktop, thunderbird, apple mail and more. As far as I can tell, border property is pretty safe to use everywhere.

Example:


<!-- With paddings: WON'T WORK IN ALL EMAIL CLIENTS! -->
<table>

    <tr>

        <td style="padding: 10px 10px 10px 10px">
            <!-- Content goes here -->
        </td>

    </tr>

</table>


<!-- Same result with borders and same border color of the background -->
<table>

    <tr>

        <td style="border: solid 10px #ffffff">
           <!-- Content goes here -->
        </td>

    </tr>

</table>


<!-- Same result using empty td/tr. (A lot more html than borders, get messy on large emails) -->
<table>

    <tr>
        <td colspan="3" height="10" style="height: 10px; line-height: 1px">&nbsp;</td>
    </tr>


    <tr>

        <td width="10" style="width: 10px; line-height: 1px">&nbsp;</td>

        <td><!--Content goes here--></td>

        <td width="10" style="width: 10px; line-height: 1px">&nbsp;</td>

    </tr>


    <tr>
        <td colspan="3" height="10" style="height: 10px; line-height: 1px">&nbsp;</td>
    </tr>

</table>
<!-- With tr/td every property is needed. height must be setted both as attribute and style, same with width, line-height must be setted JIC default value is greater than actual height and without the &nbsp; some email clients won't render the column because is empty. You can remove the colspan and still will work, but is annoying when inspecting the element in browser not to see a perfect square table -->

In addition, here is an excelent guide to make responsive newsletters without mediaqueries. The emails really works everywhere:

https://webdesign.tutsplus.com/tutorials/creating-a-future-proof-responsive-email-without-media-queries--cms-23919

And always remember to make styles inline:

https://inliner.cm/

To test emails, here is a good resource:

https://putsmail.com/

Finally, for doubts about css support in email clients you can go here:

https://templates.mailchimp.com/resources/email-client-css-support/

or here:

https://www.campaignmonitor.com/css/

How can I check that JButton is pressed? If the isEnable() is not work?

JButton#isEnabled changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.

When a JButton is pressed, it fires a actionPerformed event.

You are receiving Add button is pressed when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.

Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener it would always be false, as the button will only be in the pressed state while the add button's ActionListeners are being called.

Based on all this information, I would suggest you might want to consider using a JCheckBox which you can then use JCheckBox#isSelected to determine if it has being checked or not.

Take a closer look at How to Use Buttons for more details

What is <scope> under <dependency> in pom.xml for?

added good images with explain scopes

enter image description here

enter image description here

Sorting a vector of custom objects

You are on the right track. std::sort will use operator< as comparison function by default. So in order to sort your objects, you will either have to overload bool operator<( const T&, const T& ) or provide a functor that does the comparison, much like this:

 struct C {
    int i;
    static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
 };

 bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }

 std::vector<C> values;

 std::sort( values.begin(), values.end() ); // uses operator<
 std::sort( values.begin(), values.end(), C::before );

The advantage of the usage of a functor is that you can use a function with access to the class' private members.

How do I center text vertically and horizontally in Flutter?

Text alignment center property setting only horizontal alignment.

enter image description here

I used below code to set text vertically and horizontally center.

enter image description here

Code:

      child: Center(
        child: Text(
          "Hello World",
          textAlign: TextAlign.center,
        ),
      ),

Temporary tables in stored procedures

Nope. Independent instances of the temporary table will be created per each connection.

How to sort a HashSet?

You can use a TreeSet instead.

How can I create a temp file with a specific extension with .NET?

In my opinion, most answers proposed here as sub-optimal. The one coming closest is the original one proposed initially by Brann.

A Temp Filename must be

  • Unique
  • Conflict-free (not already exist)
  • Atomic (Creation of Name & File in the same operation)
  • Hard to guess

Because of these requirements, it is not a godd idea to program such a beast on your own. Smart People writing IO Libraries worry about things like locking (if needed) etc. Therefore, I see no need to rewrite System.IO.Path.GetTempFileName().

This, even if it looks clumsy, should do the job:

//Note that this already *creates* the file
string filename1 = System.IO.Path.GetTempFileName()
// Rename and move
filename = filename.Replace(".tmp", ".csv");
File.Move(filename1 , filename);

How do I disable directory browsing?

Try this in .htaccess:

IndexIgnore *.jpg

Populating a ComboBox using C#

Create a class Language

public class Language
{
     public string Name{get;set;}
     public string Value{get;set;}
     public override string ToString() { return this.Name;}
}

Then, add as many language to the combobox that you want:

yourCombobox.Items.Add(new Language{Name="English",Value="En"});

Collision resolution in Java HashMap

First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

Although, from Java 8 , the linked lists are replaced with trees (O(log n))

HttpContext.Current.User.Identity.Name is Empty

In addition to "answered Mar 28 '11 at 12:27Bryan Bedard"

In case that the solution doesn't work, you have to enable Windows Authentication in iss manager. How to do that:

1.To start IIS Manager from the Run dialog box: On the Start menu, click All Programs, click Accessories, and then click Run. In the Open box, type inetmgr and then click OK.

2.In the Connections pane, expand the server name, expand Sites, and go to the level in the hierarchy pane that you want to configure, and then click the Web site or Web application. 3. Scroll to the IIS section in the Home pane, and then double-click Authentication.

4.In the Authentication pane, select Anonymous Authentication, and then click Disable. enter image description here

  1. In the Authentication pane, select Windows Authentication, and then click Enable.

Reference

Uncaught SyntaxError: Unexpected token :

If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below

<br />
<b>Deprecated</b>:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}

Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start

error_reporting(E_ERROR | E_PARSE);

To view, right click on page, "view source" and then examine complete html to spot this error.

How to select all and copy in vim?

ggVG 

will select from beginning to end

Map<String, String>, how to print both the "key string" and "value string" together

final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
        .stream()
        //depending on how you want to join K and V use different delimiter
        .map(entry -> 
        String.join(":", entry.getKey(),entry.getValue()))
        .forEach(System.out::println);

How to add conditional attribute in Angular 2?

you can use this.

<span [attr.checked]="val? true : false"> </span>

How to set the current working directory?

Perhaps this is what you are looking for:

import os
os.chdir(default_path)

Internet Explorer 11 detection

A pretty safe & concise way to detect IE 11 only is

if(window.msCrypto) {
    // I'm IE11 for sure
}

or something like this

var IE11= !!window.msCrypto;

msCrypto is a prefixed version of the window.crypto object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto

How to convert integer to decimal in SQL Server query?

SELECT height/10.0 AS HeightDecimal FROM dbo.whatever;

If you want a specific precision scale, then say so:

SELECT CONVERT(DECIMAL(16,4), height/10.0) AS HeightDecimal
  FROM dbo.whatever;

Purge Kafka Topic

From kafka 1.1

Purge a topic

bin/kafka-configs.sh --zookeeper localhost:2181 --alter --entity-type topics --entity-name tp_binance_kline --add-config retention.ms=100

wait 1 minute, to be secure that kafka purge the topic remove the configuration, and then go to default value

bin/kafka-configs.sh --zookeeper localhost:2181 --alter --entity-type topics --entity-name tp_binance_kline --delete-config retention.ms

Calculating a 2D Vector's Cross Product

Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:

| a x b | = |a| . |b| . sine(theta)

or

sine(theta) = | a x b | / (|a| . |b|)

So, in implementation 1 above, if a and b are known in advance to be unit vectors then the result of that function is exactly that sine() value.

What is the fastest factorial function in JavaScript?

var factorial = function(numToBeFactored)
    {
        if (numToBeFactored == 0)
                return 1;
            var numLength = 0;
            var numBeingFactored = 1;
        /*goes through the loop numToBeFactored times and each time multiplies numBeingFactored by one less than the last loop*/
            for (numLength = 0; numLength < numToBeFactored; numLength++)
            {
                numBeingFactored *= (numToBeFactored - numLength);
            }
            return numBeingFactored;
    };

Subtract two dates in Java

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date2));

long diff = d2.getTime() - d1.getTime();

System.out.println("Difference between  " + d1 + " and "+ d2+" is "
        + (diff / (1000 * 60 * 60 * 24)) + " days.");

CGContextDrawImage draws image upside down when passed UIImage.CGImage

During the course of my project I jumped from Kendall's answer to Cliff's answer to solve this problem for images that are loaded from the phone itself.

In the end I ended up using CGImageCreateWithPNGDataProvider instead:

NSString* imageFileName = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"clockdial.png"];

return CGImageCreateWithPNGDataProvider(CGDataProviderCreateWithFilename([imageFileName UTF8String]), NULL, YES, kCGRenderingIntentDefault);

This doesn't suffer from the orientation issues that you would get from getting the CGImage from a UIImage and it can be used as the contents of a CALayer without a hitch.

Auto logout with Angularjs based on idle user

There should be different ways to do it and each approach should fit a particular application better than another. For most apps, you can simply just handle key or mouse events and enable/disable a logout timer appropriately. That said, on the top of my head, a "fancy" AngularJS-y solution is monitoring the digest loop, if none has been triggered for the last [specified duration] then logout. Something like this.

app.run(function($rootScope) {
  var lastDigestRun = new Date();
  $rootScope.$watch(function detectIdle() {
    var now = new Date();
    if (now - lastDigestRun > 10*60*60) {
       // logout here, like delete cookie, navigate to login ...
    }
    lastDigestRun = now;
  });
});

Hidden TextArea

<textarea name="hide" style="display:none;"></textarea>

This sets the css display property to none, which prevents the browser from rendering the textarea.

PHP: trying to create a new line with "\n"

$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"&lt;br/>";

Remove part of string after "."

If the string should be of fixed length, then substr from base R can be used. But, we can get the position of the . with regexpr and use that in substr

substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"   

Using lodash to compare jagged arrays (items existence without order)

By 'the same' I mean that there are is no item in array1 that is not contained in array2.

You could use flatten() and difference() for this, which works well if you don't care if there are items in array2 that aren't in array1. It sounds like you're asking is array1 a subset of array2?

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];

function isSubset(source, target) {
    return !_.difference(_.flatten(source), _.flatten(target)).length;
}

isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true

Proxy Error 502 : The proxy server received an invalid response from an upstream server

Add this into your httpd.conf file

Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore