Programs & Examples On #Derived class

In Object Oriented languages, derived class can inherit properties and/or member functions from a base class, also called super class. cf inheritance and polymorphism.

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

How about:

public static T As<T>(this object obj)
    {
        return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
    }

How can I run a directive after the dom has finished rendering?

Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load() inside the body of the returned function. (alternatively you can use document.ready. It really depends if you need all the images or not).

Using $timeout in my humble opinion is a very weak option and may fail in some cases.

Here is the complete code i'd use:

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function($scope, $elem, attrs){

           $(window).load(function() {
               //...JS here...
           });
       }
   }
});

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.

2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.

  @Configuration
    public class WebMvcCofig implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }

How to align absolutely positioned element to center?

Have you tried using?:

left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */

Not sure if it'll work, but it's worth a try...

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...

Log4j2 configuration - No log4j2 configuration file found

Additionally to what Tomasz W wrote, by starting your application you could use settings:

-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE 

to get most of configuration problems.

For details see Log4j2 FAQ: How do I debug my configuration?

In AngularJS, what's the difference between ng-pristine and ng-dirty?

ng-pristine ($pristine)

Boolean True if the form/input has not been used yet (not modified by the user)

ng-dirty ($dirty)

Boolean True if the form/input has been used (modified by the user)


$setDirty(); Sets the form to a dirty state. This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will propagate current state to parent forms.

$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.

Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

How to exit a 'git status' list in a terminal?

I have to guess here, but git is probably running its output into your $PAGER program, likely less or more. In either case, typing q should get you out.

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Use of Finalize/Dispose method in C#

  1. If you are using other managed objects that are using unmanaged resources, it is not your responsibility to ensure those are finalized. Your responsibility is to call Dispose on those objects when Dispose is called on your object, and it stops there.

  2. If your class doesn't use any scarce resources, I fail to see why you would make your class implement IDisposable. You should only do so if you're:

    • Know you will have scarce resources in your objects soon, just not now (and I mean that as in "we're still developing, it will be here before we're done", not as in "I think we'll need this")
    • Using scarce resources
  3. Yes, the code that uses your code must call the Dispose method of your object. And yes, the code that uses your object can use using as you've shown.

  4. (2 again?) It is likely that the WebClient uses either unmanaged resources, or other managed resources that implement IDisposable. The exact reason, however, is not important. What is important is that it implements IDisposable, and so it falls on you to act upon that knowledge by disposing of the object when you're done with it, even if it turns out WebClient uses no other resources at all.

Using moment.js to convert date to string "MM/dd/yyyy"

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

How would I run an async Task<T> method synchronously?

I have found that SpinWait works pretty well for this.

var task = Task.Run(()=>DoSomethingAsyncronous());

if(!SpinWait.SpinUntil(()=>task.IsComplete, TimeSpan.FromSeconds(30)))
{//Task didn't complete within 30 seconds, fail...
   return false;
}

return true;

The above approach doesn't need to use .Result or .Wait(). It also lets you specify a timeout so that you're not stuck forever in case the task never completes.

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

How can I see what I am about to push with git?

One way to compare your local version before pushing it on the remote repo (kind of push in dry-run):

Use TortoiseGit:
Right click on the root folder project > TortoiseGit > Diff with previous version >
for Version 2 choose refs/remotes/origin/master

Print text instead of value from C enum

I like this to have enum in the dayNames. To reduce typing, we can do the following:

#define EP(x) [x] = #x  /* ENUM PRINT */

const char* dayNames[] = { EP(Sunday), EP(Monday)};

TypeError: 'module' object is not callable

Assume that the content of YourClass.py is:

class YourClass:
    # ......

If you use:

from YourClassParentDir import YourClass  # means YourClass.py

In this way, I got TypeError: 'module' object is not callable if you then tried to use YourClass().

But, if you use:

from YourClassParentDir.YourClass import YourClass   # means Class YourClass

or use YourClass.YourClass(), it works for me.

How to get full file path from file name?

private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

SVG gradient using CSS

Thank you everyone, for all your precise replys.

Using the svg in a shadow dom, I add the 3 linear gradients I need within the svg, inside a . I place the css fill rule on the web component and the inheritance od fill does the job.

