Programs & Examples On #Self organizing maps

Type of Neural network (unsupervised learning). SOM's goal is to convert high-dimensional data into low-dimensional, like 2D map, which can be understood by human. Impl. questions: neural network structure, learning parameters, performance, use, multi-thread optimization, etc.

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

Random strings in Python

You can build random ascii characters like:

import random
print chr(random.randint(0,255))

And then build up a longer string like:

len = 50
print ''.join( [chr(random.randint(0,255)) for i in xrange(0,len)] )

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

Generate a random point within a circle (uniformly)

How to generate a random point within a circle of radius R:

r = R * sqrt(random())
theta = random() * 2 * PI

(Assuming random() gives a value between 0 and 1 uniformly)

If you want to convert this to Cartesian coordinates, you can do

x = centerX + r * cos(theta)
y = centerY + r * sin(theta)


Why sqrt(random())?

Let's look at the math that leads up to sqrt(random()). Assume for simplicity that we're working with the unit circle, i.e. R = 1.

The average distance between points should be the same regardless of how far from the center we look. This means for example, that looking on the perimeter of a circle with circumference 2 we should find twice as many points as the number of points on the perimeter of a circle with circumference 1.


                

Since the circumference of a circle (2πr) grows linearly with r, it follows that the number of random points should grow linearly with r. In other words, the desired probability density function (PDF) grows linearly. Since a PDF should have an area equal to 1 and the maximum radius is 1, we have


                

So we know how the desired density of our random values should look like. Now: How do we generate such a random value when all we have is a uniform random value between 0 and 1?

We use a trick called inverse transform sampling

  1. From the PDF, create the cumulative distribution function (CDF)
  2. Mirror this along y = x
  3. Apply the resulting function to a uniform value between 0 and 1.

Sounds complicated? Let me insert a blockquote with a little side track that conveys the intuition:

Suppose we want to generate a random point with the following distribution:

                

That is

  • 1/5 of the points uniformly between 1 and 2, and
  • 4/5 of the points uniformly between 2 and 3.

The CDF is, as the name suggests, the cumulative version of the PDF. Intuitively: While PDF(x) describes the number of random values at x, CDF(x) describes the number of random values less than x.

In this case the CDF would look like:

                

To see how this is useful, imagine that we shoot bullets from left to right at uniformly distributed heights. As the bullets hit the line, they drop down to the ground:

                

See how the density of the bullets on the ground correspond to our desired distribution! We're almost there!

The problem is that for this function, the y axis is the output and the x axis is the input. We can only "shoot bullets from the ground straight up"! We need the inverse function!

This is why we mirror the whole thing; x becomes y and y becomes x:

                

We call this CDF-1. To get values according to the desired distribution, we use CDF-1(random()).

…so, back to generating random radius values where our PDF equals 2x.

Step 1: Create the CDF:

Since we're working with reals, the CDF is expressed as the integral of the PDF.

CDF(x) = ? 2x = x2

Step 2: Mirror the CDF along y = x:

Mathematically this boils down to swapping x and y and solving for y:

CDF:     y = x2
Swap:   x = y2
Solve:   y = √x
CDF-1:  y = √x

Step 3: Apply the resulting function to a uniform value between 0 and 1

CDF-1(random()) = √random()

Which is what we set out to derive :-)

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

Undo working copy modifications of one file in Git?

This answers is for command needed for undoing local changes which are in multiple specific files in same or multiple folders (or directories). This answers specifically addresses question where a user has more than one file but the user doesn't want to undo all local changes:

if you have one or more files you could apply the same command (git checkout -- file ) to each of those files by listing each of their location separated by space as in:

git checkout -- name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext

mind the space above between name1/name2/fileOne.ext nameA/subFolder/fileTwo.ext

For multiple files in the same folder:

If you happen to need to discard changes for all of the files in a certain directory, use the git checkout as follows:

git checkout -- name1/name2/*

The asterisk in the above does the trick of undoing all files at that location under name1/name2.

And, similarly the following can undo changes in all files for multiple folders:

git checkout -- name1/name2/* nameA/subFolder/*

again mind the space between name1/name2/* nameA/subFolder/* in the above.

Note: name1, name2, nameA, subFolder - all of these example folder names indicate the folder or package where the file(s) in question may be residing.

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

How to call a button click event from another method

You can simply call it:

SubGraphButton_Click(sender, args);

Now, if your SubGraphButton_Click does something with the args, you might be in trouble, but usually you don't do anything with them.

How to Display Selected Item in Bootstrap Button Dropdown Title

It seems to be a long issue. All we want is just implement a select tag in the input group. But the bootstrap would not do it: https://github.com/twbs/bootstrap/issues/10486

the trick is just adding "btn-group" class to the parent div

html:

<div class="input-group">
  <div class="input-group-btn btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
      Product Name <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
    </ul>
  </div>
  <input type="text" class="form-control">
  <span class="input-group-btn">
    <button class="btn btn-primary" type="button">Search</button>
  </span>
</div>

js:

$(".dropdown-menu li a").click(function(e){
    var selText = $(this).text();
    $(this).parents('.input-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');       
});

Avoiding NullPointerException in Java

Just don't ever use null. Don't allow it.

In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.

class C {
    private final MyType mustBeSet;
    public C(MyType mything) {
       mustBeSet=Contract.notNull(mything);
    }
   private String name = "<unknown>";
   public void setName(String s) {
      name = Contract.notNull(s);
   }
}


class Contract {
    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}

The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.

How can I reset or revert a file to a specific revision?

Assuming the hash of the commit you want is c5f567:

git checkout c5f567 -- file1/to/restore file2/to/restore

The git checkout man page gives more information.

If you want to revert to the commit before c5f567, append ~1 (where 1 is the number of commits you want to go back, it can be anything):

git checkout c5f567~1 -- file1/to/restore file2/to/restore

As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).

jquery - return value using ajax result on success

// Common ajax caller
function AjaxCall(url,successfunction){
  var targetUrl=url;
  $.ajax({
    'url': targetUrl,
    'type': 'GET',
    'dataType': 'json',
    'success': successfunction,
    'error': function() {
      alert("error");
    }
  });
}

// Calling Ajax
$(document).ready(function() {
  AjaxCall("productData.txt",ajaxSuccessFunction);
});

// Function details of success function
function ajaxSuccessFunction(d){
  alert(d.Pioneer.Product[0].category);
}

it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example

How to create a directive with a dynamic template in AngularJS?

i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.

template.html:

<script type="text/ng-template" id=“foo”>
foo
</script>

<script type="text/ng-template" id=“bar”>
bar
</script>

directive:

myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {

    var getTemplate = function(data) {
        // use data to determine which template to use
        var templateid = 'foo';
        var template = $templateCache.get(templateid);
        return template;
    }

    return {
        templateUrl: 'views/partials/template.html',
        scope: {data: '='},
        restrict: 'E',
        link: function(scope, element) {
            var template = getTemplate(scope.data);

            element.html(template);
            $compile(element.contents())(scope);
        }
    };
}]);

How to update an object in a List<> in C#

Using Linq to find the object you can do:

var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;

But in this case you might want to save the List into a Dictionary and use this instead:

// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;

How to scale an Image in ImageView to keep the aspect ratio

this solved my problem

android:adjustViewBounds="true"
android:scaleType="fitXY"

pandas convert some columns into rows

UPDATE
From v0.20, melt is a first order function, you can now use

df.melt(id_vars=["location", "name"], 
        var_name="Date", 
        value_name="Value")

  location    name        Date  Value
0        A  "test"    Jan-2010     12
1        B   "foo"    Jan-2010     18
2        A  "test"    Feb-2010     20
3        B   "foo"    Feb-2010     20
4        A  "test"  March-2010     30
5        B   "foo"  March-2010     25

OLD(ER) VERSIONS: <0.20

You can use pd.melt to get most of the way there, and then sort:

>>> df
  location  name  Jan-2010  Feb-2010  March-2010
0        A  test        12        20          30
1        B   foo        18        20          25
>>> df2 = pd.melt(df, id_vars=["location", "name"], 
                  var_name="Date", value_name="Value")
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
1        B   foo    Jan-2010     18
2        A  test    Feb-2010     20
3        B   foo    Feb-2010     20
4        A  test  March-2010     30
5        B   foo  March-2010     25
>>> df2 = df2.sort(["location", "name"])
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
2        A  test    Feb-2010     20
4        A  test  March-2010     30
1        B   foo    Jan-2010     18
3        B   foo    Feb-2010     20
5        B   foo  March-2010     25

(Might want to throw in a .reset_index(drop=True), just to keep the output clean.)

Note: pd.DataFrame.sort has been deprecated in favour of pd.DataFrame.sort_values.

How to write Unicode characters to the console?

This works for me:

Console.OutputEncoding = System.Text.Encoding.Default;

To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:

  1. Open Command Prompt;

  2. Right click on the top bar of the Command Prompt;

  3. Click Properties;

  4. If the font is set to Raster Fonts, change it to Lucida Console.

How to set session timeout in web.config

The value you are setting in the timeout attribute is the one of the correct ways to set the session timeout value.

The timeout attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.

By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.

To test this, create a simple aspx page, and write this code in the Page_Load event,

Response.Write(Session.SessionID);

Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.

Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -

Session["UserId"] = 1;

Now, you will have to perform a check on every page for this variable like this -

if(Session["UserId"] == null)
    Response.Redirect("login.aspx");

This is a bare-bones example of how this will work.

But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.

Fully change package name including company domain

You can do this:

Change the package name manually in the manifest file. Click on your R.java class and the press F6 (Refactor->Move...). It will allow you to move the class to other package, and all references to that class will be updated.

reference: How do I rename the android package name?

How can I read a whole file into a string variable

I'm not with computer,so I write a draft. You might be clear of what I say.

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

How to concatenate text from multiple rows into a single text string in SQL server?

I really liked elegancy of Dana's answer. Just wanted to make it complete.

DECLARE @names VARCHAR(MAX)
SET @names = ''

SELECT @names = @names + ', ' + Name FROM Names 

-- Deleting last two symbols (', ')
SET @sSql = LEFT(@sSql, LEN(@sSql) - 1)

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

You can use ternary operator for conditional statements in dart, It's use is simple

(condition) ? statement1 : statement2

if the condition is true then the statement1 will be executed otherwise statement2.

Taking a practical example

Center(child: condition ? Widget1() : Widget2())

Remember if you are going to use null as Widget2 it is better to use SizedBox.shrink() because some parent widgets will throw an exception after getting a null child.

Git Clone: Just the files, please?

The git command that would be the closest from what you are looking for would by git archive.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all script)

You can then use that archive anywhere, giving you back only files, no .git directory.

git archive --remote=<repository URL> | tar -t

If you need folders and files just from the first level:

git archive --remote=<repository URL> | tar -t --exclude="*/*"

To list only first-level folders of a remote repo:

git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"

Note: that does not work for GitHub (not supported)

So you would need to clone (shallow to quicken the clone step), and then archive locally:

git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar

Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.

git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo

The repo folder would include only the file, without .git.

Note: git --git-dir is an option of the command git, not git clone.


Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.

"git archive", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.

See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 62b1cb7, 25 Sep 2017)

archive: don't add empty directories to archives

While git doesn't track empty directories, git archive can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.

As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty .gitignore file in it.

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

