Programs & Examples On #Domready

Comparing date part only without comparing time in JavaScript

This works for me:

 export default (chosenDate) => {
  const now = new Date();
  const today = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
  const splitChosenDate = chosenDate.split('/');

  today.setHours(0, 0, 0, 0);
  const fromDate = today.getTime();
  const toDate = new Date(splitChosenDate[2], splitChosenDate[1] - 1, splitChosenDate[0]).getTime();

  return toDate < fromDate;
};

In accepted answer, there is timezone issue and in the other time is not 00:00:00

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

Converting Epoch time into the datetime

To convert your time value (float or int) to a formatted string, use:

time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
{
    public static string CompressToBase64(this string data)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
    }

    public static string DecompressFromBase64(this string data)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    }
    
    public static byte[] Compress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.CompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }

    public static byte[] Decompress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.DecompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }
    
    public static void CompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
        {
            stream.CopyTo(gZipStream);
            gZipStream.Flush();
        }
    }

    public static void DecompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
        {
            gZipStream.CopyTo(outputStream);
        }
    }
}

number_format() with MySQL

You can use

SELECT round(123.4566,2)  -> 123.46

PowerShell : retrieve JSON object by field value

This is my json data:

[
   {
      "name":"Test",
      "value":"TestValue"
   },
   {
      "name":"Test",
      "value":"TestValue"
   }
]

Powershell script:

$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json

foreach ($line in $data) {
     $line.name
}

How do I time a method's execution in Java?

In Spring framework we have a call called StopWatch (org.springframework.util.StopWatch)

//measuring elapsed time using Spring StopWatch
        StopWatch watch = new StopWatch();
        watch.start();
        for(int i=0; i< 1000; i++){
            Object obj = new Object();
        }
        watch.stop();
        System.out.println("Total execution time to create 1000 objects in Java using StopWatch in millis: "
                + watch.getTotalTimeMillis());

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

[Ljava.lang.Object; cannot be cast to

I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:

You need to frame your query like this

select entity from Entity as entity where ...

Also check such case, it perfectly works for me:

public List<User> findByRole(String role) {

    Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
    query.setString("role_name", role);
    @SuppressWarnings("unchecked")
    List<User> users = (List<User>) query.list();
    return users;
}

So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.

Extend contigency table with proportions (percentages)

I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.

set.seed(1234)

total_bill <- rnorm(50, 25, 3)
tip <- 0.15 * total_bill + rnorm(50, 0, 1)
sex <- rbinom(50, 1, 0.5)
smoker <- rbinom(50, 1, 0.3)
day <- ceiling(runif(50, 0,7))
time <- ceiling(runif(50, 0,3))
size <- 1 + rpois(50, 2)
my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
my.data

my.table <- table(my.data$smoker)

my.prop <- prop.table(my.table)

cbind(my.table, my.prop)

How to change collation of database, table, column?

if you want to update the default charset on a schema:

 ALTER SCHEMA MYSCHEMA DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;

Google Maps setCenter()

in your code, at line

map.setCenter(new GLatLng(lat, lon), 5);

the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?

I suggest you should change it to,

map.setCenter(new GLatLng(lat, lon));

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

The difference between the Runnable and Callable interfaces in Java

Callable interface declares call() method and you need to provide generics as type of Object call() should return -

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Runnable on the other hand is interface that declares run() method that is called when you create a Thread with the runnable and call start() on it. You can also directly call run() but that just executes the run() method is same thread.

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used 
     * to create a thread, starting the thread causes the object's 
     * <code>run</code> method to be called in that separately executing 
     * thread. 
     * <p>
     * The general contract of the method <code>run</code> is that it may 
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

To summarize few notable Difference are

  1. A Runnable object does not return a result whereas a Callable object returns a result.
  2. A Runnable object cannot throw a checked exception wheras a Callable object can throw an exception.
  3. The Runnable interface has been around since Java 1.0 whereas Callable was only introduced in Java 1.5.

Few similarities include

  1. Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another thread.
  2. Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.
  3. Both are functional interfaces and can be used in Lambda expressions since Java8.

Methods in ExecutorService interface are

<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);

How to create PDF files in Python

fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

This is an old post, but if IE is giving you trouble. Change your GET requests to POST and IE will no longer cache them.

I spent way too much time figuring this out the hard way. Hope it helps.

How do I format a number with commas in T-SQL?

For SQL Server before 2012 which does not include the FORMAT function, create this function:

CREATE FUNCTION FormatCurrency(@value numeric(30,2))
    RETURNS varchar(50)
    AS
    BEGIN
        DECLARE @NumAsChar VARCHAR(50)
        SET @NumAsChar = '$' + CONVERT(varchar(50), CAST(@Value AS money),1)
        RETURN @NumAsChar
    END 

select dbo.FormatCurrency(12345678) returns $12,345,678.00

Drop the $ if you just want commas.

convert double to int

Here is a complete example

class Example 
{    
  public static void Main() 
  {    
    double x, y; 
    int i; 

    x = 10.0; 
    y = 3.0; 

    // cast double to int, fractional component lost (Line to be replaced) 
    i = (int) (x / y); 
    Console.WriteLine("Integer outcome of x / y: " + i); 
  }    
}

If you want to round the number to the closer integer do the following:

i = (int) Math.Round(x / y); // Line replaced

Difference in make_shared and normal shared_ptr in C++

If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

you just need to reset dependencies in app.gradle file like old one as

androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'

to new one as

androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

How do I compare two Integers?

"equals" is it. To be on the safe side, you should test for null-ness:

x == y || (x != null && x.equals(y))

the x==y tests for null==null, which IMHO should be true.

The code will be inlined by the JIT if it is called often enough, so performance considerations should not matter.

Of course, avoiding "Integer" in favor of plain "int" is the best way, if you can.

[Added]

Also, the null-check is needed to guarantee that the equality test is symmetric -- x.equals(y) should by the same as y.equals(x), but isn't if one of them is null.

Detect Safari browser

User agent sniffing is really tricky and unreliable. We were trying to detect Safari on iOS with something like @qingu's answer above, it did work pretty well for Safari, Chrome and Firefox. But it falsely detected Opera and Edge as Safari.

So we went with feature detection, as it looks like as of today, serviceWorker is only supported in Safari and not in any other browser on iOS. As stated in https://jakearchibald.github.io/isserviceworkerready/

Support does not include iOS versions of third-party browsers on that platform (see Safari support).

So we did something like

if ('serviceWorker' in navigator) {
    return 'Safari';
}
else {
    return 'Other Browser';
}

Note: Not tested on Safari on MacOS.

Android - get children inside a View?

You can always access child views via View.findViewById() http://developer.android.com/reference/android/view/View.html#findViewById(int).

For example, within an activity / view:

...
private void init() {
  View child1 = findViewById(R.id.child1);
}
...

or if you have a reference to a view:

...
private void init(View root) {
  View child2 = root.findViewById(R.id.child2);
}

Push an associative item into an array in JavaScript

JavaScript has associative arrays.

Here is a working snippet.

_x000D_
_x000D_
<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>
_x000D_
_x000D_
_x000D_

They are simply called objects.

How should I unit test multithreaded code?

For J2E code, I've used SilkPerformer, LoadRunner and JMeter for concurrency testing of threads. They all do the same thing. Basically, they give you a relatively simple interface for administrating their version of the proxy server, required, in order to analyze the TCP/IP data stream, and simulate multiple users making simultaneous requests to your app server. The proxy server can give you the ability to do things like analyze the requests made, by presenting the whole page and URL sent to the server, as well as the response from the server, after processing the request.

You can find some bugs in insecure http mode, where you can at least analyze the form data that is being sent, and systematically alter that for each user. But the true tests are when you run in https (Secured Socket Layers). Then, you also have to contend with systematically altering the session and cookie data, which can be a little more convoluted.

The best bug I ever found, while testing concurrency, was when I discovered that the developer had relied upon Java garbage collection to close the connection request that was established at login, to the LDAP server, when logging in. This resulted in users being exposed to other users' sessions and very confusing results, when trying to analyze what happened when the server was brought to it's knees, barely able to complete one transaction, every few seconds.