_x000D_
_x000D_
    <svg viewbox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
      <path
        d="m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z"></path>
    </svg>
    
    <svg height="0" width="0">
      <defs>
        <linearGradient id="lgrad-p" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#4169e1"></stop><stop offset="99%" stop-color="#c44764"></stop></linearGradient>
        <linearGradient id="lgrad-s" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#ef3c3a"></stop><stop offset="99%" stop-color="#6d5eb7"></stop></linearGradient>
        <linearGradient id="lgrad-g" gradientTransform="rotate(75)"><stop offset="45%" stop-color="#585f74"></stop><stop offset="99%" stop-color="#b6bbc8"></stop></linearGradient>
      </defs>
    </svg>
    
    <div></div>

    <style>
      :first-child {
        height:150px;
        width:150px;
        fill:url(#lgrad-p) blue;
      }
      div{
        position:relative;
        width:150px;
        height:150px;
        fill:url(#lgrad-s) red;
      }
    </style>
    <script>
      const shadow = document.querySelector('div').attachShadow({mode: 'open'});
      shadow.innerHTML="<svg viewbox=\"0 0 512 512\">\
        <path d=\"m258 0c-45 0-83 38-83 83 0 45 37 83 83 83 45 0 83-39 83-84 0-45-38-82-83-82zm-85 204c-13 0-24 10-24 23v48c0 13 11 23 24 23h23v119h-23c-13 0-24 11-24 24l-0 47c0 13 11 24 24 24h168c13 0 24-11 24-24l0-47c0-13-11-24-24-24h-21v-190c0-13-11-23-24-23h-123z\"></path>\
      </svg>\
      <svg height=\"0\">\
      <defs>\
        <linearGradient id=\"lgrad-s\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#ef3c3a\"></stop><stop offset=\"99%\" stop-color=\"#6d5eb7\"></stop></linearGradient>\
        <linearGradient id=\"lgrad-g\" gradientTransform=\"rotate(75)\"><stop offset=\"45%\" stop-color=\"#585f74\"></stop><stop offset=\"99%\" stop-color=\"#b6bbc8\"></stop></linearGradient>\
      </defs>\
    </svg>\
    ";
    </script>
_x000D_
_x000D_
_x000D_

The first one is normal SVG, the second one is inside a shadow dom.

Android EditText Max Length

I had the same problem.

Here is a workaround

android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"

Thx to How can I turnoff suggestions in EditText?

How to call another components function in angular2

Component 1(child):

@Component(
  selector:'com1'
)
export class Component1{
  function1(){...}
}

Component 2(parent):

@Component(
  selector:'com2',
  template: `<com1 #component1></com1>`
)
export class Component2{
  @ViewChild("component1") component1: Component1;

  function2(){
    this.component1.function1();
  }
}

How can moment.js be imported with typescript?

You need to import moment() the function and Moment the class separately in TS.

I found a note in the typescript docs here.

/*~ Note that ES6 modules cannot directly export callable functions
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');

So the code to import moment js into typescript actually looks like this:

import { Moment } from 'moment'
....
let moment = require('moment');
...
interface SomeTime {
  aMoment: Moment,
}
...
fn() {
  ...
  someTime.aMoment = moment(...);
  ...
}

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

jQuery get the image src

When dealing with the HTML DOM (ie. this), the array selector [0] must be used to retrieve the jQuery element from the Javascript array.

$(this)[0].getAttribute('src');

AngularJS open modal on button click

I am not sure,how you are opening popup or say model in your code. But you can try something like this..

<html ng-app="MyApp">
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />

<script type="text/javascript">
    var myApp = angular.module("MyApp", []);
    myApp.controller('MyController', function ($scope) {
      $scope.open = function(){
        var modalInstance = $modal.open({
                        templateUrl: '/assets/yourOpupTemplatename.html',
                        backdrop:'static',
                        keyboard:false,
                        controller: function($scope, $modalInstance) {
                            $scope.cancel = function() {
                                $modalInstance.dismiss('cancel');
                            };
                            $scope.ok = function () {
                              $modalInstance.close();
                            };
                        }
                    });
      }
    });
</script>
</head>
<body ng-controller="MyController">

    <button class="btn btn-primary" ng-click="open()">Test Modal</button>

    <!-- Confirmation Dialog -->
    <div class="modal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title">Delete confirmation</h4>
          </div>
          <div class="modal-body">
            <p>Are you sure?</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="cancel()">No</button>
            <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
          </div>
        </div>
      </div>
    </div>
    <!-- End of Confirmation Dialog -->

 </body>
 </html>

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32

How to make a countdown timer in Android?

Here's the solution I used in Kotlin

private fun startTimer()
{
    Log.d(TAG, ":startTimer: timeString = '$timeString'")

    object : CountDownTimer(TASK_SWITCH_TIMER, 250)
    {
        override fun onTick(millisUntilFinished: Long)
        {
            val secondsUntilFinished : Long = 
            Math.ceil(millisUntilFinished.toDouble()/1000).toLong()
            val timeString = "${TimeUnit.SECONDS.toMinutes(secondsUntilFinished)}:" +
                    "%02d".format(TimeUnit.SECONDS.toSeconds(secondsUntilFinished))
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $ttlseconds")
            Log.d(TAG, ":startTimer::CountDownTimer:millisUntilFinished = $millisUntilFinished")
        }

        @SuppressLint("SetTextI18n")
        override fun onFinish()
        {
            timerTxtVw.text = "0:00"
            gameStartEndVisibility(true)
        }
    }.start()
}

How exactly does the python any() function work?

>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

It just reduce several line of code into one. You don't have to write lengthy code like:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False

DLL References in Visual C++

You need to do a couple of things to use the library:

  1. Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2

  2. Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.

  3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.

After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)

Cheers!

EDIT

Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.

Selenium Webdriver move mouse to Point

I am using JavaScript but some of the principles are common I am sure.

The code I am using is as follows:

    var s = new webdriver.ActionSequence(d);
    d.findElement(By.className('fc-time')).then(function(result){
        s.mouseMove(result,l).click().perform();
    });

the driver = d. The location = l is simply {x:300,y:500) - it is just an offset.

What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.

I suspect the figures in the locate are a bit more difficult to predict than I thought.

It is an old post but this response may help other newcomers like me.

Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:

verify(bar).doStuff(any());

Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.


Primitive types

This doesn't work with primitive types, unfortunately:

public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

Python, compute list difference

One liner:

diff = lambda l1,l2: [x for x in l1 if x not in l2]
diff(A,B)
diff(B,A)

Or:

diff = lambda l1,l2: filter(lambda x: x not in l2, l1)
diff(A,B)
diff(B,A)

Change table header color using bootstrap

there's a bootstrap function to change the color of table header called thead-dark for dark background of table header and thead-light for light background of table header. Your code will look like this after using this function.

<table class="table">
    <tr class="thead-danger">
        <!-- here I used dark table headre -->
        <th>
            @Html.DisplayNameFor(model => model.name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.checkBox1)
        </th>
        <th></th>
    </tr>

How to check if file already exists in the folder

'In Visual Basic

Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml

Dim FilePath ="C:\MyFolderName" & "\" & FileName  'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.

If System.IO.File.Exists(FilePath) Then
    MsgBox("The file exists")
Else
    MsgBox("the file doesn't exist")
End If

Multiple try codes in one block

If you don't want to chain (a huge number of) try-except clauses, you may try your codes in a loop and break upon 1st success.

Example with codes which can be put into functions:

for code in (
    lambda: a / b,
    lambda: a / (b + 1),
    lambda: a / (b + 2),
    ):
    try: print(code())
    except Exception as ev: continue
    break
else:
    print("it failed: %s" % ev)

Example with arbitrary codes (statements) directly in the current scope:

for i in 2, 1, 0:
    try:
        if   i == 2: print(a / b)
        elif i == 1: print(a / (b + 1))
        elif i == 0: print(a / (b + 2))
        break        
    except Exception as ev:
        if i:
            continue
        print("it failed: %s" % ev)

Why can't non-default arguments follow default arguments?

Let me clear two points here :

  • firstly non-default argument should not follow default argument , it means you can't define (a=b,c) in function the order of defining parameter in function are :
    • positional parameter or non-default parameter i.e (a,b,c)
    • keyword parameter or default parameter i.e (a="b",r="j")
    • keyword-only parameter i.e (*args)
    • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(**ab) is var-keyword parameter

  • now secondary thing is if i try something like this : def example(a, b, c=a,d=b):

argument is not defined when default values are saved,Python computes and saves default values when you define the function

c and d are not defined, does not exist, when this happens (it exists only when the function is executed)

"a,a=b" its not allowed in parameter.

How to append text to an existing file in Java?

Try with bufferFileWriter.append, it works with me.

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}

How do I output lists as a table in Jupyter notebook?

You could try to use the following function

def tableIt(data):
    for lin in data:
        print("+---"*len(lin)+"+")
        for inlin in lin:
            print("|",str(inlin),"", end="")
        print("|")
    print("+---"*len(lin)+"+")

data = [[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3]]

tableIt(data)

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

what is the difference between json and xml

XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

{
 'attrib' : 'value',
 'array' : [1, 2, 3]
}

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply!

PHP Constants Containing Arrays?

You can define like this

define('GENERIC_DOMAIN',json_encode(array(
    'gmail.com','gmail.co.in','yahoo.com'
)));

$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);

How can I make git show a list of the files that are being tracked?

If you want to list all the files currently being tracked under the branch master, you could use this command:

git ls-tree -r master --name-only

If you want a list of files that ever existed (i.e. including deleted files):

git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

Color theme for VS Code integrated terminal

VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.

  • For changing the color theme press ctrl+k+t in windows/ubuntu or cmd+k+t on mac.
  • Alternatively you can open command palette by pressing ctrl+shift+p in windows/ubuntu or cmd+shift+p on mac and type color. Select preferences: color theme from the options, to select your favourite color.
  • You can also install more themes from the extensions menu on the left bar. just search category:themes to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs)

Edit - for manually editing colors in terminal

VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766

nodejs module.js:340 error: cannot find module

I had a nearly identical issue, turned out my JS file wasn't actually in the folder I was calling it from, and I had gone one folder too deep. I went up one directory, ran the file, it recognized it, happily ever after.

Alternatively, if you go one folder up, and it gives you the same error, but about a different module, take that same file in your parent folder and move it into the subfolder you were previously trying to run things from.

TL;DR- your file or its module(s) is not in the folder you think it is. Go up one level

Centering FontAwesome icons vertically and horizontally

I have used transform to correct the offset. It works great with round icons like the life ring.

<span class="fa fa-life-ring"></span>

.fa {
    transform: translateY(-4%);
}

What is C# analog of C++ std::pair?

Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

and access values through t.Item1 and t.Item2, you can simply do it like that:

(string message, int count) = ("Hello", 4);

or even:

(var message, var count) = ("Hello", 4);

What is the difference between a candidate key and a primary key?

Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table)

Candidate key -> Any column or set of columns that are candidate to become primary key are Candidate key. (There can be one or more candidate key(s) in the table, if there is only one candidate key, it can be chosen as Primary key)

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

System.Net.Http: missing from namespace? (using .net 4.5)

To solve the problem :

  1. Go to your solution explorer.
  2. Right click on the project name and choose add
  3. Select references and allow the .Net framework 4.5 to finish loading
  4. Scroll down and select System.Net.Http and click ok.

Problem solved.

Color Tint UIButton Image

For Xamarin.iOS (C#):

UIButton messagesButton = new UIButton(UIButtonType.Custom);
UIImage icon = UIImage.FromBundle("Images/icon.png");
messagesButton.SetImage(icon.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal);
messagesButton.TintColor = UIColor.White;
messagesButton.Frame = new RectangleF(0, 0, 25, 25);

Get Substring - everything before certain char

Building on BrainCore's answer:

    int index = 0;   
    str = "223232-1.jpg";

    //Assuming we trust str isn't null 
    if (str.Contains('-') == "true")
    {
      int index = str.IndexOf('-');
    }

    if(index > 0) {
        return str.Substring(0, index);
    }
    else {
       return str;
    }

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

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

When do I need to do "git pull", before or after "git add, git commit"?

You want your change to sit on top of the current state of the remote branch. So probably you want to pull right before you commit yourself. After that, push your changes again.

"Dirty" local files are not an issue as long as there aren't any conflicts with the remote branch. If there are conflicts though, the merge will fail, so there is no risk or danger in pulling before committing local changes.

How to play an android notification sound

I think the concept of "notification sound" is someway wrong for Android UI.

The Android expected behaviour is to use the standard Notification to alert the user. If you play a notification sound without the status bar icon, you get the user confused ("what was that sound? there is no icon here, maybe I have hearing problems?").

How to set sound on a notification is, for example, here: Setting sound for notification

How to empty a redis database?

Be careful here.

FlushDB deletes all keys in the current database while FlushALL deletes all keys in all databases on the current host.

White spaces are required between publicId and systemId

If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.

  • Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)
  • Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)
  • At the top of the page that appears there is a drop down, select "Manual."
  • Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.
  • Enter in the proxy url and port you need to connect to the internet in your web browser normally.
  • Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

I'm getting favicon.ico error

For me the answer didn't work too, but this work fine:

<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">

How to set UTF-8 encoding for a PHP file

You have to specify what encoding the data is. Either in meta or in headers

header('Content-Type: text/plain; charset=utf-8');

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

in angularjs how to access the element that triggered the event?

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText

Android Recyclerview vs ListView with Viewholder

If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.

So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You can also use Url.Action for the path instead like so:

$.ajax({
        url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",                
        type: "GET",           
        success: function (partialViewResult) {            
            $("#refTable").html(partialViewResult);
        }
    });

PHP: Show yes/no confirmation dialog

<a href="http://stackoverflow.com" 
    onclick="return confirm('Are you sure?');">My Link</a>

Unable to create Genymotion Virtual Device

Disadvantage of deleting the deployed and .ova files is obvious i.e. you have to download the massive 200mb image again. A better choice is to :

  • Open genymotion and open settings --> virtualBox --> virtual devices browse and set the path to a folder which can be completely accessed without administrative pivileges e.g. for ubuntu set virtual devices path to any folder in your home directory for example /home/user/deployed and for windows you can use a folder like C://deployed.

That's it . Now you can use your already existing .ova file again to deploy image to new locatioin without any problem.

adding css class to multiple elements

.button input,
.button a {
    ...
}

How to check if a string contains a specific text

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

HTTP Request in Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

Or simpler:

URL("https://google.com").readText()

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

in project's build.gradle file comment classpath com.android.tools.build:gradle:. File ? Project Structure select Android Gradle Plugin Version to match Android Studio version

Project Structure

String Pattern Matching In Java

If you want to check if some string is present in another string, use something like String.contains

If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.

Example: Suppose you have some regex a(b|c) that checks if a string matches ab or ac
.*(a(b|c)).* will check if a string contains a ab or ac.

A disadvantage of this method is that it will not give you the location of the match.

A generic error occurred in GDI+, JPEG Image to MemoryStream

if your code is as follows then also this error occurs

private Image GetImage(byte[] byteArray)
{
   using (var stream = new MemoryStream(byteArray))
   {
       return Image.FromStream(stream);
    }
}

The correct one is

private Image GetImage(byte[] byteArray)
{
   var stream = new MemoryStream(byteArray))
   return Image.FromStream(stream);        
}

This may be because we are returning from the using block

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

How to use boolean 'and' in Python

In python, use and instead of && like this:

#!/usr/bin/python
foo = True;
bar = True;
if foo and bar:
    print "both are true";

This prints:

both are true

how to open a jar file in Eclipse

Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.

In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.

Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip

Then import it into Eclipse.

If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

How to refresh datagrid in WPF

From MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

Using two values for one switch case statement

you can do like:

case text1:
case text4: {
            //blah
            break;
}

Populate a Drop down box from a mySQL table in PHP

Since mysql_connect has been deprecated, connect and query instead with mysqli:

$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);

And then, if you have more than one option list with the same values on the same page, put the values in an array:

while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

And then you can loop the array multiple times on the same page:

foreach ($rows as $row) {
    print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}

How to allow users to check for the latest app version from inside the app?

Google updated play store two months before. This is the solution working right now for me..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

and don't forget to add JSoup library

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

and on Oncreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

that's it.. Thanks to this link

Getting vertical gridlines to appear in line plot in matplotlib

According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

How to use an array list in Java?

You could either get your strings by index (System.out.println(S.get(0));) or iterate through it:

for (String s : S) {
  System.out.println(s);
}

For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.

Additionally:

  • you shouldn't use variable names starting with upper-case letters
  • you should parametrize your array list: ArrayList<String> list = new ArrayList<String>();
  • you should get familiar with Java's extensive API documentation (aka Javadoc), e.g. Java 5, Java 6

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

Display images in asp.net mvc

Make sure you image is a relative path such as:

@Url.Content("~/Content/images/myimage.png")

MVC4

<img src="~/Content/images/myimage.png" />

You could convert the byte[] into a Base64 string on the fly.

string base64String = Convert.ToBase64String(imageBytes);

<img src="@String.Format("data:image/png;base64,{0}", base64string)" />

Curl Command to Repeat URL Request

for i in `seq 1 20`; do curl http://url; done

Or if you want to get timing information back, use ab:

ab -n 20 http://url/

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

Based on all the answers on this thread, I wrote the following code and it worked for me.

If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"

for eg.

<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>

and the Javascript (jQuery) can look like this :

$(document).ready(function(){
    window.onbeforeunload = function(e) {
        var returnFlag = false;
        $('textarea, input').each(function(){
            if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                returnFlag = true;
        });

        if(returnFlag)
            return "Sure you want to leave?";   
    };
});

How to set the LDFLAGS in CMakeLists.txt?

For linking against libraries see Andre's answer.

For linker flags - the following 4 CMake variables:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm

Removing all line breaks and adding them after certain text

I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL

Left padding a String with Zeros

I have used this:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

Result: 00123

I hope you find it useful!

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

UIDevice uniqueIdentifier deprecated - What to do now?

Little hack for you:

/**
 @method uniqueDeviceIdentifier
 @abstract A unique device identifier is a hash value composed from various hardware identifiers such
 as the device’s serial number. It is guaranteed to be unique for every device but cannot 
 be tied to a user account. [UIDevice Class Reference]
 @return An 1-way hashed identifier unique to this device.
 */
+ (NSString *)uniqueDeviceIdentifier {      
    NSString *systemId = nil;
    // We collect it as long as it is available along with a randomly generated ID.
    // This way, when this becomes unavailable we can map existing users so the
    // new vs returning counts do not break.
    if (([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0f)) {
        SEL udidSelector = NSSelectorFromString(@"uniqueIdentifier");
        if ([[UIDevice currentDevice] respondsToSelector:udidSelector]) {
            systemId = [[UIDevice currentDevice] performSelector:udidSelector];
        }
    }
    else {
        systemId = [NSUUID UUID];
    }
    return systemId;
}

Simulate a click on 'a' element using javascript/jquery

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

Concatenate a vector of strings/character

For sdata:

gsub(", ","",toString(sdata))

For a vector of integers:

gsub(", ","",toString(c(1:10)))

Asynchronously wait for Task<T> to complete with timeout

A generic version of @Kevan's answer above, using Reactive Extensions.

public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, IScheduler scheduler)
{
    return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

With optional Scheduler:

public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, Scheduler scheduler = null)
{
    return scheduler is null 
       ? task.ToObservable().Timeout(timeout).ToTask() 
       : task.ToObservable().Timeout(timeout, scheduler).ToTask();
}

BTW: When a Timeout happens, a timeout exception will be thrown

How can I find the number of years between two dates?

Thanks @Ole V.v for reviewing it: i have found some inbuilt library classes which does the same

    int noOfMonths = 0;
    org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat
            .forPattern("yyyy-MM-dd");
    DateTime dt = formatter.parseDateTime(startDate);

    DateTime endDate11 = new DateTime();
    Months m = Months.monthsBetween(dt, endDate11);
    noOfMonths = m.getMonths();
    System.out.println(noOfMonths);

How can I iterate through a string and also know the index (current position)?

I would use it-str.begin() In this particular case std::distance and operator- are the same. But if container will change to something without random access, std::distance will increment first argument until it reach second, giving thus linear time and operator- will not compile. Personally I prefer the second behaviour - it's better to be notified when you algorithm from O(n) became O(n^2)...

when exactly are we supposed to use "public static final String"?

final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.

Iterate over values of object

In the sense I think you intended, in ES5 or ES2015, no, not without some work on your part.

In ES2016, probably with object.values.

Mind you Arrays in JavaScript are effectively a map from an integer to a value, and the values in JavaScript arrays can be enumerated directly.

['foo', 'bar'].forEach(v => console.log(v)); // foo bar

Also, in ES2015, you can make an object iterable by placing a function on a property with the name of Symbol.iterator:

var obj = { 
    foo: '1', 
    bar: '2',
    bam: '3',
    bat: '4',
};

obj[Symbol.iterator] = iter.bind(null, obj);

function* iter(o) {
    var keys = Object.keys(o);
    for (var i=0; i<keys.length; i++) {
        yield o[keys[i]];
    }
}

for(var v of obj) { console.log(v); } // '1', '2', '3', '4'

Also, per other answers, there are other built-ins that provide the functionality you want, like Map (but not WeakMap because it is not iterable) and Set for example (but these are not present in all browsers yet).

How to initialize a two-dimensional array in Python?

The important thing I understood is: While initializing an array(in any dimension) We should give a default value to all the positions of array. Then only initialization completes. After that, we can change or receive new values to any position of the array. The below code worked for me perfectly

N=7
F=2

#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]

#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
    for j in range(F):
        ar[i][j]=int(input())
print(ar)

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

How do I make a Docker container start automatically on system boot?

More "gentle" mode from the documentation:

docker run -dit --restart unless-stopped <image_name>

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

JavaScript code to stop form submission

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Delete all app files from Phone

To automate the deletion of an app on your phone you can use the steps below. It can be very useful to delete your app and app data on a quick and clean way.

Make a textfile with this code and save it as Uninstall.sh. Go to the folder (where you've put it) of this script in the terminal and do: sh Uninstall.sh YOURNAMESPACE

Now your namespacefolder (including saved appfiles and database) will be deleted.

  echo "Going to platform tools $HOME/Library/Android/sdk/platform-tools"
  cd $HOME/Library/Android/sdk/platform-tools
  echo "uninstalling app with packagae name $1"
  ./adb uninstall $1

Delete all app files from pc

Make a textfile with this code and save it as DeleteBinObj.sh.

find . -iname "bin" -o -iname "obj" | xargs rm -rf

Go to the folder of your project where you place this script and do in the terminal: sh DeleteBinObj.sh

Move top 1000 lines from text file to a new file using Unix shell commands

Out of curiosity, I found a box with a GNU version of sed (v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s

This is the Linux I was working with:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux

For this test, at least, it looks like sed is slower than the tail approach (27 sec vs ~14 sec).

How to change root logging level programmatically for logback

I assume you are using logback (from the configuration file).

From logback manual, I see

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Perhaps this can help you change the value?

Validating with an XML schema in Python

There are two ways(actually there are more) that you could do this.
1. using lxml
pip install lxml

from lxml import etree, objectify
from lxml.etree import XMLSyntaxError

def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):
    try:
        schema = etree.XMLSchema(file=xsd_file)
        parser = objectify.makeparser(schema=schema)
        objectify.fromstring(some_xml_string, parser)
        print "YEAH!, my xml file has validated"
    except XMLSyntaxError:
        #handle exception here
        print "Oh NO!, my xml file does not validate"
        pass

xml_file = open('my_xml_file.xml', 'r')
xml_string = xml_file.read()
xml_file.close()

xml_validator(xml_string, '/path/to/my_schema_file.xsd')
  1. Use xmllint from the commandline. xmllint comes installed in many linux distributions.

>> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I was also getting this error, I deleted dlls from my debug folder and when I started a new instance for debug I got this error. For me the issue was due to the the build setting, Release was selected in the build type, I just changed it to debug and then application was working fine

android pick images from gallery

Just to offer an update to the answer for people with API min 19, per the docs:

On Android 4.4 (API level 19) and higher, you have the additional option of using the ACTION_OPEN_DOCUMENT intent, which displays a system-controlled picker UI controlled that allows the user to browse all files that other apps have made available. From this single UI, the user can pick a file from any of the supported apps.

On Android 5.0 (API level 21) and higher, you can also use the ACTION_OPEN_DOCUMENT_TREE intent, which allows the user to choose a directory for a client app to access.

Open files using storage access framework - Android Docs

     val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
     intent.type = "image/*"
     startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)

How to resize a custom view programmatically?

Android throws an exception if you fail to pass the height or width of a view. Instead of creating a new LayoutParams object, use the original one, so that all other set parameters are kept. Note that the type of LayoutParams returned by getLayoutParams is that of the parent layout, not the view you are resizing.

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

Can I automatically increment the file build version when using Visual Studio?

Go to Project | Properties and then Assembly Information and then Assembly Version and put an * in the last or the second-to-last box (you can't auto-increment the Major or Minor components).

What is JNDI? What is its basic use? When is it used?

JNDI in layman's terms is basically an Interface for being able to get instances of internal/External resources such as

  javax.sql.DataSource, 
  javax.jms.Connection-Factory,
  javax.jms.QueueConnectionFactory,
  javax.jms.TopicConnectionFactory,
  javax.mail.Session, java.net.URL,
  javax.resource.cci.ConnectionFactory,

or any other type defined by a JCA resource adapter. It provides a syntax in being able to create access whether they are internal or external. i.e (comp/env in this instance means where component/environment, there are lots of other syntax):

jndiContext.lookup("java:comp/env/persistence/customerDB");

How to unset (remove) a collection element after fetching it?

I'm not fine with solutions that iterates over a collection and inside the loop manipulating the content of even that collection. This can result in unexpected behaviour.

See also here: https://stackoverflow.com/a/2304578/655224 and in a comment the given link http://php.net/manual/en/control-structures.foreach.php#88578

So, when using foreach if seems to be OK but IMHO the much more readable and simple solution is to filter your collection to a new one.

/**
 * Filter all `selected` items
 *
 * @link https://laravel.com/docs/7.x/collections#method-filter
 */
$selected = $collection->filter(function($value, $key) {
    return $value->selected;
})->toArray();

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()
legend.get_frame().set_facecolor('none')

Warning, you want 'none' (the string). None means the default color instead.

LINQ: Select an object and change some properties without creating a new object

User u = UserCollection.Single(u => u.Id == 1);
u.FirstName = "Bob"

Extract parameter value from url using regular expressions

I know the question is Old and already answered but this can also be a solution

\b[\w-]+$

and I checked these two URLs

http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos

DEMO

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

python setup.py uninstall

Extending on what Martin said, recording the install output and a little bash scripting does the trick quite nicely. Here's what I do...

for i in $(less install.record);
sudo rm $i;
done;

And presto. Uninstalled.

How do I add options to a DropDownList using jQuery?

U can use direct

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

-> Here u can use direct string

%matplotlib line magic causes SyntaxError in Python script

Instead of %matplotlib inline,it is not a python script so we can write like this it will work from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline')

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

You can use the simple program StarUML. The trial version is unlimited and can do almost anything.

Onced installed you can use it to generate great number of uml digrams just by pasting the source code. Class diagram is just one type of it. (It understands not only Java language but C#, C++ and other)

P.S. The program is great for drawing architectural diagrams before you start to code the program.

[] and {} vs list() and dict(), which is better?

IMHO, using list() and dict() makes your Python look like C. Ugh.

How to import a class from default package

  1. Create a new package.
  2. Move your files from the default package to the new one.

How do you remove Subversion control for a folder?

Another (simpler) Linux solution:

rm -r `find /path/to/foo -name .svn`

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

How to get Activity's content view?

There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

If content view was already set, requestWindowFeature will throw an exception.

What is the Simplest Way to Reverse an ArrayList?

A little more readable :)

public static <T> ArrayList<T> reverse(ArrayList<T> list) {
    int length = list.size();
    ArrayList<T> result = new ArrayList<T>(length);

    for (int i = length - 1; i >= 0; i--) {
        result.add(list.get(i));
    }

    return result;
}

How to merge two sorted arrays into a sorted array?

GallopSearch Merge: O(log(n)*log(i)) rather than O(n)

I went ahead and implemented greybeard suggestion in the comments. Mostly because I needed a highly efficient mission critical version of this code.

  • The code uses a gallopSearch which is O(log(i)) where i is the distance from the current index the relevant index exists.
  • The code uses a binarySearch for after the gallop search has identified the proper,range. Since gallop limited this to a smaller range the resulting binarySearch is also O(log(i))
  • The gallop and merge are performed backwards. This doesn't seem mission critical but it allows in place merging of arrays. If one of your arrays has enough room to store the results values, you can simply use it as the merging array and the results array. You must specify the valid range within the array in such a case.
  • It does not require memory allocation in that case (big savings in critical operations). It simply makes sure it doesn't and cannot overwrite any unprocessed values (which can only be done backwards). In fact, you use the same array for both of the inputs and the results. It will suffer no ill effects.
  • I consistently used Integer.compare() so this could be switched out for other purposes.
  • There's some chance I might have goofed a little and not utilized information I have previously proven. Such as binary searching into a range of two values, for which one value was already checked. There might also be a better way to state the main loop, the flipping c value wouldn't be needed if they were combined into two operations in sequence. Since you know you will do one then the other everytime. There's room for for some polish.

This should be the most efficient way to do this, with time complexity of O(log(n)*log(i)) rather than O(n). And worst case time complexity of O(n). If your arrays are clumpy and have long strings of values together, this will dwarf any other way to do it, otherwise it'll just be better than them.

It has two read values at the ends of the merging array and the write value within the results array. After finding out which is end value is less, it does a gallop search into that array. 1, 2, 4, 8, 16, 32, etc. When it finds the range where the the other array's read value is bigger. It binary searches into that range (cuts the range in half, search the correct half, repeat until single value). Then it array copies those values into the write position. Keeping in mind that the copy is, by necessity, moved such that it cannot overwrite the same values from the either reading array (which means the write array and read array can be the same). It then performs the same operation for the other array which is now known to be less than the new read value of the other array.

static public int gallopSearch(int current, int[] array, int v) {
    int d = 1;
    int seek = current - d;
    int prevIteration = seek;
    while (seek > 0) {
        if (Integer.compare(array[seek], v) <= 0) {
            break;
        }
        prevIteration = seek;
        d <<= 1;
        seek = current - d;
        if (seek < 0) {
            seek = 0;
        }
    }
    if (prevIteration != seek) {
        seek = binarySearch(array, seek, prevIteration, v);
        seek = seek >= 0 ? seek : ~seek;
    }
    return seek;
}

static public int binarySearch(int[] list, int fromIndex, int toIndex, int v) {
    int low = fromIndex;
    int high = toIndex - 1;
    while (low <= high) {
        int mid = (low + high) >>> 1;
        int midVal = list[mid];
        int cmp = Integer.compare(midVal, v);
        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            return mid;// key found
        }
    }
    return -(low + 1);// key not found.
}

static public int[] sortedArrayMerge(int[] a, int[] b) {
    return sortedArrayMerge(null, a, a.length, b, b.length);
}

static public int[] sortedArrayMerge(int[] results, int[] a, int aRead, int b[], int bRead) {
    int write = aRead + bRead, length, gallopPos;
    if ((results == null) || (results.length < write)) {
        results = new int[write];
    }
    if (aRead > 0 && bRead > 0) {
        int c = Integer.compare(a[aRead - 1], b[bRead - 1]);
        while (aRead > 0 && bRead > 0) {
            switch (c) {
                default:
                    gallopPos = gallopSearch(aRead, a, b[bRead-1]);
                    length = (aRead - gallopPos);
                    write -= length;
                    aRead = gallopPos;
                    System.arraycopy(a, gallopPos--, results, write, length);
                    c = -1;
                    break;
                case -1:
                    gallopPos = gallopSearch(bRead, b, a[aRead-1]);
                    length = (bRead - gallopPos);
                    write -= length;
                    bRead = gallopPos;
                    System.arraycopy(b, gallopPos--, results, write, length);
                    c = 1;
                    break;
            }
        }
    }
    if (bRead > 0) {
        if (b != results) {
            System.arraycopy(b, 0, results, 0, bRead);
        }
    } else if (aRead > 0) {
        if (a != results) {
            System.arraycopy(a, 0, results, 0, aRead);
        }
    }
    return results;
}

This should be the most efficient way to do it.


Some answers had a duplicate remove ability. That'll require an O(n) algorithm because you must actually compare each item. So here's a stand-alone for that, to be applied after the fact. You can't gallop through multiple entries all the way through if you need to look at all of them, though you could gallop through the duplicates, if you had a lot of them.

static public int removeDuplicates(int[] list, int size) {
    int write = 1;
    for (int read = 1; read < size; read++) {
        if (list[read] == list[read - 1]) {
            continue;
        }
        list[write++] = list[read];
    }
    return write;
}

Update: Previous answer, not horrible code but clearly inferior to the above.

Another needless hyper-optimization. It not only invokes arraycopy for the end bits, but also for the beginning. Processing any introductory non-overlap in O(log(n)) by a binarySearch into the data. O(log(n) + n) is O(n) and in some cases the effect will be pretty pronounced especially things like where there is no overlap between the merging arrays at all.

private static int binarySearch(int[] array, int low, int high, int v) {
    high = high - 1;
    while (low <= high) {
        int mid = (low + high) >>> 1;
        int midVal = array[mid];
        if (midVal > v)
            low = mid + 1;
        else if (midVal < v)
            high = mid - 1;
        else
            return mid; // key found
    }
    return low;//traditionally, -(low + 1);  // key not found.
}

private static int[] sortedArrayMerge(int a[], int b[]) {
    int result[] = new int[a.length + b.length];
    int k, i = 0, j = 0;
    if (a[0] > b[0]) {
        k = i = binarySearch(b, 0, b.length, a[0]);
        System.arraycopy(b, 0, result, 0, i);
    } else {
        k = j = binarySearch(a, 0, a.length, b[0]);
        System.arraycopy(a, 0, result, 0, j);
    }
    while (i < a.length && j < b.length) {
        result[k++] = (a[i] < b[j]) ? a[i++] : b[j++];
    }
    if (j < b.length) {
        System.arraycopy(b, j, result, k, (b.length - j));
    } else {
        System.arraycopy(a, i, result, k, (a.length - i));
    }
    return result;
}

Populating VBA dynamic arrays

Yes, you're looking for the ReDim statement, which dynamically allocates the required amount of space in the array.

The following statement

Dim MyArray()

declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.

But you can use the ReDim statement to resize the array:

ReDim MyArray(0 To 3)

And if you need to resize the array while preserving its contents, you can use the Preserve keyword along with the ReDim statement:

ReDim Preserve MyArray(0 To 3)

But do note that both ReDim and particularly ReDim Preserve have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.


However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim at all. Just declare the array with explicit dimensions:

Dim MyArray(0 To 3)

Anaconda Installed but Cannot Launch Navigator

I had a similar issue today where only the prompt was available after installation. Finally solved this by un-installing my regular python installation and then install anaconda(anaconda 3 v5.2.0, with python 3.6).

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.

PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:

  1. PHP started as a very basic CGI. PHP has progressed very far since its early stage, but it happened in small steps. PHP already had many millions of users by the time it became the embed-able and flexible C library that it is today, most of whom were dependent on its earlier model of execution, so it hasn't yet made a solid attempt to escape the CGI model internally. Even the command line interface invokes the PHP library (libphp5.so on Linux, php5ts.dll on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.

Note that PHP does have extensions to provide event loops (such as libevent) and threads (such as pthreads) in PHP userspace, but very, very, few of the applications use these.

  1. PHP still has significant issues with garbage collection. Although these issues have been consistently improving (likely its greatest step to end the life cycle as described above), even the best attempts at creating long-running PHP applications require being restarted on a regular basis. This also makes it unpractical for real-time applications.

PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.

How to resolve this System.IO.FileNotFoundException

Check all the references carefully

  • Version remains same on target machine and local machine
  • If assembly is referenced from GAC, ensure that proper version is loaded

For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

Simple way to calculate median with MySQL

The below query will work perfect for both even or odd number of rows. In the subquery, we are finding the value(s) which has same number of rows before and after it. In case of odd rows the having clause will evaluate to 0 (same number of rows before and after cancels out the sign).

Similarly, for even rows the having clause evaluates to 1 for two rows (the center 2 rows) because they will (collectively) have same number of rows before and after.

In the outer query, we will avg out either the single value (in case of odd rows) or (2 values in case of even rows).

select avg(val) as median
from
(
    select d1.val
    from data d1 cross join data d2
    group by d1.val
    having abs(sum(sign(d1.val-d2.val))) in (0,1)
) sub

Note: In case your table has duplicate values, the above having clause should be changed to the below condition. In this case, there could be values outside of the original possibilities of 0,1. The below condition will make this condition dynamic and work in case of duplicates too.

having sum(case when d1.val=d2.val then 1 else 0 end)>=
abs(sum(sign(d1.val-d2.val)))

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

Mount current directory as a volume in Docker on Windows 10

For Git Bash for Windows (in ConEmu), the following works for me (for Docker Windows containers):

docker run --rm -it -v `pwd -W`:c:/api microsoft/dotnet:2-runtime

Note the backticks/backquotes around pwd -W!

With all other variations of PWD I've tried I've received: "Error response from daemon: invalid volume specification: ..."

Update: The above was for Docker Windows containers, for Linux containers use:

docker run --rm -it -v `pwd -W`:/api -p 8080:80 microsoft/aspnetcore:2

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

MySQL query to get column names?

This query fetches a list of all columns in a database without having to specify a table name. It returns a list of only column names:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE table_schema = 'db_name'

However, when I ran this query in phpmyadmin, it displayed a series of errors. Nonetheless, it worked. So use it with caution.

How much faster is C++ than C#?

.NET languages can be as fast as C++ code, or even faster, but C++ code will have a more constant throughput as the .NET runtime has to pause for GC, even if it's very clever about its pauses.

So if you have some code that has to consistently run fast without any pause, .NET will introduce latency at some point, even if you are very careful with the runtime GC.

In C#, can a class inherit from another class and an interface?

Yes. Try:

class USBDevice : GenericDevice, IOurDevice

Note: The base class should come before the list of interface names.

Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

Remove all whitespaces from NSString

stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end

Use

[YourString stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]]

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the following code.

File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');

if (lastSlash >= 0)
{
    fileName = url.toString().substring(lastSlash + 1);
}


if (fileName.endsWith("pdf"))
{
    mimeType = "application/pdf";
}
else
{
    mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
    (MimeTypeMap.getFileExtensionFromUrl(path));
}

Uri uri_path = Uri.fromFile(file);

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);