How to create an empty array in PHP with predefined size?

There is no way to create an array of a predefined size without also supplying values for the elements of that array.


The best way to initialize an array like that is array_fill. By far preferable over the various loop-and-insert solutions.

$my_array = array_fill(0, $size_of_the_array, $some_data);

Every position in the $my_array will contain $some_data.

The first zero in array_fill just indicates the index from where the array needs to be filled with the value.

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Before Mongo 3.6:

You may start mongodb with

mongod --httpinterface

And access it on

http://localhost:28017

Since version 2.6: MongoDB disables the HTTP interface by default.

Update

HTTP Interface and REST API

MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.

See Mongo http interface and rest api

Java 32-bit vs 64-bit compatibility

All byte code is 8-bit based. (That's why its called BYTE code) All the instructions are a multiple of 8-bits in size. We develop on 32-bit machines and run our servers with 64-bit JVM.

Could you give some detail of the problem you are facing? Then we might have a chance of helping you. Otherwise we would just be guessing what the problem is you are having.

How to handle-escape both single and double quotes in an SQL-Update statement

Depending on what language you are programming in, you can use a function to replace double quotes with two double quotes.

For example in PHP that would be:

str_replace('"', '""', $string);

If you are trying to do that using SQL only, maybe REPLACE() is what you are looking for.

So your query would look something like this:

"UPDATE Table SET columnname = '" & REPLACE(@wstring, '"', '""') & "' where ... blah ... blah "

How to export a CSV to Excel using Powershell

This is a slight variation that worked better for me.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets

$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True

$xl.Quit()

Excel VBA - select multiple columns not in sequential order

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

How to format numbers by prepending 0 to single-digit numbers?

I built a pretty simple format function that I call whenever I need a simple date formatted. It deals with formatting single digits to double digits when they're less than 10. It kicks out a date formatted as Sat Sep 29 2018 - 00:05:44

This function is used as part of a utils variable so it's called as:

let timestamp = utils._dateFormatter('your date string');

var utils = {
  _dateFormatter: function(dateString) {
    let d = new Date(dateString);
    let hours = d.getHours();
    let minutes = d.getMinutes();
    let seconds = d.getSeconds();
    d = d.toDateString();
    if (hours < 10) {
      hours = '0' + hours;
    }
    if (minutes < 10) {
      minutes = '0' + minutes;
    }
    if (seconds < 10) {
      seconds = '0' + seconds;
    }
    let formattedDate = d + ' - ' + hours + ':' + minutes + ':' + seconds;
    return formattedDate;
  }
}

How to automatically update an application without ClickOnce?

I think you should check the following project at codeplex.com http://autoupdater.codeplex.com/

This sample application is developed in C# as a library with the project name “AutoUpdater”. The DLL “AutoUpdater” can be used in a C# Windows application(WinForm and WPF).

There are certain features about the AutoUpdater:

  1. Easy to implement and use.
  2. Application automatic re-run after checking update.
  3. Update process transparent to the user.
  4. To avoid blocking the main thread using multi-threaded download.
  5. Ability to upgrade the system and also the auto update program.
  6. A code that doesn't need change when used by different systems and could be compiled in a library.
  7. Easy for user to download the update files.

How to use?

In the program that you want to be auto updateable, you just need to call the AutoUpdate function in the Main procedure. The AutoUpdate function will check the version with the one read from a file located in a Web Site/FTP. If the program version is lower than the one read the program downloads the auto update program and launches it and the function returns True, which means that an auto update will run and the current program should be closed. The auto update program receives several parameters from the program to be updated and performs the auto update necessary and after that launches the updated system.

  #region check and download new version program
  bool bSuccess = false;
  IAutoUpdater autoUpdater = new AutoUpdater();
  try
  {
      autoUpdater.Update();
      bSuccess = true;
  }
  catch (WebException exp)
  {
      MessageBox.Show("Can not find the specified resource");
  }
  catch (XmlException exp)
  {
      MessageBox.Show("Download the upgrade file error");
  }
  catch (NotSupportedException exp)
  {
      MessageBox.Show("Upgrade address configuration error");
  }
  catch (ArgumentException exp)
  {
      MessageBox.Show("Download the upgrade file error");
  }
  catch (Exception exp)
  {
      MessageBox.Show("An error occurred during the upgrade process");
  }
  finally
  {
      if (bSuccess == false)
      {
          try
          {
              autoUpdater.RollBack();
          }
          catch (Exception)
          {
             //Log the message to your file or database
          }
      }
  }
  #endregion

Force to open "Save As..." popup open at text link click for PDF in HTML

I just had a very similar issue with the added problem that I needed to create download links to files inside a ZIP file.

I first tried to create a temporary file, then provided a link to the temporary file, but I found that some browsers would just display the contents (a CSV Excel file) rather than offering to download. Eventually I found the solution by using a servlet. It works both on Tomcat and GlassFish, and I tried it on Internet Explorer 10 and Chrome.

The servlet takes as input a full path name to the ZIP file, and the name of the file inside the zip that should be downloaded.

Inside my JSP file I have a table displaying all the files inside the zip, with links that say: onclick='download?zip=<%=zip%>&csv=<%=csv%>'

The servlet code is in download.java:

package myServlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.zip.*;
import java.util.*;

// Extend HttpServlet class
public class download extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        PrintWriter out = response.getWriter(); // now we can write to the client

        String filename = request.getParameter("csv");
        String zipfile = request.getParameter("zip");

        String aLine = "";

        response.setContentType("application/x-download");
        response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
        ZipFile zip = new ZipFile(zipfile);
        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            if(entry.toString().equals(filename)) {
                InputStream is = zip.getInputStream(entry);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
                while ((aLine = br.readLine()) != null) {
                    out.println(aLine);
                }
                is.close();
                break;
            }
        }
    }
}

To compile on Tomcat you need the classpath to include tomcat\lib\servlet-api.jar or on GlassFish: glassfish\lib\j2ee.jar

But either one will work on both. You also need to set your servlet in web.xml.

"Please provide a valid cache path" error in laravel

The cause of this error can be traced from Illuminate\View\Compilers\Compiler.php

public function __construct(Filesystem $files, $cachePath)
{
    if (! $cachePath) {
        throw new InvalidArgumentException('Please provide a valid cache path.');
    }

    $this->files = $files;
    $this->cachePath = $cachePath;
}

The constructor is invoked by BladeCompiler in Illuminate\View\ViewServiceProvider

/**
 * Register the Blade engine implementation.
 *
 * @param  \Illuminate\View\Engines\EngineResolver  $resolver
 * @return void
 */
public function registerBladeEngine($resolver)
{
    // The Compiler engine requires an instance of the CompilerInterface, which in
    // this case will be the Blade compiler, so we'll first create the compiler
    // instance to pass into the engine so it can compile the views properly.
    $this->app->singleton('blade.compiler', function () {
        return new BladeCompiler(
            $this->app['files'], $this->app['config']['view.compiled']
        );
    });

    $resolver->register('blade', function () {
        return new CompilerEngine($this->app['blade.compiler']);
    });
}

So, tracing back further, the following code:

$this->app['config']['view.compiled']

is generally located in your /config/view.php, if you use the standard laravel structure.

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | View Storage Paths
    |--------------------------------------------------------------------------
    |
    | Most templating systems load templates from disk. Here you may specify
    | an array of paths that should be checked for your views. Of course
    | the usual Laravel view path has already been registered for you.
    |
    */
    'paths' => [
        resource_path('views'),
    ],
    /*
    |--------------------------------------------------------------------------
    | Compiled View Path
    |--------------------------------------------------------------------------
    |
    | This option determines where all the compiled Blade templates will be
    | stored for your application. Typically, this is within the storage
    | directory. However, as usual, you are free to change this value.
    |
    */
    'compiled' => realpath(storage_path('framework/views')),
];

realpath(...) returns false, if the path does not exist. Thus, invoking

'Please provide a valid cache path.' error.

Therefore, to get rid of this error, what you can do is to ensure that

storage_path('framework/views')

or

/storage/framework/views

exists :)

Prevent content from expanding grid items

The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr) instead of 1fr as your track size.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Use multiple custom fonts using @font-face?

I use this method in my css file

@font-face {
  font-family: FontName1;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName2;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
  font-family: FontName3;
  src: url("fontname1.eot"); /* IE */
  src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}

Sending private messages to user

This is pretty simple here is an example

Add your command code here like:

if (cmd === `!dm`) {
 let dUser =
  message.guild.member(message.mentions.users.first()) ||
  message.guild.members.get(args[0]);
 if (!dUser) return message.channel.send("Can't find user!");
 if (!message.member.hasPermission('ADMINISTRATOR'))
  return message.reply("You can't you that command!");
 let dMessage = args.join(' ').slice(22);
 if (dMessage.length < 1) return message.reply('You must supply a message!');

 dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);

 message.author.send(
  `${message.author} You have sent your message to ${dUser}`
 );
}

How to test that no exception is thrown?

JUnit5 adds the assertAll() method for this exact purpose.

assertAll( () -> foo() )

source: JUnit 5 API

How to mark-up phone numbers?

this worked for me:

1.make a standards compliant link:

        <a href="tel:1500100900">

2.replace it when mobile browser is not detected, for skype:

$("a.phone")
    .each(function()
{ 
  this.href = this.href.replace(/^tel/, 
     "callto");
});

Selecting link to replace via class seems more efficient. Of course it works only on anchors with .phone class.