In the end, you or someone will probably have to buckle down and analyze the code for blunders like the one I just mentioned. And an open discussion across departments, like the one that occurred, when we unfolded the problem described above, are most useful. But these tools are the best solution to testing multi-threaded code. JMeter is open source. SilkPerformer and LoadRunner are proprietary. If you really want to know whether your app is thread safe, that's how the big boys do it. I've done this for very large companies professionally, so I'm not guessing. I'm speaking from personal experience.

A word of caution: it does take some time to understand these tools. It will not be a matter of simply installing the software and firing up the GUI, unless you've already had some exposure to multi-threaded programming. I've tried to identify the 3 critical categories of areas to understand (forms, session and cookie data), with the hope that at least starting with understanding these topics will help you focus on quick results, as opposed to having to read through the entire documentation.

random.seed(): What does it do?

>>> random.seed(9001)   
>>> random.randint(1, 10)  
1     
>>> random.seed(9001)     
>>> random.randint(1, 10)    
1           
>>> random.seed(9001)          
>>> random.randint(1, 10)                 
1                  
>>> random.seed(9001)         
>>> random.randint(1, 10)          
1     
>>> random.seed(9002)                
>>> random.randint(1, 10)             
3

You try this.

Let's say 'random.seed' gives a value to random value generator ('random.randint()') which generates these values on the basis of this seed. One of the must properties of random numbers is that they should be reproducible. When you put same seed, you get the same pattern of random numbers. This way you are generating them right from the start. You give a different seed- it starts with a different initial (above 3).

Given a seed, it will generate random numbers between 1 and 10 one after another. So you assume one set of numbers for one seed value.

Sending JWT token in the headers with Postman

Somehow postman didn't work for me. I had to use a chrome extension called RESTED which did work.

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

What is the difference between a heuristic and an algorithm?

They find a solution suboptimally without any guarantee as to the quality of solution found, it is obvious that it makes sense to the development of heuristics only polynomial. The application of these methods is suitable to solve real world problems or large problems so awkward from the computational point of view that for them there is not even an algorithm capable of finding an approximate solution in polynomial time.

How to convert an Stream into a byte[] in C#?

Quick and dirty technique:

    static byte[] StreamToByteArray(Stream inputStream)
    {
        if (!inputStream.CanRead)
        {
            throw new ArgumentException(); 
        }

        // This is optional
        if (inputStream.CanSeek)
        {
            inputStream.Seek(0, SeekOrigin.Begin);
        }

        byte[] output = new byte[inputStream.Length];
        int bytesRead = inputStream.Read(output, 0, output.Length);
        Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
        return output;
    }

Test:

    static void Main(string[] args)
    {
        byte[] data;
        string path = @"C:\Windows\System32\notepad.exe";
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
        {
            data = StreamToByteArray(fs);
        }

        Debug.Assert(data.Length > 0);
        Debug.Assert(new FileInfo(path).Length == data.Length); 
    }

I would ask, why do you want to read a stream into a byte[], if you are wishing to copy the contents of a stream, may I suggest using MemoryStream and writing your input stream into a memory stream.

why is plotting with Matplotlib so slow?

This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:

import platform     # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
    # In my installations of Windows 7, it takes an inordinate amount of time to save
    # graphs as .svg files, so on that platform I've disabled the call that does so.
    # The first run of a script is still a little slow while everything is loaded in,
    # but execution times of subsequent runs are improved immensely.
    fig.savefig('figure_name.svg')

How do I deploy Node.js applications as a single executable file?

In addition to nexe, browserify can be used to bundle up all your dependencies as a single .js file. This does not bundle the actual node executable, just handles the javascript side. It too does not handle native modules. The command line options for pure node compilation would be browserify --output bundle.js --bare --dg false input.js.

Scala how can I count the number of occurrences in a list

scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)

scala> println(list.filter(_ == 2).size)
3

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I am using apache (xampp) on my dev environment and apache on the production, add:

errorDocument 404 /index.html

to the .htaccess solve for me this issue.

disable editing default value of text input

Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.

Sorry for my english

CSS transition between left -> right and top -> bottom positions

You can animate the position (top, bottom, left, right) and then subtract the element's width or height through a CSS transformation.

Consider:

_x000D_
_x000D_
$('.animate').on('click', function(){
  $(this).toggleClass("move");
})
_x000D_
     .animate {
        height: 100px;
        width: 100px;
        background-color: #c00;
        transition: all 1s ease;
        position: absolute;
        cursor: pointer;
        font: 13px/100px sans-serif;
        color: white;
        text-align: center;
      }

                               /* ? just to position things  */
      .animate.left   { left: 0;   top: 50%;  margin-top: -100px;}
      .animate.right  { right: 0;  top: 50%;  }
      .animate.top    { top: 0;    left: 50%; }
      .animate.bottom { bottom: 0; left: 50%; margin-left: -100px;}


      .animate.left.move {
        left: 100%; 
        transform: translate(-100%, 0);
      }

      .animate.right.move {
        right: 100%; 
        transform: translate(100%, 0);
      }

      .animate.top.move {
        top: 100%; 
        transform: translate(0, -100%);
      }

      .animate.bottom.move {
        bottom: 100%; 
        transform: translate(0, 100%);
      }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click to animate
<div class="animate left">left</div>
<div class="animate top">top</div>
<div class="animate bottom">bottom</div>
<div class="animate right">right</div>
_x000D_
_x000D_
_x000D_

And then animate depending on the position...

Is it possible to set a custom font for entire of application?

Yes, its possible to set the font to the entire application.

The easiest way to accomplish this is to package the desired font(s) with your application.

To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets.

You might, for example, create assets/fonts/ and put your TTF files in there.

public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);

Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}

Automatically resize images with browser size using CSS

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

for example :

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

and then any images you add simply using the img tag will be flexible

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

HashMap: One Key, multiple Values

HashMap – Single Key and Multiple Values Using List

Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values

    List<String> One = new ArrayList<String>();
    One.add("Apple");
    One.add("Aeroplane");

    // create list two and store values
    List<String> Two = new ArrayList<String>();
    Two.add("Bat");
    Two.add("Banana");

    // put values into map
    map.put("A", One);
    map.put("B", Two);
    map.put("C", Three);

How do I get a file extension in PHP?

Sorry... "Short Question; But NOT Short Answer"

Example 1 for PATH

$path = "/home/ali/public_html/wp-content/themes/chicken/css/base.min.css";
$name = pathinfo($path, PATHINFO_FILENAME);
$ext  = pathinfo($path, PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

Example 2 for URL

$url = "//www.example.com/dir/file.bak.php?Something+is+wrong=hello";
$url = parse_url($url);
$name = pathinfo($url['path'], PATHINFO_FILENAME);
$ext  = pathinfo($url['path'], PATHINFO_EXTENSION);
printf('<hr> Name: %s <br> Extension: %s', $name, $ext);

Output of example 1:

Name: base.min
Extension: css

Output of example 2:

Name: file.bak
Extension: php

References

  1. https://www.php.net/manual/en/function.pathinfo.php

  2. https://www.php.net/manual/en/function.realpath.php

  3. https://www.php.net/manual/en/function.parse-url.php

Using jQuery to build table rows from AJAX response(json)

Try this (DEMO link updated):

success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }

Fiddle DEMO WITH AJAX

Sequelize, convert entity to plain object

As CharlesA notes in his answer, .values() is technically deprecated, though this fact isn't explicitly noted in the docs. If you don't want to use { raw: true } in the query, the preferred approach is to call .get() on the results.

.get(), however, is a method of an instance, not of an array. As noted in the linked issue above, Sequelize returns native arrays of instance objects (and the maintainers don't plan on changing that), so you have to iterate through the array yourself:

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    }
}).success((sensors) => {
    const nodeData = sensors.map((node) => node.get({ plain: true }));
});

How to call JavaScript function instead of href in HTML

href is optional for a elements.

It's completely sufficient to use

<a onclick="ShowOld(2367,146986,2)">link text</a>

illegal character in path

Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.

The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.

Java ArrayList clear() function

ArrayList.clear(From Java Doc):

Removes all of the elements from this list. The list will be empty after this call returns

is there a css hack for safari only NOT chrome?

Note: If iOS-only is sufficient (if you're willing to sacrifice Safari desktop), then this works:

    @supports (-webkit-overflow-scrolling: touch) {
    /* CSS specific to iOS devices */ 
    }

What's the best mock framework for Java?

We are heavily using EasyMock and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.

Open directory using C

Some feedback on the segment of code, though for the most part, it should work...

void main(int c,char **args)
  • int main - the standard defines main as returning an int.
  • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)