startActivity(intent);

How do you write to a folder on an SD card in Android?

In order to download a file to Download or Music Folder In SDCard

File downlodDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);// or DIRECTORY_PICTURES

And dont forget to add these permission in manifest

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

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

CSS Animation and Display None

CSS (or jQuery, for that matter) can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);

#main-image{
    height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.

You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/

Why can't I use a list as a dict key in python?

Your awnser can be found here:

Why Lists Can't Be Dictionary Keys

Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.

Source & more info: http://wiki.python.org/moin/DictionaryKeys

What is the difference between CSS and SCSS?

And this is less

@primarycolor: #ffffff;
@width: 800px;

body{
 width: @width;
 color: @primarycolor;
 .content{
  width: @width;
  background:@primarycolor;
 }
}

How do I import a .bak file into Microsoft SQL Server 2012?

You can use the following script if you don't wish to use Wizard;

RESTORE DATABASE myDB
FROM  DISK = N'C:\BackupDB.bak' 
WITH  REPLACE,RECOVERY,  
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',  
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'

Convert string to buffer Node

You can do:

var buf = Buffer.from(bufStr, 'utf8');

But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.

Why does the C preprocessor interpret the word "linux" as the constant "1"?

This appears to be an (undocumented) "GNU extension": [correction: I finally found a mention in the docs. See below.]