I have put it in function if( !isMobile() ) { ... so it triggers only when detects desktop browser. But this one is problably obsolete...

function isMobile() {
    return (
        ( navigator.userAgent.indexOf( "iPhone" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPod" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "iPad" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "Android" ) > -1 ) ||
        ( navigator.userAgent.indexOf( "webOS" ) > -1 )
    );
}

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

In pydev eclipse plugin, you may want to set the environment variable for DYLD. The path can be set as shown in

Install mysqldb on snow leopard

JUNIT testing void methods

You can still unit test a void method by asserting that it had the appropriate side effect. In your method1 example, your unit test might look something like:

public void checkIfValidElementsWithDollarSign() {
    checkIfValidElement("$",19);
    assert ErrorFile.errorMessages.contains("There is a dollar sign in the specified parameter");
}

Javascript validation: Block special characters

A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

Vim clear last search highlighting

Disable search highlighting permanently

Matches won't be highlighted whenever you do a search using /

:set nohlsearch

Clear highlight until next search

:noh

or :nohlsearch (clears until n or N is pressed)


Clear highlight on pressing ESC

nnoremap <esc> :noh<return><esc>

Clear highlight on pressing another key or custom map

  • Clear highlights on pressing \ (backslash)

    nnoremap \ :noh<return>
    
  • Clear highlights on hitting ESC twice

    nnoremap <esc><esc> :noh<return>
    

Setting table column width

Here's another minimal way to do it in CSS that works even in older browsers that do not support :nth-child and the like selectors: http://jsfiddle.net/3wZWt/.

HTML:

<table>
    <tr>
        <th>From</th>
        <th>Subject</th>
        <th>Date</th>
    </tr>
    <tr>
        <td>Dmitriy</td>
        <td>Learning CSS</td>
        <td>7/5/2014</td>
    </tr>
</table>

CSS:

table {
    border-collapse: collapse;
    width: 100%;
}

tr > * {
    border: 1px solid #000;
}

tr > th + th {
    width: 70%;
}

tr > th + th + th {
    width: 15%;
}

Download File Using jQuery

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

What are the rules about using an underscore in a C++ identifier?

Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.

Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.

How to render pdfs using C#

There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself).

For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow:

In the last two I talk about a few things you can try:

  • You can get a commercial renderer (PDFViewForNet, PDFRasterizer.NET, ABCPDF, ActivePDF, XpdfRasterizer and others in the other answers...).
    Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails.

  • In addition to Omar Shahine's code snippet, there is a CodeProject article that shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF).

  • You could have a look at the source code for SumatraPDF, an OpenSource PDF viewer for windows.

  • There is also Poppler, a rendering engine that uses Xpdf as a rendering engine. All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL.

  • You may want to consider using GhostScript as an interpreter because rendering pages is a fairly simple process.
    The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process).
    It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net.
    I did a small project that you will find on the Developer Express forums as an attachment.
    Be careful of the license requirements for GhostScript through.
    If you can't leave with that then commercial software is probably your only choice.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Count Rows in Doctrine QueryBuilder

For people who are using only Doctrine DBAL and not the Doctrine ORM, they will not be able to access the getQuery() method because it doesn't exists. They need to do something like the following.

$qb = new QueryBuilder($conn);
$count = $qb->select("count(id)")->from($tableName)->execute()->fetchColumn(0);

creating custom tableview cells in swift

[1] First Design your tableview cell in StoryBoard.

[2] Put below table view delegate method

//MARK: - Tableview Delegate Methods

func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{

    return <“Your Array”>
}


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{

    var totalHeight : CGFloat = <cell name>.<label name>.frame.origin.y    

    totalHeight +=   UpdateRowHeight(<cell name>.<label name>, textToAdd: <your array>[indexPath.row])    

    return totalHeight
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{


    var cell : <cell name>! = tableView.dequeueReusableCellWithIdentifier(“<cell identifire>”, forIndexPath: indexPath) as! CCell_VideoCall

    if(cell == nil)
    {
        cell = NSBundle.mainBundle().loadNibNamed("<cell identifire>", owner: self, options: nil)[0] as! <cell name>;
    }


    <cell name>.<label name>.text = <your array>[indexPath.row] as? String



    return cell as <cell name>
}

//MARK: - Custom Methods

func UpdateRowHeight ( ViewToAdd : UILabel , textToAdd : AnyObject  ) -> CGFloat{


    var actualHeight : CGFloat = ViewToAdd.frame.size.height

    if let strName : String? = (textToAdd as? String)
        where !strName!.isEmpty
    {

        actualHeight = heightForView1(strName!, font: ViewToAdd.font, width: ViewToAdd.frame.size.width, DesignTimeHeight: actualHeight )

    }
    return actualHeight
}

How to remove class from all elements jquery

You could try this:

 $(".edgetoedge").children().removeClass("highlight");

Replacing a fragment with another fragment inside activity group

you can use simple code its work for transaction

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I believe this can be solved by adding a project reference to Microsoft.EntityFrameworkCore.SqlServer.Design

Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Microsoft.EntityFrameworkCore.SqlServer wasn't directly installed in my project, but the .Design package will install it anyway as a prerequisite.

ab load testing

I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.

the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".

the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!

but did anyone think to "localhost" on any apache server for example www.apachefriends.org?

you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".

and then: benchmark it!

bench.php

<?php

for($i=1;$i<50000;$i++){
    print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>

void.php

<?php
?>

on your Desktop you should use a .bat file(in Windows) like this:

bench.bat

"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause

Now if you pay attention closely ...

the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!

here i got :

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/void.php
Document Length:        0 bytes

Concurrency Level:      1
Time taken for tests:   11.219 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2150000 bytes
HTML transferred:       0 bytes
Requests per second:    891.34 [#/sec] (mean)
Time per request:       1.122 [ms] (mean)
Time per request:       1.122 [ms] (mean, across all concurrent requests)
Transfer rate:          187.15 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:     0    1   0.9      1      17
Waiting:        0    1   0.9      1      17
Total:          0    1   0.9      1      17

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      2
  98%      2
  99%      3
 100%     17 (longest request)

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/bench.php
Document Length:        1799964 bytes

Concurrency Level:      1
Time taken for tests:   177.006 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      18001600000 bytes
HTML transferred:       17999640000 bytes
Requests per second:    56.50 [#/sec] (mean)
Time per request:       17.701 [ms] (mean)
Time per request:       17.701 [ms] (mean, across all concurrent requests)
Transfer rate:          99317.00 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:    12   17   3.2     17      90
Waiting:        0    1   1.1      1      26
Total:         13   18   3.2     18      90

Percentage of the requests served within a certain time (ms)
  50%     18
  66%     19
  75%     19
  80%     20
  90%     21
  95%     22
  98%     23
  99%     26
 100%     90 (longest request)

c:\xampp\htdocs\bench>pause
Press any key to continue . . .

90-17= 73 the result i expect !

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Update for CXF 3.1.7

In my case I put the WSDL files in src/main/resources and added this path to my Srouces in Eclipse (Right Click on Project-> Build Path -> Configure Build Path...-> Source[Tab] -> Add Folder).

Here is how my pom file looks like and as can be seen there is NO wsdlLocation option needed:

       <plugin>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-codegen-plugin</artifactId>
            <version>${cxf.version}</version>
            <executions>
                <execution>
                    <id>generate-sources</id>
                    <phase>generate-sources</phase>
                    <configuration>
                        <sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
                        <wsdlOptions>
                            <wsdlOption>
                                <wsdl>classpath:wsdl/FOO_SERVICE.wsdl</wsdl>
                            </wsdlOption>
                        </wsdlOptions>
                    </configuration>
                    <goals>
                        <goal>wsdl2java</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

And here is the generated Service. As can be seen the URL is get from ClassLoader and not from the Absolute File-Path

@WebServiceClient(name = "EventService", 
              wsdlLocation = "classpath:wsdl/FOO_SERVICE.wsdl",
              targetNamespace = "http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/") 
public class EventService extends Service {

public final static URL WSDL_LOCATION;

public final static QName SERVICE = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventService");
public final static QName EventPort = new QName("http://www.sas.com/xml/schema/sas-svcs/rtdm-1.1/wsdl/", "EventPort");
static {
    URL url = EventService.class.getClassLoader().getResource("wsdl/FOO_SERVICE.wsdl");
    if (url == null) {
        java.util.logging.Logger.getLogger(EventService.class.getName())
            .log(java.util.logging.Level.INFO, 
                 "Can not initialize the default wsdl from {0}", "classpath:wsdl/FOO_SERVICE.wsdl");
    }       
    WSDL_LOCATION = url;   
}

How to use an output parameter in Java?

This is not accurate ---> "...* pass array. arrays are passed by reference. i.e. if you pass array of integers, modified the array inside the method.

Every parameter type is passed by value in Java. Arrays are object, its object reference is passed by value.

This includes an array of primitives (int, double,..) and objects. The integer value is changed by the methodTwo() but it is still the same arr object reference, the methodTwo() cannot add an array element or delete an array element. methodTwo() cannot also, create a new array then set this new array to arr. If you really can pass an array by reference, you can replace that arr with a brand new array of integers.

Every object passed as parameter in Java is passed by value, no exceptions.

Browse files and subfolders in Python

from tkinter import *
import os

root = Tk()
file = filedialog.askdirectory()
changed_dir = os.listdir(file)
print(changed_dir)
root.mainloop()

Reference excel worksheet by name?

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

Drag and drop elements from list into separate blocks

Dragging an object and placing in a different location is part of the standard of HTML5. All the objects can be draggable. But the Specifications of below web browser should be followed. API Chrome Internet Explorer Firefox Safari Opera Version 4.0 9.0 3.5 6.0 12.0

You can find example from below: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2

What does 'var that = this;' mean in JavaScript?

Sometimes this can refer to another scope and refer to something else, for example suppose you want to call a constructor method inside a DOM event, in this case this will refer to the DOM element not the created object.

HTML

<button id="button">Alert Name</button>

JS

var Person = function(name) {
  this.name = name;
  var that = this;
  this.sayHi = function() {
    alert(that.name);
  };
};

var ahmad = new Person('Ahmad');
var element = document.getElementById('button');
element.addEventListener('click', ahmad.sayHi); // => Ahmad

Demo

The solution above will assing this to that then we can and access the name property inside the sayHi method from that, so this can be called without issues inside the DOM call.

Another solution is to assign an empty that object and add properties and methods to it and then return it. But with this solution you lost the prototype of the constructor.

var Person = function(name) {
  var that = {};
  that.name = name;
  that.sayHi = function() {
    alert(that.name);
  };
  return that;
};

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

How to print object array in JavaScript?

you can use console.log() to print object

console.log(my_object_array);

in case you have big object and want to print some of its values then you can use this custom function to print array in console

this.print = function (data,bpoint=0) {
    var c = 0;
    for(var k=0; k<data.length; k++){
        c++;
        console.log(c+'  '+data[k]);
        if(k!=0 && bpoint === k)break;  
    }
}

usage

print(array);   // to print entire obj array

or

print(array,50);  // 50 value to print only 

Random number c++ in some range

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

How can I clear previous output in Terminal in Mac OS X?

I couldn't get any of the previous answers to work (on macOS).

A combination worked for me -

IO.write "\e[H\e[2J\e[3J"

This clears the buffer and the screen.

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

What type of hash does WordPress use?

include_once('../../../wp-config.php');

global $wpdb;

$password = wp_hash_password("your password");

Select tableview row programmatically

Use this category to select a table row and execute a given segue after a delay.
Call this within your viewDidAppear method:

[tableViewController delayedSelection:withSegueIdentifier:]


@implementation UITableViewController (TLUtils)

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                                                                                                                                                 
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                                                                                               
}

-(void)selectIndexPath:(NSDictionary *)args {
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                                                                                                                                                                         
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                                                                                                            

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                                                                                                                              

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                                                                                                                                            
}

@end

Location of ini/config files in linux/unix?

  1. Typically in a dotfile (like .myprogramrc) in the user's home directory.
  2. It is of course up to the programmer but normally command line arguments override everything else. If environment variables are used it is usually as an alternative to the command line arguments or to specify where the configuration is located.

Git pull command from different user

Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.

Posting this answer here since I think this is the intended question

So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.

How to pull from the repo without using the credentials of the old user ?

You edit the .git/config file of your repo.

and change

url = https://<old-username>@github.com/abc/repo.git/

to

url = https://<new-username>@github.com/abc/repo.git/

After saving the changes, from now onwards git pull will pull data while using credentials of the new user.

I hope this helps anyone with a similar problem

Java Read Large Text File With 70million line of text

I tried the following three methods, my file size is 1M, and I got results:

enter image description here

I run the program several times it looks that BufferedReader is faster.

@Test
public void testLargeFileIO_Scanner() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    InputStream inputStream = new FileInputStream(fileName);

    try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            //System.out.println(line);
        }
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Scanner Time Consumed => " + time);

}


@Test
 public void testLargeFileIO_BufferedReader() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
        String fileLineContent;
        while ((fileLineContent = fileBufferReader.readLine()) != null) {
            //System.out.println(fileLineContent);
        }
    }
    long end = new Date().getTime();

    long time = (long) (end - start);
    System.out.println("BufferedReader Time Consumed => " + time);

}


@Test
public void testLargeFileIO_Stream() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
        //inputStream.forEach(System.out::println);
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Stream Time Consumed => " + time);

}