Calling ASP.NET MVC Action Methods from JavaScript

Use jQuery ajax:

function AddToCart(id)
{
   $.ajax({
      url: 'urlToController',
      data: { id: id }
   }).done(function() {
      alert('Added'); 
   });
}

http://api.jquery.com/jQuery.ajax/

How to get the current directory of the cmdlet being executed

Get-Location will return the current location:

$Currentlocation = Get-Location

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

Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!

<meta property="article:author" content="https://www.facebook.com/mpatnode76">

But Pinterest wants to see something like this:

<meta property="article:author" content="Mike Patnode">

We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.

Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/

Path of currently executing powershell script

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}

What is your favorite C programming trick?

Two good source books for this sort of stuff are The Practice of Programming and Writing Solid Code. One of them (I don't remember which) says: Prefer enum to #define where you can, because enum gets checked by the compiler.

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Which TensorFlow and CUDA version combinations are compatible?

The compatibility table given in the tensorflow site does not contain specific minor versions for cuda and cuDNN. However, if the specific versions are not met, there will be an error when you try to use tensorflow.

For tensorflow-gpu==1.12.0 and cuda==9.0, the compatible cuDNN version is 7.1.4, which can be downloaded from here after registration.

You can check your cuda version using
nvcc --version

cuDNN version using
cat /usr/include/cudnn.h | grep CUDNN_MAJOR -A 2

tensorflow-gpu version using
pip freeze | grep tensorflow-gpu

UPDATE: Since tensorflow 2.0, has been released, I will share the compatible cuda and cuDNN versions for it as well (for Ubuntu 18.04).

  • tensorflow-gpu = 2.0.0
  • cuda = 10.0
  • cuDNN = 7.6.0

Java: Find .txt files in specified folder

import org.apache.commons.io.FileUtils;   

List<File> htmFileList = new ArrayList<File>();

for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
    htmFileList.add(file);
}

This is my latest code to add all text files from a directory

How to add scroll bar to the Relative Layout?

I used the

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout

and works perfectly

Copy all the lines to clipboard

On Ubuntu 12

you might try to install the vim-gnome package:

sudo apt-get install vim-gnome

I tried it, because vim --version told me that it would have the flag xterm_clipboard disabled (indicated by - ), which is needed in order to use the clipboard functionality.

-> installing the vim-gnome package on Ubuntu 12 also installed a console based version of vim, that has this option enabled (indicated by a + before the xterm_clipboard flag)

On Arch Linux

you may install vim-clipboard for the same reason.

If you run neovim then you should install xclip (as explained by help clipboard-tool)

Using LINQ to remove elements from a List<T>

This is a very old question, but I found a really simple way to do this:

authorsList = authorsList.Except(authors).ToList();

Note that since the return variable authorsList is a List<T>, the IEnumerable<T> returned by Except() must be converted to a List<T>.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

For files encoding...

public class FRomUtf8ToIso {
        static File input = new File("C:/Users/admin/Desktop/pippo.txt");
        static File output = new File("C:/Users/admin/Desktop/ciccio.txt");


    public static void main(String[] args) throws IOException {

        BufferedReader br = null;

        FileWriter fileWriter = new FileWriter(output);
        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader( input ));

            int i= 0;
            while ((sCurrentLine = br.readLine()) != null) {
                byte[] isoB =  encode( sCurrentLine.getBytes() );
                fileWriter.write(new String(isoB, Charset.forName("ISO-8859-15") ) );
                fileWriter.write("\n");
                System.out.println( i++ );
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }


    static byte[] encode(byte[] arr){
        Charset utf8charset = Charset.forName("UTF-8");
        Charset iso88591charset = Charset.forName("ISO-8859-15");

        ByteBuffer inputBuffer = ByteBuffer.wrap( arr );

        // decode UTF-8
        CharBuffer data = utf8charset.decode(inputBuffer);

        // encode ISO-8559-1
        ByteBuffer outputBuffer = iso88591charset.encode(data);
        byte[] outputData = outputBuffer.array();

        return outputData;
    }

}

Installing tkinter on ubuntu 14.04

Try:

sudo apt-get install python-tk python3-tk tk-dev

If you're using python3, then Python3 virtual environment(venv) is also required. Use:

sudo apt install python3-venv

CSS3 Box Shadow on Top, Left, and Right Only

I found a way to cover the shadow with ":after", here is my code:

#div:after {
    content:"";
    position:absolute;
    width:5px;
    background:#fff;
    height:38px;
    top:1px;
    right:-5px;
}

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Reading a single char in Java

Here is a class 'getJ' with a static function 'chr()'. This function reads one char.

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class getJ {
    static char  chr()throws IOException{  
        BufferedReader bufferReader =new BufferedReader(new InputStreamReader(System.in));
        return bufferReader.readLine().charAt(0);
    }
}

In order to read a char use this:

anyFunc()throws IOException{
...
...
char c=getJ.chr();
}

Because of 'chr()' is static, you don't have to create 'getJ' by 'new' ; I mean you don't need to do:

getJ ob = new getJ;
c=ob.chr();

You should remember to add 'throws IOException' to the function's head. If it's impossible, use try / catch as follows:

anyFunc(){// if it's impossible to add 'throws IOException' here
...
try
{
char c=getJ.chr(); //reads a char into c
} 
catch(IOException e)
{
System.out.println("IOException has been caught");
}

Credit to: tutorialspoint.com

See also: geeksforgeeks.

How do I rename the android package name?

What I did was the following

  1. Change manifest.
  2. Close androidStudio
  3. Open folder with Windows Explorer. Change folder names.
  4. Open androidStudio, and do a search and replace.

Done!

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

PHP mail not working for some reason

I'm using this for a while now, don't know if this is still up to date with the actual PHP versions. You can use this in a one file setup, or just split it up in two files like contact.php and index.php

contact.php | Code

<?php 
error_reporting(E_ALL ^ E_NOTICE); 


if(isset($_POST['submitted'])) {


if(trim($_POST['contactName']) === '') {
    $nameError =  '<span style="margin-left:40px;">You have missed your name.</span>'; 
    $hasError = true;
} else {
    $name = trim($_POST['contactName']);
}

if(trim($_POST['topic']) === '') {
    $topicError = '<span style="margin-left:40px;">You have missed the topic.</span>'; 
    $hasError = true;
} else {
    $topic = trim($_POST['topic']);
}

$telefon = trim($_POST['phone']);
$company = trim($_POST['company']);


if(trim($_POST['email']) === '')  {
    $emailError = '<span style="margin-left:40px;">You have missed your email adress.</span>';
    $hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
    $emailError = '<span style="margin-left:40px;">You have missspelled your email adress.</span>';
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}


if(trim($_POST['comments']) === '') {
    $commentError = '<span style="margin-left:40px;">You have missed the comment section.</span>';
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = utf8_encode(stripslashes(trim($_POST['comments'])));
    } else {
        $comments = trim($_POST['comments']);
    }
}


if(!isset($hasError)) {

    $emailTo = '[email protected]';
    $subject = 'Example.com - '.$name.' - '.$betreff;
    $sendCopy = trim($_POST['sendCopy']);
    $body = "\n\n This is an email from http://www.example.com \n\nCompany : $company\n\nName : $name \n\nEmail-Adress : $email \n\nPhone-No.. : $phone \n\nTopic : $topic\n\nMessage of the sender: $comments\n\n";
    $headers = "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n";

    mail($emailTo, $subject, $body, $headers);



    $emailSent = true;
}
}
?>