The following command uses the -dM option to print all preprocessor defines; since the input "file" is empty, it shows exactly the predefined macros. It was run with gcc-4.7.3 on a standard ubuntu install. You can see that the preprocessor is standard-aware. In total, there 243 macros with -std=gnu99 and 240 with -std=c99; I filtered the output for relevance.

$ cpp --std=c89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu89 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

$ cpp --std=c99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

$ cpp --std=gnu99 -dM < /dev/null | grep linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

The "gnu standard" versions also #define unix. (Using c11 and gnu11 produces the same results.)

I suppose they had their reasons, but it seems to me to make the default installation of gcc (which compiles C code with -std=gnu89 unless otherwise specified) non-conformant, and -- as in this question -- surprising. Polluting the global namespace with macros whose names don't begin with an underscore is not permitted in a conformant implementation. (6.8.10p2: "Any other predefined macro names shall begin with a leading underscore followed by an uppercase letter or a second underscore," but, as mentioned in Appendix J.5 (portability issues), such names are often predefined.)

When I originally wrote this answer, I wasn't able to find any documentation in gcc about this issue, but I did finally discover it, not in C implementation-defined behaviour nor in C extensions but in the cpp manual section 3.7.3, where it notes that:

We are slowly phasing out all predefined macros which are outside the reserved namespace. You should never use them in new programs…