how to take user input in Array using java?

package userinput;

import java.util.Scanner;

public class USERINPUT {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        //allow user  input;
        System.out.println("How many numbers do you want to enter?");
        int num = input.nextInt();

        int array[] = new int[num];

        System.out.println("Enter the " + num + " numbers now.");

        for (int i = 0 ; i < array.length; i++ ) {
           array[i] = input.nextInt();
        }

        //you notice that now the elements have been stored in the array .. array[]

        System.out.println("These are the numbers you have entered.");
        printArray(array);

        input.close();

    }

    //this method prints the elements in an array......
    //if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
    public static void printArray(int arr[]){

        int n = arr.length;

        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }

}

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Google MAP API v3: Center & Zoom on displayed markers

Try this function....it works...

$(function() {
        var myOptions = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
        var latlng_pos=[];
        var j=0;
         $(".property_item").each(function(){
            latlng_pos[j]=new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val());
            j++;
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng($(this).find(".latitude").val(),$(this).find(".longitude").val()),
                // position: new google.maps.LatLng(-35.397, 150.640),
                map: map
            });
        }
        );
        // map: an instance of google.maps.Map object
        // latlng: an array of google.maps.LatLng objects
        var latlngbounds = new google.maps.LatLngBounds( );
        for ( var i = 0; i < latlng_pos.length; i++ ) {
            latlngbounds.extend( latlng_pos[ i ] );
        }
        map.fitBounds( latlngbounds );



    });

MySQL Data Source not appearing in Visual Studio

I was having the same problem just now. I solved it by uninstalling the latest Connector/NET drivers (6.7.4) and then installed the older drivers (6.6.5) and it works.

I am using Visual Studio 2010. I uninstalled the latest ones because I figured they were somehow related to .NET4.5, which I'm not able to use.


Update #1:

Supposedly another way is to register the MySql Connector with various Visual Studio versions (2010/2012/2013/2015...) during installation: Go to Modify Product Features and select all the relevant Visual Studio versions.

see Image


Update #2 - Visual Studio 2019 Update:

When I installed MySQL Community with the ConnectorNET and VisualStudio Plugin options included - MySQL didn't show up as a data provider in Visual Studio.

The installer I used included the VS Plugin version 1.2.9, which had supposedly fixed installation issues from 1.2.8, but still didn't work for me...

The solution for me was to uninstall the Connector and the Visual Studio Plugin, download them as individual components, and then install them separately (not as part of the MySQLServer Installer). Install the Connector first, then VS plugin after.

I found the solution here, Thanks to @LambertHeenan.


NOTE about Visual Studio Express

The OP asks whether MySQL is supported with Visual Studio Express (which as far as I can tell has been renamed to Visual Studio Community). In the past MySQL officially didn't support Visual Studio Express, as per @Paul's answer below, but they do officially support Visual Studio Community 2017 and 2019, according to this page.

How to generate a number of most distinctive colors in R?

I would recomend to use an external source for large color palettes.

http://tools.medialab.sciences-po.fr/iwanthue/

has a service to compose any size of palette according to various parameters and

https://graphicdesign.stackexchange.com/questions/3682/where-can-i-find-a-large-palette-set-of-contrasting-colors-for-coloring-many-d/3815

discusses the generic problem from a graphics designers perspective and gives lots of examples of usable palettes.

To comprise a palette from RGB values you just have to copy the values in a vector as in e.g.:

colors37 = c("#466791","#60bf37","#953ada","#4fbe6c","#ce49d3","#a7b43d","#5a51dc","#d49f36","#552095","#507f2d","#db37aa","#84b67c","#a06fda","#df462a","#5b83db","#c76c2d","#4f49a3","#82702d","#dd6bbb","#334c22","#d83979","#55baad","#dc4555","#62aad3","#8c3025","#417d61","#862977","#bba672","#403367","#da8a6d","#a79cd4","#71482c","#c689d0","#6b2940","#d593a7","#895c8b","#bd5975")

Python integer incrementing with ++

You can do:

number += 1

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

Setting custom UITableViewCells height

Your UITableViewDelegate should implement tableView:heightForRowAtIndexPath:

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 20;
}

Swift 5

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return indexPath.row * 20
}

You will probably want to use NSString's sizeWithFont:constrainedToSize:lineBreakMode: method to calculate your row height rather than just performing some silly math on the indexPath :)

Browser detection

use from

Request.Browser

this link will help you :

Detect the browser using ASP.NET and C#

JavaScript closures vs. anonymous functions

In a nutshell Javascript Closures allow a function to access a variable that is declared in a lexical-parent function.

Let's see a more detailed explanation. To understand closures it is important to understand how JavaScript scopes variables.

Scopes

In JavaScript scopes are defined with functions. Every function defines a new scope.

Consider the following example;

function f()
{//begin of scope f
  var foo='hello'; //foo is declared in scope f
  for(var i=0;i<2;i++){//i is declared in scope f
     //the for loop is not a function, therefore we are still in scope f
     var bar = 'Am I accessible?';//bar is declared in scope f
     console.log(foo);
  }
  console.log(i);
  console.log(bar);
}//end of scope f

calling f prints

hello
hello
2
Am I Accessible?

Let's now consider the case we have a function g defined within another function f.

function f()
{//begin of scope f
  function g()
  {//being of scope g
    /*...*/
  }//end of scope g
  /*...*/
}//end of scope f

We will call f the lexical parent of g. As explained before we now have 2 scopes; the scope f and the scope g.

But one scope is "within" the other scope, so is the scope of the child function part of the scope of the parent function? What happens with the variables declared in the scope of the parent function; will I be able to access them from the scope of the child function? That's exactly where closures step in.

Closures

In JavaScript the function g can not only access any variables declared in scope g but also access any variables declared in the scope of the parent function f.

Consider following;

function f()//lexical parent function
{//begin of scope f
  var foo='hello'; //foo declared in scope f
  function g()
  {//being of scope g
    var bar='bla'; //bar declared in scope g
    console.log(foo);
  }//end of scope g
  g();
  console.log(bar);
}//end of scope f

calling f prints

hello
undefined

Let's look at the line console.log(foo);. At this point we are in scope g and we try to access the variable foo that is declared in scope f. But as stated before we can access any variable declared in a lexical parent function which is the case here; g is the lexical parent of f. Therefore hello is printed.
Let's now look at the line console.log(bar);. At this point we are in scope f and we try to access the variable bar that is declared in scope g. bar is not declared in the current scope and the function g is not the parent of f, therefore bar is undefined

Actually we can also access the variables declared in the scope of a lexical "grand parent" function. Therefore if there would be a function h defined within the function g

function f()
{//begin of scope f
  function g()
  {//being of scope g
    function h()
    {//being of scope h
      /*...*/
    }//end of scope h
    /*...*/
  }//end of scope g
  /*...*/
}//end of scope f

then h would be able to access all the variables declared in the scope of function h, g, and f. This is done with closures. In JavaScript closures allows us to access any variable declared in the lexical parent function, in the lexical grand parent function, in the lexical grand-grand parent function, etc. This can be seen as a scope chain; scope of current function -> scope of lexical parent function -> scope of lexical grand parent function -> ... until the last parent function that has no lexical parent.

The window object

Actually the chain doesn't stop at the last parent function. There is one more special scope; the global scope. Every variable not declared in a function is considered to be declared in the global scope. The global scope has two specialities;

  • every variable declared in the global scope is accessible everywhere
  • the variables declared in the global scope correspond to the properties of the window object.

Therefore there are exactly two ways of declaring a variable foo in the global scope; either by not declaring it in a function or by setting the property foo of the window object.

Both attempts uses closures

Now that you have read a more detailed explanation it may now be apparent that both solutions uses closures. But to be sure, let's make a proof.

Let's create a new Programming Language; JavaScript-No-Closure. As the name suggests, JavaScript-No-Closure is identical to JavaScript except it doesn't support Closures.

In other words;

var foo = 'hello';
function f(){console.log(foo)};
f();
//JavaScript-No-Closure prints undefined
//JavaSript prints hello

Alright, let's see what happens with the first solution with JavaScript-No-Closure;

for(var i = 0; i < 10; i++) {
  (function(){
    var i2 = i;
    setTimeout(function(){
        console.log(i2); //i2 is undefined in JavaScript-No-Closure 
    }, 1000)
  })();
}

therefore this will print undefined 10 times in JavaScript-No-Closure.

Hence the first solution uses closure.

Let's look at the second solution;

for(var i = 0; i < 10; i++) {
  setTimeout((function(i2){
    return function() {
        console.log(i2); //i2 is undefined in JavaScript-No-Closure
    }
  })(i), 1000);
}

therefore this will print undefined 10 times in JavaScript-No-Closure.

Both solutions uses closures.

Edit: It is assumed that these 3 code snippets are not defined in the global scope. Otherwise the variables foo and i would be bind to the window object and therefore accessible through the window object in both JavaScript and JavaScript-No-Closure.

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Base64 length calculation?

If there is someone interested in achieve the @Pedro Silva solution in JS, I just ported this same solution for it:

const getBase64Size = (base64) => {
  let padding = base64.length
    ? getBase64Padding(base64)
    : 0
  return ((Math.ceil(base64.length / 4) * 3 ) - padding) / 1000
}

const getBase64Padding = (base64) => {
  return endsWith(base64, '==')
    ? 2
    : 1
}

const endsWith = (str, end) => {
  let charsFromEnd = end.length
  let extractedEnd = str.slice(-charsFromEnd)
  return extractedEnd === end
}

pycharm convert tabs to spaces automatically

For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.

How to set the width of a RaisedButton in Flutter?

Simply use FractionallySizedBox, where widthFactor & heightFactor define the percentage of app/parent size.

FractionallySizedBox(
widthFactor: 0.8,   //means 80% of app width
child: RaisedButton(
  onPressed: () {},
  child: Text(
    "Your Text",
    style: TextStyle(color: Colors.white),
  ),
  color: Colors.red,
)),

AngularJS ng-if with multiple conditions

you can also try with && for mandatory constion if both condtion are true than work

//div ng-repeat="(k,v) in items"

<div ng-if="(k == 'a' &&  k == 'b')">
    <!-- SOME CONTENT -->
</div>

Call break in nested if statements

If you label the if statement you can use break.