STYLESHEET

}
.formblock{display:block;padding:5px;margin:8px; margin-left:40px;}
.text{width:500px;height:200px;padding:5px;margin-left:40px;}
.center{min-height:12em;display:table-cell;vertical-align:middle;}
.failed{ margin-left:20px;font-size:18px;color:#C00;}
.okay{margin-left:20px;font-size:18px;color:#090;}
.alert{border:2px #fc0;padding:8px;text-transform:uppercase;font-weight:bold;}
.error{font-size:14px;color:#C00;}

label
{
margin-left:40px;
}

textarea

{
margin-left:40px;
}

index.php | FORM CODE

<?php header('Content-Type: text/html;charset=UTF-8'); ?>
<!DOCTYPE html>
<html lang="de">
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>


<form action="contact.php" method="post">

<?php if(isset($emailSent) && $emailSent == true) { ?>

<span class="okay">Thank you for your interest. Your email has been send !</span>

<br>

<br>

<?php } else { ?>

<?php if(isset($hasError) || isset($captchaError) ) { ?>

<span class="failed">Email not been send. Please check the contact form.</span>

<br>

<br>

<?php } ?>

<label class="text label">Company</label>

<br>

<input type="text" size="30" name="company" id="company" value="<?php if(isset($_POST['company'])) echo $_POST['comnpany'];?>" class="formblock" placeholder="Your Company">

<label class="text label">Your Name <strong class="error">*</strong></label>

<br>

<?php if($nameError != '') { ?>

<span class="error"><?php echo $nameError;?></span>

<?php } ?>

<input type="text" size="30" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="formblock" placeholder="Your Name">

<label class="text label">- Betreff - Anliegen - <strong class="error">*</strong></label>

<br>

<?php if($topicError != '') { ?>

<span class="error"><?php echo $betrError;?></span>

<?php } ?>

<input type="text" size="30" name="topic" id="topic" value="<?php if(isset($_POST['topic'])) echo $_POST['topic'];?>" class="formblock" placeholder="Your Topic">

<label class="text label">Phone-No.</label>

<br>

<input type="text" size="30" name="phone" id="phone" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>" class="formblock" placeholder="12345 678910">

<label class="text label">Email-Adress<strong class="error">*</strong></label>

<br>

<?php if($emailError != '') { ?>

<span class="error"><?php echo $emailError;?></span>

<?php } ?>

<input type="text" size="30" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="formblock" placeholder="[email protected]">

<label class="text label">Your Message<strong class="error">*</strong></label>

<br>

<?php if($commentError != '') { ?>

<span class="error"><?php echo $commentError;?></span>

<?php } ?>

<textarea name="comments" id="commentsText" class="formblock text" placeholder="Leave your message here..."><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>

<button class="formblock" name="submit" type="submit">Send Email</button>
<input type="hidden" name="submitted" id="submitted" value="true">
<?php } ?>

</form>
</body>
</html>

JAVASCRIPT

<script type="text/javascript">

<!--//--><![CDATA[//><!--

$(document).ready(function() {

$('form#contact-us').submit(function() {

$('form#contact-us .error').remove();
var hasError = false;

$('.requiredField').each(function() {

if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have missed '+labelText+'.</span>.');

$(this).addClass('inputError');
hasError = true;

} else if($(this).hasClass('email')) {

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {

var labelText = $(this).prev('label').text();

$(this).parent().append('<br><br><span style="margin-left:20px;">You have entered a wrong '+labelText+' adress.</span>.');

$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {

var formInput = $(this).serialize();

$.post($(this).attr('action'),formInput, function(data){

$('form#contact-us').slideUp("fast", function() {                  
$(this).before('<br><br><strong>Thank You!</strong>Your Email has been send successfuly.');

});

});

}
return false;   

});

});

//-->!]]>

</script>

sed one-liner to convert all uppercase to lowercase?

short, sweet and you don't even need redirection :-)

perl -p -i -e 'tr/A-Z/a-z/' file

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

Just remove Trusted_Connection=True property from the connection string.

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

Get current NSDate in timestamp format

Swift:

I have a UILabel which shows TimeStamp over a Camera Preview.

    var timeStampTimer : NSTimer?
    var dateEnabled:  Bool?
    var timeEnabled: Bool?
   @IBOutlet weak var timeStampLabel: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
//Setting Initial Values to be false.
        dateEnabled =  false
        timeEnabled =  false
}

override func viewWillAppear(animated: Bool) {

        //Current Date and Time on Preview View
        timeStampLabel.text = timeStamp
        self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true)
}

func updateCurrentDateAndTimeOnTimeStamperLabel()
    {
//Every Second, it updates time.

        switch (dateEnabled, timeEnabled) {
        case (true?, true?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle)
            break;
        case (true?, false?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle)
            break;

        case (false?, true?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle)
            break;
        case (false?, false?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle)
            break;
        default:
            break;

        }
    }

I am setting up a setting Button to trigger a alertView.

@IBAction func settingsButton(sender : AnyObject) {


let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)

let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  true

}
let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  false

}
let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  false


}
let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  true
}

let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in

}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(timeStampOnAction)
cameraSettingsAlert.addAction(timeStampOffAction)
cameraSettingsAlert.addAction(dateOnlyAction)
cameraSettingsAlert.addAction(timeOnlyAction)

self.presentViewController(cameraSettingsAlert, animated: true, completion: nil)

}

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

In my case the problem was the 32/64 bit driver which I solved by configuring the properties of the sql server job:

enter image description here

How to keep :active css style after click a button

CSS

:active denotes the interaction state (so for a button will be applied during press), :focus may be a better choice here. However, the styling will be lost once another element gains focus.

The final potential alternative using CSS would be to use :target, assuming the items being clicked are setting routes (e.g. anchors) within the page- however this can be interrupted if you are using routing (e.g. Angular), however this doesnt seem the case here.

_x000D_
_x000D_
.active:active {_x000D_
  color: red;_x000D_
}_x000D_
.focus:focus {_x000D_
  color: red;_x000D_
}_x000D_
:target {_x000D_
  color: red;_x000D_
}
_x000D_
<button class='active'>Active</button>_x000D_
<button class='focus'>Focus</button>_x000D_
<a href='#target1' id='target1' class='target'>Target 1</a>_x000D_
<a href='#target2' id='target2' class='target'>Target 2</a>_x000D_
<a href='#target3' id='target3' class='target'>Target 3</a>
_x000D_
_x000D_
_x000D_

Javascript / jQuery

As such, there is no way in CSS to absolutely toggle a styled state- if none of the above work for you, you will either need to combine with a change in your HTML (e.g. based on a checkbox) or programatically apply/remove a class using e.g. jQuery

_x000D_
_x000D_
$('button').on('click', function(){_x000D_
    $('button').removeClass('selected');_x000D_
    $(this).addClass('selected');_x000D_
});
_x000D_
button.selected{_x000D_
  color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button>Item</button><button>Item</button><button>Item</button>_x000D_
  
_x000D_
_x000D_
_x000D_

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

iOS: present view controller programmatically

your code :

 AddTaskViewController *add = [[AddTaskViewController alloc] init];
 [self presentViewController:add animated:YES completion:nil];

this code can goes to the other controller , but you get a new viewController , not the controller of your storyboard, you can do like this :

AddTaskViewController *add = [self.storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardID"];
[self presentViewController:add animated:YES completion:nil];

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

How to efficiently concatenate strings in go

You could create a big slice of bytes and copy the bytes of the short strings into it using string slices. There is a function given in "Effective Go":

func Append(slice, data[]byte) []byte {
    l := len(slice);
    if l + len(data) > cap(slice) { // reallocate
        // Allocate double what's needed, for future growth.
        newSlice := make([]byte, (l+len(data))*2);
        // Copy data (could use bytes.Copy()).
        for i, c := range slice {
            newSlice[i] = c
        }
        slice = newSlice;
    }
    slice = slice[0:l+len(data)];
    for i, c := range data {
        slice[l+i] = c
    }
    return slice;
}

Then when the operations are finished, use string ( ) on the big slice of bytes to convert it into a string again.

Why are my PowerShell scripts not running?

On Windows 10: Click change security property of myfile.ps1 and change "allow access" by right click / properties on myfile.ps1

Download a div in a HTML page as pdf using javascript

AFAIK there is no native jquery function that does this. Best option would be to process the conversion on the server. How you do this depends on what language you are using (.net, php etc.). You can pass the content of the div to the function that handles the conversion, which would return a pdf to the user.

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

How to scale down a range of numbers with a known min and max value

Let's say you want to scale a range [min,max] to [a,b]. You're looking for a (continuous) function that satisfies

f(min) = a
f(max) = b

In your case, a would be 1 and b would be 30, but let's start with something simpler and try to map [min,max] into the range [0,1].

Putting min into a function and getting out 0 could be accomplished with

f(x) = x - min   ===>   f(min) = min - min = 0

So that's almost what we want. But putting in max would give us max - min when we actually want 1. So we'll have to scale it:

        x - min                                  max - min
f(x) = ---------   ===>   f(min) = 0;  f(max) =  --------- = 1
       max - min                                 max - min

which is what we want. So we need to do a translation and a scaling. Now if instead we want to get arbitrary values of a and b, we need something a little more complicated:

       (b-a)(x - min)
f(x) = --------------  + a
          max - min

You can verify that putting in min for x now gives a, and putting in max gives b.

You might also notice that (b-a)/(max-min) is a scaling factor between the size of the new range and the size of the original range. So really we are first translating x by -min, scaling it to the correct factor, and then translating it back up to the new minimum value of a.

Hope this helps.

Sorting a list with stream.sorted() in Java

It seems to be working fine:

List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

Example Input/Output

Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]

Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

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

Select the project -> Right-Click -> clean and build and then run the project again simply solve the problem for me.

As, multiple process could bind the same port for example port 8086, In that case I have to kill all the processes involved with the port with PID. That might be cumbersome.

OR operator in switch-case?

Switch is not same as if-else-if.

Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Dynamically Add C# Properties at Runtime

you could deserialize your json string into a dictionary and then add new properties then serialize it.

 var jsonString = @"{}";

        var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);

        jsonDoc.Add("Name", "Khurshid Ali");

        Console.WriteLine(JsonSerializer.Serialize(jsonDoc));