Angular 2 execute script after template render

I've used this method (reported here )

export class AppComponent {

  constructor() {
    if(document.getElementById("testScript"))
      document.getElementById("testScript").remove();
    var testScript = document.createElement("script");
    testScript.setAttribute("id", "testScript");
    testScript.setAttribute("src", "assets/js/test.js");
    document.body.appendChild(testScript);
  }
}

it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

How to stop text from taking up more than 1 line?

You can use CSS white-space Property to achieve this.

white-space: nowrap

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

add these in php file where your ajax url call

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

How to run composer from anywhere?

For MAC and LINUX use the following procedure:

Add the directory where composer.phar is located to you PATH:

export PATH=$PATH:/yourdirectory

and then rename composer.phar to composer:

mv composer.phar composer

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

How do I "commit" changes in a git submodule?

$ git submodule status --recursive

Is also a life saver in this situation. You can use it and gitk --all to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.

reading text file with utf-8 encoding using java

Use

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;     
    public class test {
    public static void main(String[] args){

    try {
        File fileDir = new File("PATH_TO_FILE");

        BufferedReader in = new BufferedReader(
           new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));

        String str;

        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }

                in.close();
        } 
        catch (UnsupportedEncodingException e) 
        {
            System.out.println(e.getMessage());
        } 
        catch (IOException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

You need to put UTF-8 in quotes

Problems when trying to load a package in R due to rJava

An alternative package that you can use is readxl. This package don't require external dependencies.

Getting the folder name from a path

DirectoryInfo does the job to strip directory name

string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name;  // System32

find all subsets that sum to a particular value

Following solution also provide array of subset which provide specific sum (here sum = 9)

array = [1, 3, 4, 2, 7, 8, 9]

(0..array.size).map { |i| array.combination(i).to_a.select { |a| a.sum == 9 } }.flatten(1)

return array of subsets which return sum of 9

 => [[9], [1, 8], [2, 7], [3, 4, 2]] 

Clear and refresh jQuery Chosen dropdown list

Using .trigger("chosen:updated"); you can update the options list after appending.

Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

Your code:

$("#refreshgallery").click(function(){
        $('#picturegallery').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#picturegallery').append(newOption);
        $('#picturegallery').trigger("chosen:updated");
    });

Is it possible to import modules from all files in a directory, using a wildcard?

The current answers suggest a workaround but it's bugged me why this doesn't exist, so I've created a babel plugin which does this.

Install it using:

npm i --save-dev babel-plugin-wildcard

then add it to your .babelrc with:

{
    "plugins": ["wildcard"]
}

see the repo for detailed install info


This allows you to do this:

import * as Things from './lib/things';

// Do whatever you want with these :D
Things.ThingA;
Things.ThingB;
Things.ThingC;

again, the repo contains further information on what exactly it does, but doing it this way avoids creating index.js files and also happens at compile-time to avoid doing readdirs at runtime.

Also with a newer version you can do exactly like your example:

 import { ThingsA, ThingsB, ThingsC } from './lib/things/*';

works the same as the above.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.

Linux bash: Multiple variable assignment

Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign

MYVAR="something"

The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).