breakme: if (condition) {
    // Do stuff

    if (condition2){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

You can even label and break plain blocks.

breakme: {
    // Do stuff

    if (condition){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.

( function() {
   // Do stuff

   if ( condition1 ) {
       // Do stuff 
   } else {
       return;
   }

   // Do other stuff
}() );

Delimiters in MySQL

The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.

Why do we have to change the delimiter?

Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Use

export LD_LIBRARY_PATH="/path/to/library/"

in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

EDIT: Looks like -R is Solaris only, and you're on Linux.

An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

ReSharper "Cannot resolve symbol" even when project builds

This was happening to me with Visual Studio 2015 and ReSharper Ultimate 10.0.2. I tried pretty much all the solutions written prior to this answer (apart from any reinstallations) and nothing worked.

I got it working again with a variety of the above steps in a very specific order:

  1. ReSharper ? Options ? Environment ? General ? Clear Caches
    • this must be done before suspending ReSharper as otherwise this option is unavailable
    • this clears out the files in C:\Users\YourUsername\AppData\Local\JetBrains\Transient\ReSharperPlatformVs14\v04 as mentioned in some other posts
  2. Tools ? Options ? ReSharper Ultimate ? Suspend
  3. Close Visual Studio
    • this actually performs the ReSharper cache clear
  4. Open Visual Studio
  5. Open the solution
    • I waited for Visual Studio to detect there were no code issues in IntelliSense and may have performed a build at this point.
  6. Tools ? Options ? ReSharper Ultimate ? Resume

Hopefully after the last step you can breathe a sigh of relief that you don't have to reinstall anything, I certainly did!

Javascript: Fetch DELETE and PUT requests

For put method we have:

const putMethod = {
 method: 'PUT', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 body: JSON.stringify(someData) // We send data in JSON format
}

// make the HTTP put request using fetch api
fetch(url, putMethod)
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

Example for someData, we can have some input fields or whatever you need:

const someData = {
 title: document.querySelector(TitleInput).value,
 body: document.querySelector(BodyInput).value
}

And in our data base will have this in json format:

{
 "posts": [
   "id": 1,
   "title": "Some Title", // what we typed in the title input field
   "body": "Some Body", // what we typed in the body input field
 ]
}

For delete method we have:

const deleteMethod = {
 method: 'DELETE', // Method itself
 headers: {
  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
 },
 // No need to have body, because we don't send nothing to the server.
}
// Make the HTTP Delete call using fetch api
fetch(url, deleteMethod) 
.then(response => response.json())
.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
.catch(err => console.log(err)) // Do something with the error

In the url we need to type the id of the of deletion: https://www.someapi/id

Merge / convert multiple PDF files into one PDF

This is the easiest solution if you have multiple files and do not want to type in the names one by one:

qpdf --empty --pages *.pdf -- out.pdf

Stash just a single file

I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:

Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.

# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master

go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

In my case this error appeared when I asigned to both dynamic created controls (combobox), same created control from other class.

//dynamic created controls
ComboBox combobox1 = ManagerControls.myCombobox1;
...some events

ComboBox combobox2 = ManagerControl.myComboBox2;
...some events

.

//method in constructor
public static void InitializeDynamicControls()
{
     ComboBox cb = new ComboBox();
     cb.Background = new SolidColorBrush(Colors.Blue);
     ...
     cb.Width = 100;
     cb.Text = "Select window";
        
     ManagerControls.myCombobox1 = cb;
     ManagerControls.myComboBox2 = cb; // <-- error here
}

Solution: create another ComboBox cb2 and assign it to ManagerControls.myComboBox2.

I hope I helped someone.

Simple java program of pyramid

public static void showPyramid(int level)
{
    for(int i=0;i<level;i++)
    {
        for(int j=0;j<level-i-1;j++)
        {
            System.out.print(" ");
        }
        for(int k=level-i;k<=level;k++)
        {
            System.out.print("*");
        }
        for(int k=level-i;k<level;k++)
        {
            System.out.print("*");
        }
        for(int j=0;j<level-i;j++)
        {
            System.out.print(" ");
        }

        System.out.print("\n");
    }

}

Output

     *          
    ***         
   *****        
  *******       
 *********      
***********     




Location of the android sdk has not been setup in the preferences in mac os?

If you have not installed plugin for eclipse, install it first.

If the plugin is installed, setup preferences: "Eclipse">"Preferences...", in left column choose "Android"(do not expand list, just choose root element), and first preference will be "SDK Location".

Replace all non-alphanumeric characters in a string

Try:

s = filter(str.isalnum, s)

in Python3:

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

Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit

Add horizontal scrollbar to html table

Insert the table inside a div, so the table will take full length

HTML

<div class="scroll">
 <table>  </table>
</div>   

CSS

.scroll{
    overflow-x: auto;
    white-space: nowrap;
}

How to strip all non-alphabetic characters from string in SQL Server?

I knew that SQL was bad at string manipulation, but I didn't think it would be this difficult. Here's a simple function to strip out all the numbers from a string. There would be better ways to do this, but this is a start.

CREATE FUNCTION dbo.AlphaOnly (
    @String varchar(100)
)
RETURNS varchar(100)
AS BEGIN
  RETURN (
    REPLACE(
      REPLACE(
        REPLACE(
          REPLACE(
            REPLACE(
              REPLACE(
                REPLACE(
                  REPLACE(
                    REPLACE(
                      REPLACE(
                        @String,
                      '9', ''),
                    '8', ''),
                  '7', ''),
                '6', ''),
              '5', ''),
            '4', ''),
          '3', ''),
        '2', ''),
      '1', ''),
    '0', '')
  )
END
GO

-- ==================
DECLARE @t TABLE (
    ColID       int,
    ColString   varchar(50)
)

INSERT INTO @t VALUES (1, 'abc1234567890')

SELECT ColID, ColString, dbo.AlphaOnly(ColString)
FROM @t

Output

ColID ColString
----- ------------- ---
    1 abc1234567890 abc

Round 2 - Data-Driven Blacklist

-- ============================================
-- Create a table of blacklist characters
-- ============================================
IF EXISTS (SELECT * FROM sys.tables WHERE [object_id] = OBJECT_ID('dbo.CharacterBlacklist'))
  DROP TABLE dbo.CharacterBlacklist
GO
CREATE TABLE dbo.CharacterBlacklist (
    CharID              int         IDENTITY,
    DisallowedCharacter nchar(1)    NOT NULL
)
GO
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'0')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'1')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'2')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'3')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'4')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'5')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'6')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'7')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'8')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'9')
GO

-- ====================================
IF EXISTS (SELECT * FROM sys.objects WHERE [object_id] = OBJECT_ID('dbo.StripBlacklistCharacters'))
  DROP FUNCTION dbo.StripBlacklistCharacters
GO
CREATE FUNCTION dbo.StripBlacklistCharacters (
    @String nvarchar(100)
)
RETURNS varchar(100)
AS BEGIN
  DECLARE @blacklistCt  int
  DECLARE @ct           int
  DECLARE @c            nchar(1)

  SELECT @blacklistCt = COUNT(*) FROM dbo.CharacterBlacklist

  SET @ct = 0
  WHILE @ct < @blacklistCt BEGIN
    SET @ct = @ct + 1

    SELECT @String = REPLACE(@String, DisallowedCharacter, N'')
    FROM dbo.CharacterBlacklist
    WHERE CharID = @ct
  END

  RETURN (@String)
END
GO

-- ====================================
DECLARE @s  nvarchar(24)
SET @s = N'abc1234def5678ghi90jkl'

SELECT
    @s                  AS OriginalString,
    dbo.StripBlacklistCharacters(@s)   AS ResultString

Output

OriginalString           ResultString
------------------------ ------------
abc1234def5678ghi90jkl   abcdefghijkl

My challenge to readers: Can you make this more efficient? What about using recursion?

Convert string (without any separator) to list

I know this question has been answered, but just to point out what timeit has to say about the solutions efficiency. Using these parameters:

size = 30
s = [str(random.randint(0, 9)) for i in range(size)] + (size/3) * ['-']
random.shuffle(s)
s = ''.join(['+'] + s)
timec = 1000

That is the "phone number" has 30 digits, 1 plus sing and 10 '-'. I've tested these approaches:

def justdigits(s):
    justdigitsres = ""
    for char in s:
        if char.isdigit():
            justdigitsres += str(char)
    return justdigitsres

re_compiled = re.compile(r'\D')

print('Filter: %ss' % timeit.Timer(lambda : ''.join(filter(str.isdigit, s))).timeit(timec))
print('GE: %ss' % timeit.Timer(lambda : ''.join(n for n in s if n.isdigit())).timeit(timec))
print('LC: %ss' % timeit.Timer(lambda : ''.join([n for n in s if n.isdigit()])).timeit(timec))
print('For loop: %ss' % timeit.Timer(lambda : justdigits(s)).timeit(timec))
print('RE: %ss' % timeit.Timer(lambda : re.sub(r'\D', '', s)).timeit(timec))
print('REC: %ss' % timeit.Timer(lambda : re_compiled.sub('', s)).timeit(timec))
print('Translate: %ss' % timeit.Timer(lambda : s.translate(None, '+-')).timeit(timec))

And came out with these results:

Filter: 0.0145790576935s
GE: 0.0185861587524s
LC: 0.0151798725128s
For loop: 0.0242128372192s
RE: 0.0120108127594s
REC: 0.00868797302246s
Translate: 0.00118899345398s

Apparently GEs and LCs are still slower than a regex or a compiled regex. And apparently my CPython 2.6.6 didn't optimize the string addition that much. translate appears to be the fastest (which is expected as the problem is stated as "ignore these two symbols", rather than "get these numbers" and I believe is quite low-level).

And for size = 100:

Filter: 0.0357120037079s
GE: 0.0465779304504s
LC: 0.0428011417389s
For loop: 0.0733139514923s
RE: 0.0213229656219s
REC: 0.0103371143341s
Translate: 0.000978946685791s

And for size = 1000:

Filter: 0.212141036987s
GE: 0.198996067047s
LC: 0.196880102158s
For loop: 0.365696907043s
RE: 0.0880808830261s
REC: 0.086804151535s
Translate: 0.00587010383606s

Remove shadow below actionbar

Add this toolbar.getBackground().setAlpha(0); to inside OnCreate method. The add this: android:elevation="0dp" android:background="@android:color/transparent to your toolbar xml file.

Can HTTP POST be limitless?

In an application I was developing I ran into what appeared to be a POST limit of about 2KB. It turned out to be that I was accidentally encoding the parameters into the URL instead of passing them in the body. So if you're running into a problem there, there is definitely a very small limit on the size of POST data you can send encoded into the URL.

Exception: Can't bind to 'ngFor' since it isn't a known native property

Use this

<div *ngFor="let talk of talks> 
   {{talk.title}} 
   {{talk.speaker}}
   <p>{{talk.description}} 
</div>

You need to specify variable to iterate over an array of an object

How do I use jQuery to redirect?

I found out why this happening.

After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.

Thank you everyone for trying to solve this. :)

How to read pickle file?

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

jQuery $.ajax request of dataType json will not retrieve data from PHP script

Try using jQuery.parseJSON when you get the data back.

type: "POST",
dataType: "json",
url: url,
data: { get_member: id },
success: function(data) { 
    response = jQuery.parseJSON(data);
    $("input[ name = type ]:eq(" + response.type + " )")
        .attr("checked", "checked");
    $("input[ name = name ]").val( response.name);
    $("input[ name = fname ]").val( response.fname);
    $("input[ name = lname ]").val( response.lname);
    $("input[ name = email ]").val( response.email);
    $("input[ name = phone ]").val( response.phone);
    $("input[ name = website ]").val( response.website);
    $("#admin_member_img")
        .attr("src", "images/member_images/" + response.image);
},
error: function(error) {
    alert(error);
}

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00

Creating a DateTime in a specific Time Zone in c#

You'll have to create a custom object for that. Your custom object will contain two values:

Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.

Get data type of field in select statement in ORACLE

You can query the all_tab_columns view in the database.

SELECT  table_name, column_name, data_type, data_length FROM all_tab_columns where table_name = 'CUSTOMER'