CSS Cell Margin

A word of warning: though padding-right might solve your particular (visual) problem, it is not the right way to add spacing between table cells. What padding-right does for a cell is similar to what it does for most other elements: it adds space within the cell. If the cells do not have a border or background colour or something else that gives the game away, this can mimic the effect of setting the space between the cells, but not otherwise.

As someone noted, margin specifications are ignored for table cells:

CSS 2.1 Specification – Tables – Visual layout of table contents

Internal table elements generate rectangular boxes with content and borders. Cells have padding as well. Internal table elements do not have margins.

What's the "right" way then? If you are looking to replace the cellspacing attribute of the table, then border-spacing (with border-collapse disabled) is a replacement. However, if per-cell "margins" are required, I am not sure how that can be correctly achieved using CSS. The only hack I can think of is to use padding as above, avoid any styling of the cells (background colours, borders, etc.) and instead use container DIVs inside the cells to implement such styling.

I am not a CSS expert, so I could well be wrong in the above (which would be great to know! I too would like a table cell margin CSS solution).

Cheers!

How to append a date in batch files

This is all awkward and not local settings independent. Do it like this:

%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt

Yes, use Cygwin date and all your problems are gone!

How to part DATE and TIME from DATETIME in MySQL

Try:

SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

This answer is just as good the top plugin-management answer above (which is to say, it's terrible).

Just delete all the offending xml code in the pom.

Done. Problem solved (except you just broke your maven config...).

Devs should be very careful they understand plugin-management tags before doing any of these solutions. Just slapping plugin-management around your plugins are random is likely to break the maven build for everyone else just to get eclipse to work.

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

MySQL Server has gone away when importing large sql file

I solved my issue with this short /etc/mysql/my.cnf file :

[mysqld]
wait_timeout = 600
max_allowed_packet = 100M

What is 'PermSize' in Java?

lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

How to hide form code from view code/inspect element browser?

There is a smart way to disable inspect element in your website. Just add the following snippet inside script tag :

$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});

Please check out this blog

The function key F12 which directly take inspect element from browser, we can also disable it, by using the following code:

$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

document.getelementbyId will return null if element is not defined?

getElementById is defined by DOM Level 1 HTML to return null in the case no element is matched.

!==null is the most explicit form of the check, and probably the best, but there is no non-null falsy value that getElementById can return - you can only get null or an always-truthy Element object. So there's no practical difference here between !==null, !=null or the looser if (document.getElementById('xx')).

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Efficient way to add spaces between characters in a string

A very pythonic and practical way to do it is by using the string join() method:

str.join(iterable)

The official Python documentations says:

Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

How to use it?

Remember: this is a string method.

This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

Let's have some practical example!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

In practice you would do it like this:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

What happens if you use a hyphen as a string instead?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

Can't find bundle for base name

BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:

$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties 
org/jfree/chart/LocalizationBundle.properties
org/jfree/chart/editor/LocalizationBundle.properties
org/jfree/chart/plot/LocalizationBundle.properties

Force "portrait" orientation mode

I think you want to add android:configChanges="orientation|keyboardHidden" to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged would not be called then, only the onCreate

C/C++ NaN constant (literal)?

In C, NAN is declared in <math.h>.

In C++, std::numeric_limits<double>::quiet_NaN() is declared in <limits>.

But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan() from <math.h> in C, or std::isnan() from <cmath> in C++.

What is the proper way to URL encode Unicode characters?

IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.

Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

I had this problem after updating your java. The best way to solve this problem is just go to your c:/ProgramFiles/Java folder. There you will find two jre folders one is as jre.your version and other with exactly like jdk folder. Try to remove jre.1.your version folder. There you go your problem is solved. Hope this might help. It's worked for me.

nvarchar(max) still being truncated

Results to text only allows a maximum of 8192 characters.

Screenshot

I use this approach

DECLARE @Query NVARCHAR(max);

set @Query = REPLICATE('A',4000)
set @Query = @Query + REPLICATE('B',4000)
set @Query = @Query + REPLICATE('C',4000)
set @Query = @Query + REPLICATE('D',4000)

select LEN(@Query)

SELECT @Query /*Won't contain any "D"s*/
SELECT @Query as [processing-instruction(x)] FOR XML PATH /*Not truncated*/

JavaScript is in array

Some browsers support Array.indexOf().

If not, you could augment the Array object via its prototype like so...

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

Source.

How to POST form data with Spring RestTemplate?

Your url String needs variable markers for the map you pass to work, like:

String url = "https://app.example.com/hr/email?{email}";

Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

String url = "https://app.example.com/hr/[email protected]";

See also https://stackoverflow.com/a/47045624/1357094

Initializing multiple variables to the same value in Java

No, it's not possible in java.

You can do this way .. But try to avoid it.

String one, two, three;
one = two = three = "";

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This did the trick for me:

echo trim($entry->title);

Jquery validation plugin - TypeError: $(...).validate is not a function

I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:

require('jquery-validation');

Fullscreen Activity in Android?

show Full Immersive:

private void askForFullScreen()
    {
        getActivity().getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

move out of full immersive mode:

 private void moveOutOfFullScreen() {
        getActivity().getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

Name node is in safe mode. Not able to leave

Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:

hadoop dfsadmin -safemode leave

If you are using cloudera manager:

go to >>Actions>>Leave Safemode

But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.

free -m

If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)

How do I add records to a DataGridView in VB.Net?

I think you should build a dataset/datatable in code and bind the grid to that.

Why does one use dependency injection?

The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface. If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.

That is already common in OOP for a long time. Many times creating code pieces like:

I_Dosomething x = new Impl_Dosomething();

The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface. In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved. Service locator example:

I_Dosomething x = ServiceLocator.returnDoing(String pKey);

DI example:

I_Dosomething x = DIContainer.returnThat();

One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.

D(b)I: Dependency Injection and Design by Interface. This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.

I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers. It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)

Add horizontal scrollbar to html table

With bootstrap

 <div class="table-responsive">
   <table class="table">
     ...
   </table>
 </div>

How to remove all CSS classes using jQuery/JavaScript?

$('#elm').removeAttr('class');

no longer class attr wil be present in "elm".

Redirecting unauthorized controller in ASP.NET MVC

You should build your own Authorize-filter attribute.

Here's mine to study ;)

Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
    Private _role As String

    Public Property Role() As String
        Get
            Return Me._role
        End Get
        Set(ByVal value As String)
            Me._role = value
        End Set
    End Property

    Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        If Not String.IsNullOrEmpty(Me.Role) Then
            If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
                Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
                Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
                Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

                filterContext.HttpContext.Response.Redirect(loginUrl, True)
            Else
                Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
                If Not hasAccess Then
                    Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
                End If
            End If
        Else
            Throw New InvalidOperationException("No Role Specified")
        End If

    End Sub
End Class

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

Regular expression to match standard 10 digit phone number

The expressions for 1, 3 and 4 are quite similar, so you can use:

^([1-9]\d{2})([- .])(\d{3})$2(\d{4})$

Note that, depending on the language and brand of regexes used, you might need to put \2 instead of $2 or such matching might not be supported at all.

I see no good way to combine this with the format 2, apart from the obvious ^(regex for 1,3,4|regex for 2)$ which is ugly, clumsy and makes it hard to get out the parts of the numbers.

As for the area code, you can add (\+\d)? to the beginning to capture a single-digit area code (sorry, I don't know the format of your area codes).

Forcing anti-aliasing using css: Is this a myth?

As a side note, Gecko and WebKit support the the

text-rendering

property as well.

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

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

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

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

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

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

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

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

IntelliJ IDEA vs WebStorm features

IntelliJ IDEA remains JetBrains' flagship product and IntelliJ IDEA provides full JavaScript support along with all other features of WebStorm via bundled or downloadable plugins. The only thing missing is the simplified project setup.

Taken from : https://confluence.jetbrains.com/display/WI/WebStorm+FAQ#WebStormFAQ-IntelliJIDEAvsWebStormfeatures

Android, Java: HTTP POST Request

HTTP request POST in java does not dump the answer?

public class HttpClientExample 
{
 private final String USER_AGENT = "Mozilla/5.0";
 public static void main(String[] args) throws Exception 
 {

HttpClientExample http = new HttpClientExample();

System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();

}

 // HTTP POST request
 private void sendPost() throws Exception {
 String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("User-Agent", USER_AGENT);

List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
        urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());

 BufferedReader rd = new BufferedReader(new 
 InputStreamReader(response.getEntity().getContent()));

  StringBuilder result = new StringBuilder();
  String line = "";
  while ((line = rd.readLine()) != null) 
        {
      result.append(line);
                System.out.println(line);
    }

   }
 }

This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

Playing sound notifications using Javascript?

Found something like that:

//javascript:
function playSound( url ){   
  document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
} 

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

when you do UNIQUE as a table level constraint as you have done then what your defining is a bit like a composite primary key see ddl constraints, here is an extract

"This specifies that the *combination* of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique."

this means that either field could possibly have a non unique value provided the combination is unique and this does not match your foreign key constraint.

most likely you want the constraint to be at column level. so rather then define them as table level constraints, 'append' UNIQUE to the end of the column definition like name VARCHAR(60) NOT NULL UNIQUE or specify indivdual table level constraints for each field.

Ajax Success and Error function failure

One also may use the following to catch the errors:

$.ajax({
    url: url, 
    success: function (data) {
        // Handle success here
        $('#editor-content-container').html(data);
        $('#editor-container').modal('show');
    },
    cache: false
}).fail(function (jqXHR, textStatus, error) {
    // Handle error here
    $('#editor-content-container').html(jqXHR.responseText);
    $('#editor-container').modal('show');
});

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

How to reset radiobuttons in jQuery so that none is checked

I know this is old and that this is a little off topic, but supposing you wanted to uncheck only specific radio buttons in a collection:

_x000D_
_x000D_
$("#go").click(function(){_x000D_
    $("input[name='correctAnswer']").each(function(){_x000D_
      if($(this).val() !== "1"){_x000D_
        $(this).prop("checked",false);_x000D_
      }_x000D_
    });_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>_x000D_
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>_x000D_
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>_x000D_
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>_x000D_
<input type="button" id="go" value="go">
_x000D_
_x000D_
_x000D_

And if you are dealing with a radiobutton list, you can use the :checked selector to get just the one you want.

$("#go").click(function(){
  $("input[name='correctAnswer']:checked").prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
<input type="button" id="go" value="go">

How to directly move camera to current location in Google Maps Android API v2?

I am explaining, How to get current location and Directly move to the camera to current location with assuming that you have implemented map-v2. For more details, You can refer official doc.

Add location service in gradle

implementation "com.google.android.gms:play-services-location:11.0.1"

Add location permission in manifest file

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

Make sure you ask for RunTimePermission. I am using Ask-Permission for that. Its easy to use.

Now refer below code to get the current location and display it on a map.

private FusedLocationProviderClient mFusedLocationProviderClient;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFusedLocationProviderClient = LocationServices
                .getFusedLocationProviderClient(getActivity());

}

private void getDeviceLocation() {
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            Location location = task.getResult();
                            LatLng currentLatLng = new LatLng(location.getLatitude(),
                                    location.getLongitude());
                            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
                                    DEFAULT_ZOOM);
                            googleMap.moveCamera(update);
                        }
                    }
                });
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
}

When user granted location permission call above getDeviceLocation() method

private void updateLocationUI() {
        if (googleMap == null) {
            return;
        }
        try {
            if (mLocationPermissionGranted) {
                googleMap.setMyLocationEnabled(true);
                googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                getDeviceLocation();
            } else {
                googleMap.setMyLocationEnabled(false);
                googleMap.getUiSettings().setMyLocationButtonEnabled(false);
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
    }

Get index of clicked element in collection with jQuery

if you are using .bind(this), try this:

let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

$(this.pagination).find("a").on('click', function(evt) {
        let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

        this.goTo(index);
    }.bind(this))

Reference — What does this symbol mean in PHP?

{} Curly braces

And some words about last post

$x[4] = 'd'; // it works
$x{4} = 'd'; // it works

$echo $x[4]; // it works
$echo $x{4}; // it works

$x[] = 'e'; // it works
$x{} = 'e'; // does not work

$x = [1, 2]; // it works
$x = {1, 2}; // does not work

echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work

echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works

How do I add an integer value with javascript (jquery) to a value that's returning a string?

parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.

var currentValue = parseInt($("#replies").text(),10);

The second paramter (radix) makes sure it is parsed as a decimal number.

How to get the file name from a full path using JavaScript?

I use:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

It replaces the last \ so it also works with folders.

Why emulator is very slow in Android Studio?

The emulator is much much faster when running on Linux. In Ubuntu 13.04, it launches within 10 seconds, and it runs nearly as smoothly as on a physical device. I haven't been able to reproduce the performance on Windows.

EDIT: Actually, after the first boot, when using the Atom arch. and GPU acceleration, the Windows emulator runs nearly as well as in Linux.

Node/Express file upload

I needed to be walked through with a bit more detail than the other answers provided (e.g. how do I write the file to a location I decide at runtime?). Hopefully this is of help to others:  

get connect-busboy:

npm install connect-busboy --save

In your server.js, add these lines

let busboy = require('connect-busboy')

// ... 

app.use(busboy());

// ... 

app.post('/upload', function(req, res) {
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename) {
        var fstream = fs.createWriteStream('./images/' + filename); 
        file.pipe(fstream);
        fstream.on('close', function () {
            res.send('upload succeeded!');
        });
    });
});

This would seem to omit error handling though... will edit it in if I find it.

Encrypt Password in Configuration Files?

A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.

This basically means initializing a javax.crypto.Cipher with algorithm "AES/CBC/PKCS5Padding" and getting a key from javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Here is a code example (updated to replace the less secure MD5-based variant):

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class ProtectedConfigFile {

    public static void main(String[] args) throws Exception {
        String password = System.getProperty("password");
        if (password == null) {
            throw new IllegalArgumentException("Run with -Dpassword=<password>");
        }

        // The salt (probably) can be stored along with the encrypted data
        byte[] salt = new String("12345678").getBytes();

        // Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
        int iterationCount = 40000;
        // Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password.toCharArray(),
                salt, iterationCount, keyLength);

        String originalPassword = "secret";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword, key);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword, key);
        System.out.println("Decrypted password: " + decryptedPassword);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}

One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (-DpropertyProtectionPassword=...).

The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Returning the product of a list

reduce(lambda x, y: x * y, list, 1)

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

ASP.NET MVC: Custom Validation by DataAnnotation

Self validated model

Your model should implement an interface IValidatableObject. Put your validation code in Validate method:

public class MyModel : IValidatableObject
{
    public string Title { get; set; }
    public string Description { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Title == null)
            yield return new ValidationResult("*", new [] { nameof(Title) });

        if (Description == null)
            yield return new ValidationResult("*", new [] { nameof(Description) });
    }
}

Please notice: this is a server-side validation. It doesn't work on client-side. You validation will be performed only after form submission.

Linq select to new object