This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.

How to resolve ambiguous column names when retrieving results?

There are two approaches:

  1. Using aliases; in this method you give new unique names (ALIAS) to the various columns and then use them in the PHP retrieval. e.g.

    SELECT student_id AS FEES_LINK, student_class AS CLASS_LINK 
    FROM students_fee_tbl 
    LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
    

    and then fetch the results in PHP:

    $query = $PDO_stmt->fetchAll();
    
    foreach($query as $q) {
        echo $q['FEES_LINK'];
    }
    
  2. Using place position or resultset column index; in this, the array positions are used to reference the duplicated column names. Since they appear at different positions, the index numbers that will be used is always unique. However, the index positioning numbers begins at 0. e.g.

    SELECT student_id, student_class 
    FROM students_fee_tbl 
    LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
    

    and then fetch the results in PHP:

    $query = $PDO_stmt->fetchAll();
    
    foreach($query as $q) {
        echo $q[0];
    }
    

Split comma-separated values

You could use LINQBridge (MIT Licensed) to add support for lambda expressions to C# 2.0:

With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.

So, yes, the launch screens need to be that size.

The maths:

The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.

The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.

In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.

Reduce left and right margins in matplotlib plot

plt.savefig("circle.png", bbox_inches='tight',pad_inches=-1)

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