Jquery Change Height based on Browser Size/Resize

Building on Chad's answer, you also want to add that function to the onload event to ensure it is resized when the page loads as well.

jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);

function resizeFrame() 
{
    var h = $(window).height();
    var w = $(window).width();
    $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
}

How do I run Redis on Windows?

You can try out baboonstack, which includes redis and also a node.js and mongoDB version manager. And it's cross platform.

IOException: Too many open files

Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.

Send response to all clients except sender

Other cases

io.of('/chat').on('connection', function (socket) {
    //sending to all clients in 'room' and you
    io.of('/chat').in('room').emit('message', "data");
};

Target class controller does not exist - Laravel 8

On a freshly installed laravel 8, in the App/Providers/RouteServices.php

    * The path to the "home" route for your application.
 *
 * This is used by Laravel authentication to redirect users after login.
 *
 * @var string
 */
public const HOME = '/home';

/**
 * The controller namespace for the application.
 *
 * When present, controller route declarations will automatically be prefixed with this namespace.
 *
 * @var string|null
 */
// protected $namespace = 'App\\Http\\Controllers';

uncomment the

protected $namespace = 'App\Http\Controllers';

that should help you run laravel the old fashioned way.

Incase you are upgrading from lower versions of laravel to 8 then you might have to implicitly add the

protected $namespace = 'App\Http\Controllers';

in the RouteServices.php file for it to function the old way.

splitting a number into the integer and decimal parts

If you don't mind using NumPy, then:

In [319]: real = np.array([1234.5678])

In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1)

In [328]: integ, deci
Out[328]: (1234, 0.5678000000000338)

Shell Script — Get all files modified after <date>

This script will find files having a modification date of two minutes before and after the given date (and you can change the values in the conditions as per your requirement)

PATH_SRC="/home/celvas/Documents/Imp_Task/"
PATH_DST="/home/celvas/Downloads/zeeshan/"

cd $PATH_SRC
TODAY=$(date  -d "$(date +%F)" +%s)
TODAY_TIME=$(date -d "$(date +%T)" +%s)


for f in `ls`;
do
#       echo "File -> $f"
        MOD_DATE=$(stat -c %y "$f")
        MOD_DATE=${MOD_DATE% *}
#       echo MOD_DATE: $MOD_DATE
        MOD_DATE1=$(date -d "$MOD_DATE" +%s)
#       echo MOD_DATE: $MOD_DATE

DIFF_IN_DATE=$[ $MOD_DATE1 - $TODAY ]
DIFF_IN_DATE1=$[ $MOD_DATE1 - $TODAY_TIME ]
#echo DIFF: $DIFF_IN_DATE
#echo DIFF1: $DIFF_IN_DATE1
if [[ ($DIFF_IN_DATE -ge -120) && ($DIFF_IN_DATE1 -le 120) && (DIFF_IN_DATE1 -ge -120) ]]
then
echo File lies in Next Hour = $f
echo MOD_DATE: $MOD_DATE

#mv $PATH_SRC/$f  $PATH_DST/$f
fi
done

For example you want files having modification date before the given date only, you may change 120 to 0 in $DIFF_IN_DATE parameter discarding the conditions of $DIFF_IN_DATE1 parameter.

Similarly if you want files having modification date 1 hour before and after given date, just replace 120 by 3600 in if CONDITION.

Is "delete this" allowed in C++?

The C++ FAQ Lite has a entry specifically for this

I think this quote sums it up nicely

As long as you're careful, it's OK for an object to commit suicide (delete this).

webpack: Module not found: Error: Can't resolve (with relative path)

I had a different problem. some of my includes were set to 'app/src/xxx/yyy' instead of '../xxx/yyy'

How to get SLF4J "Hello World" working with log4j?

Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.

  • Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
  • Configure log4j.properties

    log4j.rootLogger=TRACE, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
    
  • Java example

    public class Slf4jExample {
        public static void main(String[] args) {
    
            Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
    
            final String message = "Hello logging!";
            logger.trace(message);
            logger.debug(message);
            logger.info(message);
            logger.warn(message);
            logger.error(message);
        }
    }
    

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

How to count how many values per level in a given factor?

Using plyr package:

library(plyr)

count(mydf$V1)

It will return you a frequency of each value.

How do I pass parameters to a jar file at the time of execution?

The JAVA Documentation says:

java [ options ] -jar file.jar [ argument ... ]

and

... Non-option arguments after the class name or JAR file name are passed to the main function...

Maybe you have to put the arguments in single quotes.

How to display activity indicator in middle of the iphone screen?

If you are using Swift, this is how you do it

let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = self.view.center
activityView.startAnimating()

self.view.addSubview(activityView)

Apache: Restrict access to specific source IP inside virtual host

In Apache 2.4, the authorization configuration syntax has changed, and the Order, Deny or Allow directives should no longer be used.

The new way to do this would be:

<VirtualHost *:8080>
    <Location />
        Require ip 192.168.1.0
    </Location>
    ...
</VirtualHost>

Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

You can avoid compiler warning with workarounds like this one:

List<?> resultRaw = query.list();
List<MyObj> result = new ArrayList<MyObj>(resultRaw.size());
for (Object o : resultRaw) {
    result.add((MyObj) o);
}

But there are some issues with this code:

  • created superfluous ArrayList
  • unnecessary loop over all elements returned from the query
  • longer code.

And the difference is only cosmetic, so using such workarounds is - in my opinion - pointless.

You have to live with these warnings or suppress them.

Change the Theme in Jupyter Notebook?

You Can Follow These Steps.

  1. pip install jupyterthemes or pip install --upgrade jupyterthemes to upgrade to latest version of theme.
  2. after that to list all the themes you have :jt -l
  3. after that jt-t <themename>for example jt -t solarizedl

setup.py examples?

Look at this complete example https://github.com/marcindulak/python-mycli of a small python package. It is based on packaging recommendations from https://packaging.python.org/en/latest/distributing.html, uses setup.py with distutils and in addition shows how to create RPM and deb packages.

The project's setup.py is included below (see the repo for the full source):

#!/usr/bin/env python

import os
import sys

from distutils.core import setup

name = "mycli"

rootdir = os.path.abspath(os.path.dirname(__file__))

# Restructured text project description read from file
long_description = open(os.path.join(rootdir, 'README.md')).read()

# Python 2.4 or later needed
if sys.version_info < (2, 4, 0, 'final', 0):
    raise SystemExit, 'Python 2.4 or later is required!'

# Build a list of all project modules
packages = []
for dirname, dirnames, filenames in os.walk(name):
        if '__init__.py' in filenames:
            packages.append(dirname.replace('/', '.'))

package_dir = {name: name}

# Data files used e.g. in tests
package_data = {name: [os.path.join(name, 'tests', 'prt.txt')]}

# The current version number - MSI accepts only version X.X.X
exec(open(os.path.join(name, 'version.py')).read())

# Scripts
scripts = []
for dirname, dirnames, filenames in os.walk('scripts'):
    for filename in filenames:
        if not filename.endswith('.bat'):
            scripts.append(os.path.join(dirname, filename))

# Provide bat executables in the tarball (always for Win)
if 'sdist' in sys.argv or os.name in ['ce', 'nt']:
    for s in scripts[:]:
        scripts.append(s + '.bat')

# Data_files (e.g. doc) needs (directory, files-in-this-directory) tuples
data_files = []
for dirname, dirnames, filenames in os.walk('doc'):
        fileslist = []
        for filename in filenames:
            fullname = os.path.join(dirname, filename)
            fileslist.append(fullname)
        data_files.append(('share/' + name + '/' + dirname, fileslist))

setup(name='python-' + name,
      version=version,  # PEP440
      description='mycli - shows some argparse features',
      long_description=long_description,
      url='https://github.com/marcindulak/python-mycli',
      author='Marcin Dulak',
      author_email='[email protected]',
      license='ASL',
      # https://pypi.python.org/pypi?%3Aaction=list_classifiers
      classifiers=[
          'Development Status :: 1 - Planning',
          'Environment :: Console',
          'License :: OSI Approved :: Apache Software License',
          'Natural Language :: English',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.4',
          'Programming Language :: Python :: 2.5',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.2',
          'Programming Language :: Python :: 3.3',
          'Programming Language :: Python :: 3.4',
      ],
      keywords='argparse distutils cli unittest RPM spec deb',
      packages=packages,
      package_dir=package_dir,
      package_data=package_data,
      scripts=scripts,
      data_files=data_files,
      )

and and RPM spec file which more or less follows Fedora/EPEL packaging guidelines may look like:

# Failsafe backport of Python2-macros for RHEL <= 6
%{!?python_sitelib: %global python_sitelib      %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")}
%{!?python_sitearch:    %global python_sitearch     %(%{__python} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(1))")}
%{!?python_version: %global python_version      %(%{__python} -c "import sys; sys.stdout.write(sys.version[:3])")}
%{!?__python2:      %global __python2       %{__python}}
%{!?python2_sitelib:    %global python2_sitelib     %{python_sitelib}}
%{!?python2_sitearch:   %global python2_sitearch    %{python_sitearch}}
%{!?python2_version:    %global python2_version     %{python_version}}

%{!?python2_minor_version: %define python2_minor_version %(%{__python} -c "import sys ; print sys.version[2:3]")}

%global upstream_name mycli


Name:           python-%{upstream_name}
Version:        0.0.1
Release:        1%{?dist}
Summary:        A Python program that demonstrates usage of argparse
%{?el5:Group:       Applications/Scientific}
License:        ASL 2.0

URL:            https://github.com/marcindulak/%{name}
Source0:        https://github.com/marcindulak/%{name}/%{name}-%{version}.tar.gz

%{?el5:BuildRoot:   %(mktemp -ud %{_tmppath}/%{name}-%{version}-%{release}-XXXXXX)}
BuildArch:      noarch

%if 0%{?suse_version}
BuildRequires:      python-devel
%else
BuildRequires:      python2-devel
%endif


%description
A Python program that demonstrates usage of argparse.


%prep
%setup -qn %{name}-%{version}


%build
%{__python2} setup.py build


%install
%{?el5:rm -rf $RPM_BUILD_ROOT}
%{__python2} setup.py install --skip-build --prefix=%{_prefix} \
   --optimize=1 --root $RPM_BUILD_ROOT


%check
export PYTHONPATH=`pwd`/build/lib
export PATH=`pwd`/build/scripts-%{python2_version}:${PATH}
%if 0%{python2_minor_version} >= 7
%{__python2} -m unittest discover -s %{upstream_name}/tests -p '*.py'
%endif


%clean
%{?el5:rm -rf $RPM_BUILD_ROOT}


%files
%doc LICENSE README.md
%{_bindir}/*
%{python2_sitelib}/%{upstream_name}
%{?!el5:%{python2_sitelib}/*.egg-info}


%changelog
* Wed Jan 14 2015 Marcin Dulak <[email protected]> - 0.0.1-1
- initial version

Matplotlib legends in subplot

This should work:

ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")

How to install Flask on Windows?

heres a step by step procedure (assuming you've already installed python):

  1. first install chocolatey:

open terminal (Run as Administrator) and type in the command line:

C:/> @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin

it will take some time to get chocolatey installed on your machine. sit back n relax...

  1. now install pip. type in terminal cinst easy.install pip

  2. now type in terminal: pip install flask

YOU'RE DONE !!! Tested on Win 8.1 with Python 2.7

Why are only a few video games written in Java?

Game marketing is a commercial process; publishers want quantifiable low-risk returns on their investment. As a consequence, the focus is usually on technology gimmicks (with exceptions) that consumers will buy to produce reliable return - these tend to be superficial visual effects such as lens glare or higher resolution. These effects are reliable because they simply use increases in processing power - they exploit the hardware/Moore's law increases. this implies using C/C++ - java is usually too abstracted from the hardware to exploit these benefits.

How do I reference a cell within excel named range?

You can use Excel's Index function:

=INDEX(Age, 5)

Jupyter notebook not running code. Stuck on In [*]

The answers that state that your kernel is still executing the code in the cell are correct. You can see that by the small circle in the top right. If it is filled with a black/grey color, then it means it is still running.

I just want to add that I experienced a problem in JupyterHub where the code in the cell would just not execute. I stopped and restarted the kernel, shutdown and reloaded the notebook, but it still did not run.

What worked for me was literally copy pasting the same code to a new cell and deleting the old one. It then ran from the new cell.

De-obfuscate Javascript code to make it readable again

Here it is:

function call_func(input) {
    var evaled = eval('(' + input + ')');
    var newDiv = document.createElement('div');
    var id = evaled.id;
    var name = evaled.Student_name;
    var dob = evaled.student_dob;
    var html = '<b>ID:</b>';
    html += '<a href="/learningyii/index.php?r=student/view&amp; id=' + id + '">' + id + '</a>';
    html += '<br/>';
    html += '<b>Student Name:</b>';
    html += name;
    html += '<br/>';
    html += '<b>Student DOB:</b>';
    html += dob;
    html += '<br/>';
    newDiv.innerHTML = html;
    newDiv.setAttribute('class', 'view');
    $('#StudentGridViewId').find('.items').prepend(newDiv);
};

How to create a function in a cshtml template?

why not just declare that function inside the cshtml file?

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

<h2>index</h2>
@GetSomeString()

How to open a specific port such as 9090 in Google Compute Engine

Creating firewall rules

Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.

For Cloud Console:

  1. Go to the Firewall rules page in the Google Cloud Platform Console.
  2. Click Create firewall rule.
  3. Enter a Name for the firewall rule. This name must be unique for the project.
  4. Specify the Network where the firewall rule will be implemented.
  5. Specify the Priority of the rule. The lower the number, the higher the priority.
  6. For the Direction of traffic, choose ingress or egress.
  7. For the Action on match, choose allow or deny.
  8. Specify the Targets of the rule.

    • If you want the rule to apply to all instances in the network, choose All instances in the network.
    • If you want the rule to apply to select instances by network (target) tags, choose Specified target tags, then type the tags to which the rule should apply into the Target tags field.
    • If you want the rule to apply to select instances by associated service account, choose Specified service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Target service account field.
  9. For an ingress rule, specify the Source filter:

    • Choose IP ranges and type the CIDR blocks into the Source IP ranges field to define the source for incoming traffic by IP address ranges. Use 0.0.0.0/0 for a source from any network.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the source for incoming traffic by subnet name.
    • To limit source by network tag, choose Source tags, then type the network tags in to the Source tags field. For the limit on the number of source tags, see VPC Quotas and Limits. Filtering by source tag is only available if the target is not specified by service account. For more information, see filtering by service account vs.network tag.
    • To limit source by service account, choose Service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Source service account field. Filtering by source service account is only available if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
    • Specify a Second source filter if desired. Secondary source filters cannot use the same filter criteria as the primary one.
  10. For an egress rule, specify the Destination filter:

    • Choose IP ranges and type the CIDR blocks into the Destination IP ranges field to define the destination for outgoing traffic by IP address ranges. Use 0.0.0.0/0 to mean everywhere.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the destination for outgoing traffic by subnet name.
  11. Define the Protocols and ports to which the rule will apply:

    • Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.

    • Define specific protocols and ports:

      • Select tcp to include the TCP protocol and ports. Enter all or a comma delimited list of ports, such as 20-22, 80, 8080.
      • Select udp to include the UDP protocol and ports. Enter all or a comma delimited list of ports, such as 67-69, 123.
      • Select Other protocols to include protocols such as icmp or sctp.
  12. (Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.

  13. (Optional) You can enable firewall rules logging:

    • Click Logs > On.
    • Click Turn on.
  14. Click Create.

Link: [1] https://cloud.google.com/vpc/docs/firewalls#firewall_rule_components

Sublime Text 2: How to delete blank/empty lines

A Find/Replace solution:

Regex Find:\s+

Replace with: //single space

How to get the device's IMEI/ESN programmatically in android?

In addition to the answer of Trevor Johns, you can use this as follows:

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

And you should add the following permission into your Manifest.xml file:

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

In emulator, you'll probably get a like a "00000..." value. getDeviceId() returns NULL if device ID is not available.

Adding a slide effect to bootstrap dropdown

I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:

Here is the result: Bootply example

Javascript/Jquery:

$(function(){
    // ADD SLIDEDOWN ANIMATION TO DROPDOWN //
    $('.dropdown').on('show.bs.dropdown', function(e){
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
    });

    // ADD SLIDEUP ANIMATION TO DROPDOWN //
    $('.dropdown').on('hide.bs.dropdown', function(e){
        e.preventDefault();
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
            //On Complete, we reset all active dropdown classes and attributes
            //This fixes the visual bug associated with the open class being removed too fast
            $('.dropdown').removeClass('show');
            $('.dropdown-menu').removeClass('show');
            $('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
        });
    });
});

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

Change event on select with knockout binding, how can I know if it is a real change?

Actually you want to find whether the event is triggered by user or program , and its obvious that event will trigger while initialization.

The knockout approach of adding subscription won't help in all cases, why because in most of the model will be implemented like this

  1. init the model with undefined data , just structure (actual KO initilization)
  2. update the model with initial data (logical init like load JSON , get data etc)
  3. User interaction and updates

The actual step that we want to capture is changes in 3, but in second step subscription will get call , So a better way is to add to event change like

 <select data-bind="value: level, event:{ change: $parent.permissionChanged}">

and detected the event in permissionChanged function

this.permissionChanged = function (obj, event) {

  if (event.originalEvent) { //user changed

  } else { // program changed

  }

}

How to pass multiple values through command argument in Asp.net?

Use OnCommand event of imagebutton. Within it do

<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>

Code-behind:

void CommandBtn_Click(Object sender, CommandEventArgs e) 
{    
    switch(e.CommandName)
    {
        case "Something":
            // Do your code
            break;
        default:              
            break; 

    }
}

Computed / calculated / virtual / derived columns in PostgreSQL

A lightweight solution with Check constraint:

CREATE TABLE example (
    discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);

Reading/writing an INI file

Here is my class, works like a charm :

public static class IniFileManager
{


    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
        string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
             string key, string def, StringBuilder retVal,
        int size, string filePath);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSection(string lpAppName,
             byte[] lpszReturnBuffer, int nSize, string lpFileName);


    /// <summary>
    /// Write Data to the INI File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// Section name
    /// <PARAM name="Key"></PARAM>
    /// Key Name
    /// <PARAM name="Value"></PARAM>
    /// Value Name
    public static void IniWriteValue(string sPath,string Section, string Key, string Value)
    {
        WritePrivateProfileString(Section, Key, Value, sPath);
    }

    /// <summary>
    /// Read Data Value From the Ini File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// <PARAM name="Key"></PARAM>
    /// <PARAM name="Path"></PARAM>
    /// <returns></returns>
    public static string IniReadValue(string sPath,string Section, string Key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section, Key, "", temp,
                                        255, sPath);
        return temp.ToString();

    }

}

The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.

Nginx reverse proxy causing 504 Gateway Timeout

NGINX itself may not be the root cause.

IF "minimum ports per VM instance" set on the NAT Gateway -- which stand between your NGINX instance & the proxy_pass destination -- is too small for the number of concurrent requests, it has to be increased.

Solution: Increase the available number of ports per VM on NAT Gateway.

Context In my case, on Google Cloud, a reverse proxy NGINX was placed inside a subnet, with a NAT Gateway. The NGINX instance was redirecting requests to a domain associated with our backend API (upstream) through the NAT Gateway.

This documentation from GCP will help you understand how NAT is relevant to the NGINX 504 timeout.

Close Window from ViewModel

Staying MVVM, I think using either Behaviors from the Blend SDK (System.Windows.Interactivity) or a custom interaction request from Prism could work really well for this sort of situation.

If going the Behavior route, here's the general idea:

public class CloseWindowBehavior : Behavior<Window>
{
    public bool CloseTrigger
    {
        get { return (bool)GetValue(CloseTriggerProperty); }
        set { SetValue(CloseTriggerProperty, value); }
    }

    public static readonly DependencyProperty CloseTriggerProperty =
        DependencyProperty.Register("CloseTrigger", typeof(bool), typeof(CloseWindowBehavior), new PropertyMetadata(false, OnCloseTriggerChanged));

    private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = d as CloseWindowBehavior;

        if (behavior != null)
        {
            behavior.OnCloseTriggerChanged();
        }
    }

    private void OnCloseTriggerChanged()
    {
        // when closetrigger is true, close the window
        if (this.CloseTrigger)
        {
            this.AssociatedObject.Close();
        }
    }
}

Then in your window, you would just bind the CloseTrigger to a boolean value that would be set when you wanted the window to close.

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:local="clr-namespace:TestApp"
        Title="MainWindow" Height="350" Width="525">
    <i:Interaction.Behaviors>
        <local:CloseWindowBehavior CloseTrigger="{Binding CloseTrigger}" />
    </i:Interaction.Behaviors>

    <Grid>

    </Grid>
</Window>

Finally, your DataContext/ViewModel would have a property that you'd set when you wanted the window to close like this:

public class MainWindowViewModel : INotifyPropertyChanged
{
    private bool closeTrigger;

    /// <summary>
    /// Gets or Sets if the main window should be closed
    /// </summary>
    public bool CloseTrigger
    {
        get { return this.closeTrigger; }
        set
        {
            this.closeTrigger = value;
            RaisePropertyChanged(nameof(CloseTrigger));
        }
    }

    public MainWindowViewModel()
    {
        // just setting for example, close the window
        CloseTrigger = true;
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

(set your Window.DataContext = new MainWindowViewModel())

How to configure log4j with a properties file

import org.apache.log4j.PropertyConfigurator;

Import this, then:

Properties props = new Properties();
InputStream is = Main.class.getResourceAsStream("/log4j.properties");

try {
    props.load(is);
} catch (Exception e) {
    // ignore this exception
    log.error("Unable to load log4j properties file.",e);
}
PropertyConfigurator.configure(props);

My java files directory like this:

src/main/java/com/abc/xyz

And log4j directory like this:

src/main/resources

Linq select objects in list where exists IN (A,B,C)

Try with Contains function;

Determines whether a sequence contains a specified element.

var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));

Add two numbers and display result in textbox with Javascript

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
    $scope.minus = function() {     _x000D_
_x000D_
     var a = Number($scope.a || 0);_x000D_
            var b = Number($scope.b || 0);_x000D_
            $scope.sum1 = a-b;_x000D_
    // $scope.sum = $scope.sum1+1; _x000D_
    alert($scope.sum1);_x000D_
    }_x000D_
_x000D_
   $scope.add = function() {     _x000D_
_x000D_
     var c = Number($scope.c || 0);_x000D_
            var d = Number($scope.d || 0);_x000D_
            $scope.sum2 = c+d;_x000D_
    alert($scope.sum2);_x000D_
    }_x000D_
});
_x000D_
<head>_x000D_
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
   </head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
     <h3>Using Double Negation</h3>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="text" ng-model="a" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="text" ng-model="b" />_x000D_
    </p>_x000D_
    <button id="minus" ng-click="minus()">Minus</button>_x000D_
    <!-- <p>Sum: {{ a - b }}</p>  -->_x000D_
 <p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="number" ng-model="c" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="number" ng-model="d" />_x000D_
    </p>_x000D_
 <button id="minus" ng-click="add()">Add</button>_x000D_
    <p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why are there no ++ and --? operators in Python?

I believe it stems from the Python creed that "explicit is better than implicit".

How to convert WebResponse.GetResponseStream return into a string?

You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

How to connect to a secure website using SSL in Java with a pkcs12 file?

It appears that you are extracting you certificate from the PKCS #12 key store and creating a new Java key store (with type "JKS"). You don't strictly have to provide a trust store password (although using one allows you to test the integrity of your root certificates).

So, try your program with only the following SSL properties set. The list shown in your question is over-specified and may be causing problems.

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Also, using the PKCS #12 file directly as the trust store should work, as long as the CA certificate is detected as a "trusted" entry. But in that case, you'll have to specify the javax.net.ssl.trustStoreType property as "PKCS12" too.

Try with these properties only. If you get the same error, I suspect your problem is not the key store. If it still occurs, post more of the stack trace in your question to narrow the problem down.


The new error, "the trustAnchors parameter must be non-empty," could be due to setting the javax.net.ssl.trustStore property to a file that doesn't exist; if the file cannot be opened, an empty key store created, which would lead to this error.

Most popular screen sizes/resolutions on Android phones

Also, their "device dashboard" stats at:

http://developer.android.com/about/dashboards/index.html#Screens

can be pretty helpful. They are current and derived from Android Market visits.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Prevent saving changes that require table re-creation

Five swift clicks

Prevent saving changes that require table re-creation in five clicks

  1. Tools
  2. Options
  3. Designers
  4. Prevent saving changes that require table re-creation
  5. OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

  • By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

  • When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In my case, I reinstalled Python. It solved the problem.

brew reinstall python

How to order events bound with jQuery

Please note that in the jQuery universe this must be implemented differently as of version 1.8. The following release note is from the jQuery blog:

.data(“events”): jQuery stores its event-related data in a data object named (wait for it) events on each element. This is an internal data structure so in 1.8 this will be removed from the user data name space so it won’t conflict with items of the same name. jQuery’s event data can still be accessed via jQuery._data(element, "events")

We do have complete control of the order in which the handlers will execute in the jQuery universe. Ricoo points this out above. Doesn't look like his answer earned him a lot of love, but this technique is very handy. Consider, for example, any time you need to execute your own handler prior to some handler in a library widget, or you need to have the power to cancel the call to the widget's handler conditionally:

$("button").click(function(e){
    if(bSomeConditional)
       e.stopImmediatePropagation();//Don't execute the widget's handler
}).each(function () {
    var aClickListeners = $._data(this, "events").click;
    aClickListeners.reverse();
});

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Bootstrap close responsive menu "on click"

This works, but does not animate.

$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

Java Equivalent of C# async/await?

Java doesn't have direct equivalent of C# language feature called async/await, however there's a different approach to the problem that async/await tries to solve. It's called project Loom, which will provide virtual threads for high-throughput concurrency. It will be available in some future version of OpenJDK.

This approach also solves "colored function problem" that async/await has.

Similar feature can be also found in Golang (goroutines).

Sum the digits of a number

Try this

    print(sum(list(map(int,input("Enter your number ")))))

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

Java system properties and environment variables

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
try
{       
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
    {
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
            sw.Write(jsonData);
    }

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
    {
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
        {
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
        }
    }
}
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

How to do fade-in and fade-out with JavaScript and CSS

Here's my attempt with Javascript and CSS3 animation So the HTML:

 <div id="handle">Fade</div> 
 <div id="slideSource">Whatever you want images or  text here</div>

The CSS3 with transitions:

div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;     
transition: opacity 3s; 
}

div#slideSource.fade {
opacity:0;
}

The Javascript part. Check if the className exists, if it does then add the class and transitions.

document.getElementById('handle').onclick = function(){
    if(slideSource.className){
        document.getElementById('slideSource').className = '';
    } else {
        document.getElementById('slideSource').className = 'fade';
    }
}

Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.

jquery, selector for class within id

You can use find() :

$('#my_id').find('my_class');

Or maybe:

$('#my_id').find('span');

Both methods will word for what you want

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

function niceBytes(x){

  let l = 0, n = parseInt(x, 10) || 0;

  while(n >= 1024 && ++l){
      n = n/1024;
  }
  //include a decimal point and a tenths-place digit if presenting 
  //less than ten of KB or greater units
  return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}

Results:

niceBytes(435)                 // 435 bytes
niceBytes(3398)                // 3.3 KB
niceBytes(490398)              // 479 KB
niceBytes(6544528)             // 6.2 MB
niceBytes(23483023)            // 22 MB
niceBytes(3984578493)          // 3.7 GB
niceBytes(30498505889)         // 28 GB
niceBytes(9485039485039445)    // 8.4 PB

How to Get Element By Class in JavaScript?

This should work in pretty much any browser...

function getByClass (className, parent) {
  parent || (parent=document);
  var descendants=parent.getElementsByTagName('*'), i=-1, e, result=[];
  while (e=descendants[++i]) {
    ((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
  }
  return result;
}

You should be able to use it like this:

function replaceInClass (className, content) {
  var nodes = getByClass(className), i=-1, node;
  while (node=nodes[++i]) node.innerHTML = content;
}

Using colors with printf

You're mixing the parts together instead of separating them cleanly.

printf '\e[1;34m%-6s\e[m' "This is text"

Basically, put the fixed stuff in the format and the variable stuff in the parameters.

React.js create loop through Array

In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

Ansible - Save registered variable to file

I am using Ansible 1.9.4 and this is what worked for me -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For me it was missing MySQL PDO, I recompiled my PHP with the --with-pdo-mysql option, installed it and restarted apache and it was all working

Plotting categorical data with pandas and matplotlib

like this :

df.groupby('colour').size().plot(kind='bar')

Array vs. Object efficiency in JavaScript

In NodeJS if you know the ID, the looping through the array is very slow compared to object[ID].

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

And the results:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

Even if the seeking ID is the first one in the array/object:

Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms

Initializing default values in a struct

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

What's the difference between :: (double colon) and -> (arrow) in PHP?

Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'. My bad, I had a $instance::method() that should have been $instance->method(). Silly me.

The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.

So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.

If anybody can expand on why that is, please do.

Forward declaration of a typedef in C++

You can do forward typedef. But to do

typedef A B;

you must first forward declare A:

class A;

typedef A B;

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

Random number from a range in a Bash Script

shuf -i 2000-65000 -n 1

Enjoy!

Edit: The range is inclusive.

Export and import table dump (.sql) using pgAdmin

  1. In pgAdmin, select the required target schema in object tree (databases->your_db_name->schemas->your_target_schema)
  2. Click on Plugins/PSQL Console (in top-bar)
  3. Write \i /path/to/yourfile.sql
  4. Press enter

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

Numpy how to iterate over columns of array?

This should give you a start

>>> for col in range(arr.shape[1]):
    some_function(arr[:,col])


[1 2 3 4]
[99 14 12 43]
[2 5 7 1]

Eclipse error: indirectly referenced from required .class files?

In addition to the already suggested cause of missing a class file this error can also indicate a duplicate class file, eclipse reports this error when an class file on the build path uses another class that has multiple definitions in the build path.

Differences between key, superkey, minimal superkey, candidate key and primary key

Super Key : Super key is a set of one or more attributes whose values identify tuple in the relation uniquely.

Candidate Key : Candidate key can be defined as a minimal subset of super key. In some cases , candidate key can not alone since there is alone one attribute is the minimal subset. Example,

Employee(id, ssn, name, addrress)

Here Candidate key is (id, ssn) because we can easily identify the tuple using either id or ssn . Althrough, minimal subset of super key is either id or ssn. but both of them can be considered as candidate key.

Primary Key : Primary key is a one of the candidate key.

Example : Student(Id, Name, Dept, Result)

Here

Super Key : {Id, Id+Name, Id+Name+Dept} because super key is set of attributes .

Candidate Key : Id because Id alone is the minimal subset of super key.

Primary Key : Id because Id is one of the candidate key

Effectively use async/await with ASP.NET Web API

I am not very sure whether it will make any difference in performance of my API.

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

And under no circumstances should you use Task.Run in this scenario.

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

Here's some JavaScript for copy-paste ease (this is irritate's answer):

function scaleBetween(unscaledNum, minAllowed, maxAllowed, min, max) {
  return (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed;
}

Applied like so, scaling the range 10-50 to a range between 0-100.

var unscaledNums = [10, 13, 25, 28, 43, 50];

var maxRange = Math.max.apply(Math, unscaledNums);
var minRange = Math.min.apply(Math, unscaledNums);

for (var i = 0; i < unscaledNums.length; i++) {
  var unscaled = unscaledNums[i];
  var scaled = scaleBetween(unscaled, 0, 100, minRange, maxRange);
  console.log(scaled.toFixed(2));
}

0.00, 18.37, 48.98, 55.10, 85.71, 100.00

Edit:

I know I answered this a long time ago, but here's a cleaner function that I use now:

Array.prototype.scaleBetween = function(scaledMin, scaledMax) {
  var max = Math.max.apply(Math, this);
  var min = Math.min.apply(Math, this);
  return this.map(num => (scaledMax-scaledMin)*(num-min)/(max-min)+scaledMin);
}

Applied like so:

[-4, 0, 5, 6, 9].scaleBetween(0, 100);

[0, 30.76923076923077, 69.23076923076923, 76.92307692307692, 100]

If Python is interpreted, what are .pyc files?

To speed up loading modules, Python caches the compiled content of modules in .pyc.

CPython compiles its source code into "byte code", and for performance reasons, it caches this byte code on the file system whenever the source file has changes. This makes loading of Python modules much faster because the compilation phase can be bypassed. When your source file is foo.py , CPython caches the byte code in a foo.pyc file right next to the source.

In python3, Python's import machinery is extended to write and search for byte code cache files in a single directory inside every Python package directory. This directory will be called __pycache__ .

Here is a flow chart describing how modules are loaded:

enter image description here

For more information:

ref:PEP3147
ref:“Compiled” Python files

localhost refused to connect Error in visual studio

This solution worked for me:

  1. Go to your project folder and open .vs folder (keep your check hidden item-box checked as this folder may be hidden sometimes)

  2. in .vs folder - open config

  3. see that applicationhost config file there? Delete that thing.(Do not worry it will regenerate automatically once you recompile the project.)

How do I disable Git Credential Manager for Windows?

I struck the same issue on Ubuntu 18.10 (Cosmic Cuttlefish), unable to remove using any normal means. I used git config --global --unset credential.helper, and that seemed to do the trick.