The answers here got me close, but in 2016, I was able to write the following LINQ:

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();

How to use a PHP class from another file?

use

require_once(__DIR__.'/_path/_of/_filename.php');

This will also help in importing files in from different folders. Try extends method to inherit the classes in that file and reuse the functions

Intel's HAXM equivalent for AMD on Windows OS

You will need to create a virtual device that runs on ARM. Virtual devices running on X86 require an Intel processor. AMD support as specified by Android is only available for Linux systems. If you want a better experience when creating your Virtual Device, use "Store a snapshot for faster startup" instead of the default "Use Host GPU".

SVN upgrade working copy

If you're getting this error from Netbeans (7.2+) then it means that your separately installed version of Subversion is higher than the version in netbeans. In my case Netbeans (v7.3.1) had SVN v1.7 and I'd just upgraded my SVN to v1.8.

If you look in Tools > Options > Miscellaneous (tab) > Versioning (tab) > Subversion (pane), set the Preferred Client = CLI, then you can set the path the the installed SVN which for me was C:\Program Files\TortoiseSVN\bin.

More can be found on the Netbeans Subversion Clients FAQ.

How do I force my .NET application to run as administrator?

As per

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.

  • Next, right click project
  • Add new Item
  • Last, find and click Application Manifest File

Uninstall / remove a Homebrew package including all its dependencies

The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed:

brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install

Why do you have to link the math library in C?

All libraries like stdio.h and stdlib.h have their implementation in libc.so or libc.a and get linked by the linker by default. The libraries for libc.so are automatically linked while compiling and is included in the executable file.
But math.h has its implementations in libm.so or libm.a which is seperate from libc.so and it does not get linked by default and you have to manually link it while compiling your program in gcc by using -lm flag.

The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.

Here read the item no 14.3, you could read it all if you wish: Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage: using the library

TreeMap sort by value

import java.util.*;

public class Main {

public static void main(String[] args) {
    TreeMap<String, Integer> initTree = new TreeMap();
    initTree.put("D", 0);
    initTree.put("C", -3);
    initTree.put("A", 43);
    initTree.put("B", 32);
    System.out.println("Sorted by keys:");
    System.out.println(initTree);
    List list = new ArrayList(initTree.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
            return e1.getValue().compareTo(e2.getValue());
        }
    });
    System.out.println("Sorted by values:");
    System.out.println(list);
}
}

Escape a string in SQL Server so that it is safe to use in LIKE expression

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

How do I remove a submodule?

If you have just added the submodule, and for example, you simply added the wrong submodule or you added it to the wrong place, simply do git stash then delete the folder. This is assuming that adding the submodule is the only thing you did in the recent repo.

How do I add a margin between bootstrap columns without wrapping

I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:

<div class="row">
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
</div>

This will automatically render some space between the 2 divs. enter image description here

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

In bash, how to store a return value in a variable?

It's due to the echo statements. You could switch your echos to prints and return with an echo. Below works

#!/bin/bash

set -x
echo "enter: "
read input

function password_formula
{
        length=${#input}
        last_two=${input:length-2:length}
        first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
        second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
        let sum=$first+$second
        sum_len=${#sum}
        print $second
        print $sum

        if [ $sum -gt 9 ]
        then
           sum=${sum:1}
        fi

        value=$second$sum$first
        echo $value
}
result=$(password_formula)
echo $result

Difference between web reference and service reference?

The low-level answer here is that a Web Reference will create a client proxy class that allows your code to talk to a Web Service that is described via WSDL and communicates via SOAP or HTTP GET (other posters indicate that it is only ASMX, but Web References can also talk to Java-based Web Services or Python-based or Ruby so long as they all talk WSDL and conform to the WS-I interoperability standard).

A Service Reference will create a client proxy class that communicates with a WCF-based service : regardless of whether that WCF service is a Web Service or not.

PHPExcel set border and format for all sheets in spreadsheet

for ($s=65; $s<=90; $s++) {
    //echo chr($s);
    $objPHPExcel->getActiveSheet()->getColumnDimension(chr($s))->setAutoSize(true);
}

Node.js heap out of memory

This command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.

node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js

Set variable value to array of strings

In SQL you can not have a variable array.
However, the best alternative solution is to use a temporary table.

WPF Datagrid Get Selected Cell Value

I was to dumb to find the Solution...

For me (VB):

 Dim string= Datagrid.SelectedCells(0).Item(0).ToString

Basic HTTP and Bearer Token Authentication

If you are using a reverse proxy such as nginx in between, you could define a custom token, such as X-API-Token.

In nginx you would rewrite it for the upstream proxy (your rest api) to be just auth:

proxy_set_header Authorization $http_x_api_token;

... while nginx can use the original Authorization header to check HTTP AUth.

get an element's id

Yes. You can get an element by its ID by calling document.getElementById. It will return an element node if found, and null otherwise:

var x = document.getElementById("elementid");   // Get the element with id="elementid"
x.style.color = "green";                        // Change the color of the element

Parsing JSON Object in Java

1.) Create an arraylist of appropriate type, in this case i.e String

2.) Create a JSONObject while passing your string to JSONObject constructor as input

  • As JSONObject notation is represented by braces i.e {}
  • Where as JSONArray notation is represented by square brackets i.e []

3.) Retrieve JSONArray from JSONObject (created at 2nd step) using "interests" as index.

4.) Traverse JASONArray using loops upto the length of array provided by length() function

5.) Retrieve your JSONObjects from JSONArray using getJSONObject(index) function

6.) Fetch the data from JSONObject using index '"interestKey"'.

Note : JSON parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes (") like this

`"{"key":"value"}"`

should be like this

`"{\"key\":\"value\"}"`

so you can use JSONParser to achieve escaped sequence format for safety as

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);

Code :

JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";

JSONObject jsonObj = (JSONObject) parser.parse(response);

or

JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> interestList = new ArrayList<String>();

JSONArray jsonArray = jsonObj.getJSONArray("interests");

for(int i = 0 ; i < jsonArray.length() ; i++){
    interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}

Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key so in those cases when you are not sure about the presence of value so use optString, optInt, optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value

From docs