Getting date format m-d-Y H:i:s.u from milliseconds

Here's a slightly shorter approach. Rather than work to create a high-precision numeric date/time, I convert the microsecond value to a string, remove the 0, and add it to the end of the date/time string. I can easily trim the number of decimals by adjusting the string length parameter; here I use 4 to get milliseconds, but you could use 7 to get microseconds.

$t = explode(" ",microtime());
echo date("m-d-y H:i:s",$t[1]).substr((string)$t[0],1,4);

For a microtime() value of 0.98236000 1407400573, this returns 08-07-14 01:08:13.982.

Java Enum Methods - return opposite direction enum

This works:

public enum Direction {
    NORTH, SOUTH, EAST, WEST;

    public Direction oppose() {
        switch(this) {
            case NORTH: return SOUTH;
            case SOUTH: return NORTH;
            case EAST:  return WEST;
            case WEST:  return EAST;
        }
        throw new RuntimeException("Case not implemented");
    }
}

How to create a DataTable in C# and how to add rows?

Question 1: How do create a DataTable in C#?

Answer 1:

DataTable dt = new DataTable(); // DataTable created

// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");

Note: There is no need to Clear() the DataTable after creating it.

Question 2: How to add row(s)?

Answer 2: Add one row:

dt.Rows.Add("Ravi","500");

Add multiple rows: use ForEach loop

DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
    dt.Rows.Add(dr["Name"], dr["Marks"]);
}

Execute function after Ajax call is complete

You can use .ajaxStop() or .ajaxComplete()

.ajaxComplete() fires after completion of each AJAX request on your page.

$( document ).ajaxComplete(function() {
  yourFunction();
});

.ajaxStop() fires after completion of all AJAX requests on your page.

$( document ).ajaxStop(function() {
  yourFunction();
});

Python: how can I check whether an object is of type datetime.date?

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

Detecting attribute change of value of an attribute I made

You can use MutationObserver to track attribute changes including data-* changes. For example:

_x000D_
_x000D_
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
  attributes: true, _x000D_
  attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
 <div id='foo'></div>_x000D_
 
_x000D_
_x000D_
_x000D_

Extract value of attribute node via XPath

//Parent/Children[@  Attribute='value']/@Attribute

This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

Calculating how many minutes there are between two times

If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):

// Default value that is returned is of type *double* 
double double_minutes = endTime.Subtract(startTime).TotalMinutes; 
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes; 
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes; 
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes; 

HTML5 Canvas: Zooming

IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.

Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.

Change the location of an object programmatically

When the parent panel has locked property set to true, we could not change the location property and the location property will act like read only by that time.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

This could help

function exportToExcel(){
var htmls = "";
            var uri = 'data:application/vnd.ms-excel;base64,';
            var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'; 
            var base64 = function(s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            };

            var format = function(s, c) {
                return s.replace(/{(\w+)}/g, function(m, p) {
                    return c[p];
                })
            };

            htmls = "YOUR HTML AS TABLE"

            var ctx = {
                worksheet : 'Worksheet',
                table : htmls
            }


            var link = document.createElement("a");
            link.download = "export.xls";
            link.href = uri + base64(format(template, ctx));
            link.click();
}

How to sort mongodb with pymongo

You can try this:

db.Account.find().sort("UserName")  
db.Account.find().sort("UserName",pymongo.ASCENDING)   
db.Account.find().sort("UserName",pymongo.DESCENDING)  

Laravel Migration table already exists, but I want to add new not the older

Edit AppServiceProvider.php will be found at app/Providers/AppServiceProvider.php and add

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

Then run

composer update

On your terminal. It helped me, may be it will work for you as well.

How to deploy a war file in JBoss AS 7?

Read the file $AS/standalone/deployments/README.txt

  • you have two different modes : auto-deploy mode and manual deploy mode
  • for the manual deploy mode you have to placed a marker files as described in the others posts
  • for the autodeploy mode : This is done via the "auto-deploy" attributes on the deployment-scanner element in the standalone.xml configuration file:

    <deployment-scanner scan-interval="5000" relative-to="jboss.server.base.dir"
    path="deployments" auto-deploy-zipped="true" **auto-deploy-exploded="true"**/>