Get an optional string associated with a key. It returns the defaultValue if there is no such key.

 public String optString(String key, String defaultValue) {
  String missingKeyValue = json_data.optString("status","N/A");
  // note there is no such key as "status" in response
  // will return "N/A" if no key found 

or To get empty string i.e "" if no key found then simply use

  String missingKeyValue = json_data.optString("status");
  // will return "" if no key found where "" is an empty string

Further reference to study

Responding with a JSON object in Node.js (converting object/array to JSON string)

const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

I have used the above code in my existing project.

With block equivalent in C#?

I was using this way:

        worksheet.get_Range(11, 1, 11, 41)
            .SetHeadFontStyle()
            .SetHeadFillStyle(45)
            .SetBorders(
                XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick
                , XlBorderWeight.xlMedium
                , XlBorderWeight.xlThick)
            ;

SetHeadFontStyle / SetHeadFillStyle is ExtMethod of Range like below:

 public static Range SetHeadFillStyle(this Range rng, int colorIndex)
 {
     //do some operation
     return rng;
 }

do some operation and return the Range for next operation

it's look like Linq :)

but now still can't fully look like it -- propery set value

with cell.Border(xlEdgeTop)
   .LineStyle = xlContinuous
   .Weight = xlMedium
   .ColorIndex = xlAutomatic

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

Why am I getting Unknown error in line 1 of pom.xml?

same problem for me, original code from spring starter demo gives unknown error on line 1:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
...

Changing just the version of 2.1.6.RELEASE to 2.1.4.RELEASE fixes the problem.

Unable to ping vmware guest from another vmware guest

You can ping ip from one virtual machine to another machine by using these steps:

  1. Go to menu VM -> Setting -> select network adapter: NAT
  2. Go to menu VM -> setting -> select options Tab and select

Guest Isolation : ENABLED, ENABLED and select box : ENABLE VMCI

Auto highlight text in a textbox control

 textBoxX1.Focus();
 this.ActiveControl = textBoxX1;
 textBoxX1.SelectAll();

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Can I serve multiple clients using just Flask app.run() as standalone?

flask.Flask.run accepts additional keyword arguments (**options) that it forwards to werkzeug.serving.run_simple - two of those arguments are threaded (a boolean) and processes (which you can set to a number greater than one to have werkzeug spawn more than one process to handle requests).

threaded defaults to True as of Flask 1.0, so for the latest versions of Flask, the default development server will be able to serve multiple clients simultaneously by default. For older versions of Flask, you can explicitly pass threaded=True to enable this behaviour.

For example, you can do

if __name__ == '__main__':
    app.run(threaded=True)

to handle multiple clients using threads in a way compatible with old Flask versions, or

if __name__ == '__main__':
    app.run(threaded=False, processes=3)

to tell Werkzeug to spawn three processes to handle incoming requests, or just

if __name__ == '__main__':
    app.run()

to handle multiple clients using threads if you know that you will be using Flask 1.0 or later.

That being said, Werkzeug's serving.run_simple wraps the standard library's wsgiref package - and that package contains a reference implementation of WSGI, not a production-ready web server. If you are going to use Flask in production (assuming that "production" is not a low-traffic internal application with no more than 10 concurrent users) make sure to stand it up behind a real web server (see the section of Flask's docs entitled Deployment Options for some suggested methods).

Emulate Samsung Galaxy Tab

If you are developing on Netbeans, you will not get the Third-Party add-ons. You can download the Skins directly from Samsung here: http://developer.samsung.com/android/tools-sdks

After download, unzip to ...\Android\android-sdk\add-ons[name of device]

Restart the Android SDK Manager, and the new device should be there under Extras.

It would be better to add the download site directly to the SDK...if anyone knows it, please post it.

Scott

Strtotime() doesn't work with dd/mm/YYYY format

I tried to convert ddmmyy format to date("Y-m-d" format but was not working when I directly pass ddmmyy =date('dmy')

then realized it has to be in yyyy-mm-dd format so. used substring to organize

$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);  

then passed to date("Y-m-d",strtotime($strParam));

it worked!

Finding the index of elements based on a condition using python list comprehension

Another way:

>>> [i for i in range(len(a)) if a[i] > 2]
[2, 5]

In general, remember that while find is a ready-cooked function, list comprehensions are a general, and thus very powerful solution. Nothing prevents you from writing a find function in Python and use it later as you wish. I.e.:

>>> def find_indices(lst, condition):
...   return [i for i, elem in enumerate(lst) if condition(elem)]
... 
>>> find_indices(a, lambda e: e > 2)
[2, 5]

Note that I'm using lists here to mimic Matlab. It would be more Pythonic to use generators and iterators.

Any reason not to use '+' to concatenate two strings?

The assumption that one should never, ever use + for string concatenation, but instead always use ''.join may be a myth. It is true that using + creates unnecessary temporary copies of immutable string object but the other not oft quoted fact is that calling join in a loop would generally add the overhead of function call. Lets take your example.

Create two lists, one from the linked SO question and another a bigger fabricated

>>> myl1 = ['A','B','C','D','E','F']
>>> myl2=[chr(random.randint(65,90)) for i in range(0,10000)]

Lets create two functions, UseJoin and UsePlus to use the respective join and + functionality.

>>> def UsePlus():
    return [myl[i] + myl[i + 1] for i in range(0,len(myl), 2)]

>>> def UseJoin():
    [''.join((myl[i],myl[i + 1])) for i in range(0,len(myl), 2)]

Lets run timeit with the first list

>>> myl=myl1
>>> t1=timeit.Timer("UsePlus()","from __main__ import UsePlus")
>>> t2=timeit.Timer("UseJoin()","from __main__ import UseJoin")
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
2.48 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.61 usec/pass
>>> 

They have almost the same runtime.

Lets use cProfile

>>> myl=myl2
>>> cProfile.run("UsePlus()")
         5 function calls in 0.001 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 <pyshell#1376>:1(UsePlus)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}


>>> cProfile.run("UseJoin()")
         5005 function calls in 0.029 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.015    0.015    0.029    0.029 <pyshell#1388>:1(UseJoin)
        1    0.000    0.000    0.029    0.029 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     5000    0.014    0.000    0.014    0.000 {method 'join' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {range}

And it looks that using Join, results in unnecessary function calls which could add to the overhead.

Now coming back to the question. Should one discourage the use of + over join in all cases?

I believe no, things should be taken into consideration

  1. Length of the String in Question
  2. No of Concatenation Operation.

And off-course in a development pre-mature optimization is evil.

Python NoneType object is not callable (beginner)

Why does it give me that error?

Because your first parameter you pass to the loop function is None but your function is expecting an callable object, which None object isn't.

Therefore you have to pass the callable-object which is in your case the hi function object.

def hi():     
  print 'hi'

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(f.name)

Angular ui-grid dynamically calculate height of the grid

tony's approach does work for me but when do a console.log, the function getTableHeight get called too many time(sort, menu click...)

I modify it so the height is recalculated only when i add/remove rows. Note: tableData is the array of rows

$scope.getTableHeight = function() {
   var rowHeight = 30; // your row height
   var headerHeight = 30; // your header height
   return {
      height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"
   };
};

$scope.$watchCollection('tableData', function (newValue, oldValue) {
    angular.element(element[0].querySelector('.grid')).css($scope.getTableHeight());
});

Html

<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize"></div>

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

rsync: difference between --size-only and --ignore-times

You are missing that rsync can also compare files by checksum.

--size-only means that rsync will skip files that match in size, even if the timestamps differ. This means it will synchronise fewer files than the default behaviour. It will miss any file with changes that don't affect the overall file size. If you have something that changes the dates on files without changing the files, and you don't want rsync to spend lots of time checksumming those files to discover they haven't changed, this is the option to use.

--ignore-times means that rsync will checksum every file, even if the timestamps and file sizes match. This means it will synchronise more files than the default behaviour. It will include changes to files even where the file size is the same and the modification date/time has been reset to the original value. Checksumming every file means it has to be entirely read from disk, which may be slow. Some build pipelines will reset timestamps to a specific date (like 1970-01-01) to ensure that the final build file is reproducible bit for bit, e.g. when packed into a tar file that saves the timestamps.

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

HTML input - name vs. id

I hope you can find the following brief example helpful:

<!DOCTYPE html>
<html>
<head>
  <script>
    function checkGender(){
      if(document.getElementById('male').checked) {
         alert("Selected gender: "+document.getElementById('male').value)
      }else if(document.getElementById('female').checked) {
         alert("Selected gender: "+document.getElementById('female').value)
      }
      else{
         alert("Please choose your gender")
      }
    }
  </script>
</head>
<body>
<h1>Select your gender:</h1>

<form>
  <input type="radio" id="male" name="gender" value="male">Male<br>
  <input type="radio" id="female" name="gender" value="female">Female<br>
  <button onclick="checkGender()">Check gender</button> 
</form> 
</body>
</html>

In the code, note that both 'name' attributes are the same to define optionality between 'male' or 'female', but the 'id's are not equals to differentiate them.

Java heap terminology: young, old and permanent generations?

What is the young generation?

The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.

What is the old generation?

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection

What is the permanent generation?

The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.

PermGen has been replaced with Metaspace since Java 8 release.

PermSize & MaxPermSize parameters will be ignored now

How does the three generations interact/relate to each other?

enter image description here

Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.

Have a look at summary diagram:

enter image description here

Is it possible to cast a Stream in Java 8?

This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast Stream<Object> to a Stream<Client>?

No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object> is not a super type of List<String>, so you can't just cast a List<Object> to a List<String>.

Similar is the issue here. You can't cast Stream<Object> to Stream<Client>. Of course you can cast it indirectly like this:

Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;

but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream it is at runtime. Everything is just Stream.

BTW, what's wrong with your approach? Looks fine to me.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

How to fill DataTable with SQL Table

You can make method which return the datatable of given sql query:

public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";

SqlCommand cmd = new SqlCommand(query, conn);

DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
    a.Fill(t1);
}
return t1;
}

and now can be used like this:

table = GetDataTable();

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

add class with JavaScript

getElementsByClassName() returns HTMLCollection so you could try this

var button = document.getElementsByClassName("navButton")[0];

Edit

var buttons = document.getElementsByClassName("navButton");
for(i=0;buttons.length;i++){
   buttons[i].onmouseover = function(){
     this.className += ' active' //add class
     this.setAttribute("src", "images/arrows/top_o.png");
   }
}