Programs & Examples On #Theming

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

npm install -g npm-install-peers

it will add all the missing peers and remove all the error

Show hide divs on click in HTML and CSS without jQuery

I like Roko's answer, and added a few lines to it so that you get a triangle that points right when the element is hidden, and down when it is displayed:

.collapse { font-weight: bold; display: inline-block; }
.collapse + input:after { content: " \25b6"; display: inline-block; }
.collapse + input:checked:after { content: " \25bc"; display: inline-block; }
.collapse + input { display: inline-block; -webkit-appearance: none; -o-appearance:none; -moz-appearance:none;  }
.collapse + input + * { display: none; }
.collapse + input:checked + * { display: block; }

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

The solution I ended up choosing was MahApps.Metro (github), which (after using it on two pieces of software now) I consider an excellent UI kit (credit to Oliver Vogel for the suggestion).

Window style

It skins the application with very little effort required, and has adaptations of the standard Windows 8 controls. It's very robust.

Text box watermark

A version is available on Nuget:

You can install MahApps.Metro via Nuget using the GUI (right click on your project, Manage Nuget References, search for ‘MahApps.Metro’) or via the console:

PM> Install-Package MahApps.Metro

It's also free -- even for commercial use.

Update 10-29-2013:

I discovered that the Github version of MahApps.Metro is packed with controls and styles that aren't available in the current nuget version, including:

Datagrids:

enter image description here

Clean Window:

enter image description here

Flyouts:

enter image description here

Tiles:

enter image description here

The github repository is very active with quite a bit of user contributions. I recommend checking it out.

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

jQuery append and remove dynamic table row

You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.

Also, move the .on() outside of the .click() function, as you only need to set it once.

http://jsfiddle.net/samliew/3AJcj/2/

$(document).ready(function(){
    $(".addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });
    $("#customFields").on('click','.remCF',function(){
        $(this).parent().parent().remove();
    });
});

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

Android Studio: Unable to start the daemon process

Steps to solve problem in android studio

  1. Click on file and select a other setting from dropdown menu and then select default setting.

  2. Select build,Execution,Deployment option.

  3. Select Compiler

  4. Here add a following line in Additional build process VM option

    -Xmx3072m -XX:MaxPermSize=524m as shown in below figure. 
    

image

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Concepts

Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.

What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map, ...). This allows to handle asynchronous things in a very flexible way.

A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:

this.textValue.valueChanges
    .debounceTime(500)
    .switchMap(data => this.httpService.getListValues(data))
    .subscribe(data => console.log('new list values', data));

(textValue is the control associated with the filter input).

Here is a wider description of such use case: How to watch for form changes in Angular 2?.

There are two great presentations at AngularConnect 2015 and EggHead:

Christoph Burgdorf also wrote some great blog posts on the subject:

In action

In fact regarding your code, you mixed two approaches ;-) Here are they:

  • Manage the observable by your own. In this case, you're responsible to call the subscribe method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of result">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit, OnDestroy {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.friendsObservable = http.get('friends.json')
                      .map(response => response.json())
                      .subscribe(result => this.result = result);
       }
    
       ngOnDestroy() {
         this.friendsObservable.dispose();
       }
    }
    

    Returns from both get and map methods are the observable not the result (in the same way than with promises).

  • Let manage the observable by the Angular template. You can also leverage the async pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe method.

    @Component({
      template: `
        <h1>My Friends</h1>
        <ul>
          <li *ngFor="#frnd of (result | async)">
            {{frnd.name}} is {{frnd.age}} years old.
          </li>
        </ul>
      `,
      directive:[CORE_DIRECTIVES]
    })
    export class FriendsList implement OnInit {
      result:Array<Object>; 
    
      constructor(http: Http) {
      }
    
      ngOnInit() {
        this.result = http.get('friends.json')
                      .map(response => response.json());
       }
    }
    

You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe method.

You can also notice that the map method is used to extract the JSON content from the response and use it then in the observable processing.

Hope this helps you, Thierry

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

Arduino Tools > Serial Port greyed out

Try to run as an administrator... Run terminal, type sudo arduino, type your root password, and... :)

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

BigDecimal to string

For better support different locales use this way:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);

df.format(bigDecimal);

also you can customize it:

DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);

Convert date formats in bash

It's enough to do:

data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206

If you want to add also the time you can use in that way

data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`

echo $data
Wed Feb 6 03:57:15 EST 2019

echo $datatime
20190206 03:57:15

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

This working for DirectAdmin;

  1. Go to your DirectAdmin.
  2. Go to your MySQL Management.
  3. Select your database.
  4. Under your Accesse Host tab, there is a field. You should fill this field by xxx.xx.xxx.xx.
  5. Click on Add Host.

Finished. Now you can access to this DB by your your_database_username & your_database_password.
So Simple!

how to add new <li> to <ul> onclick with javascript

First you have to create a li(with id and value as you required) then add it to your ul.

Javascript ::

addAnother = function() {
    var ul = document.getElementById("list");
    var li = document.createElement("li");
    var children = ul.children.length + 1
    li.setAttribute("id", "element"+children)
    li.appendChild(document.createTextNode("Element "+children));
    ul.appendChild(li)
}

Check this example that add li element to ul.

jQuery AJAX form data serialize using PHP

_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
    var form=$("#myForm");_x000D_
    $("#smt").click(function(){_x000D_
        $.ajax({_x000D_
            type:"POST",_x000D_
            url:form.attr("action"),_x000D_
            data:form.serialize(),_x000D_
            success: function(response){_x000D_
                console.log(response);  _x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

This is perfect code , there is no problem.. You have to check that in php script.

Difference between Inheritance and Composition

as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.

pthread function from a class

My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

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

You can add this script to make a error when user inpect :D

Try this code

_x000D_
_x000D_
<script type="text/javascript">_x000D_
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(3(){(3 a(){8{(3 b(2){7((\'\'+(2/2)).6!==1||2%5===0){(3(){}).9(\'4\')()}c{4}b(++2)})(0)}d(e){g(a,f)}})()})();',17,17,'||i|function|debugger|20|length|if|try|constructor|||else|catch||5000|setTimeout'.split('|'),0,{}))_x000D_
</script>
_x000D_
_x000D_
_x000D_

From http://www.bloggerku.com/2017/08/memasang-anti-inspect.html

why are there two different kinds of for loops in java?

The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.

Is System.nanoTime() completely useless?

This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.

In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.

[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

Java 8 LocalDate Jackson format

annotation in Pojo without using additional dependencies

@DateTimeFormat (pattern = "yyyy/MM/dd", iso = DateTimeFormat.ISO.DATE)
private LocalDate enddate;

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

sh: react-scripts: command not found after running npm start

Just doing an Yarn install solved the problem for me

What does the @Valid annotation indicate in Spring?

IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

How to Replace Multiple Characters in SQL?

One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.

The general idea of char replacement can be demonstrated with a simple character map table approach:

create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')


create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')

select 
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar

Then you can bring in the tally table approach to do the lookup on each character position in the string.

create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
    insert tally values (@i)
    set @i = @i + 1
end

create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')

select
    i,
    SUBSTRING(testString, i, 1) as srcChar,
    coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
    left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

Adding asterisk to required fields in Bootstrap 3

This CSS worked for me:

.form-group.required.control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -10px;
}

and this HTML:

<div class="form-group required control-label">
  <label for="emailField">Email</label>
  <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>

pandas: best way to select all columns whose names start with X

The simplest way is to use str directly on column names, there is no need for pd.Series

df.loc[:,df.columns.str.startswith("foo")]


How to kill zombie process

You can clean up a zombie process by killing its parent process with the following command:

kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')

How to debug .htaccess RewriteRule not working

Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:

<Directory ..>
    ...
    AllowOverride None
    ...
</Directory>

Should be changed to

AllowOverride All

And you'll be able to change directives in .htaccess files.

How to encode a URL in Swift

Adding to Bryan Chen's answer above:

Just incase anyone else is getting something similar with Alamofire:

error: Alamofire was compiled with optimization - stepping may behave oddly; variables may not be available.

It's not a very descriptive error. I was getting that error when constructing a URL for google geo services. I was appending a street address to the end of the URL WITHOUT encoding the street address itself first. I was able to fix it using Bryan Chen's solution:

var streetAdress = "123 fake street, new york, ny"
var escapedStreetAddress = streetAddress.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = "\(self.baseUrl)&address=\(escapedAddress!)"

That fixed it for me! It didnt like that the address had spaces and commas, etc.

Hope this helps someone else!

How to save python screen output to a text file

Here's a really simple way in python 3+:

f = open('filename.txt', 'w')
print('something', file = f)

^ found that from this answer: https://stackoverflow.com/a/4110906/6794367

How to create materialized views in SQL Server?

They're called indexed views in SQL Server - read these white papers for more background:

Basically, all you need to do is:

  • create a regular view
  • create a clustered index on that view

and you're done!

The tricky part is: the view has to satisfy quite a number of constraints and limitations - those are outlined in the white paper. If you do this, that's all there is. The view is being updated automatically, no maintenance needed.

Additional resources:

How do I create and store md5 passwords in mysql

Insertion:

INSERT INTO ... VALUES ('bob', MD5('bobspassword'));

retrieval:

SELECT ... FROM ... WHERE ... AND password=md5('hopefullybobspassword');

is how'd you'd do it directly in the queries. However, if your MySQL has query logging enabled, then the passwords' plaintext will get written out to this log. So... you'd want to do the MD5 conversion in your script, and then insert that resulting hash into the query.

Replacing few values in a pandas dataframe column with another value

loc function can be used to replace multiple values, Documentation for it : loc

df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'

SQL : BETWEEN vs <= and >=

Although BETWEEN is easy to read and maintain, I rarely recommend its use because it is a closed interval and as mentioned previously this can be a problem with dates - even without time components.

For example, when dealing with monthly data it is often common to compare dates BETWEEN first AND last, but in practice this is usually easier to write dt >= first AND dt < next-first (which also solves the time part issue) - since determining last usually is one step longer than determining next-first (by subtracting a day).

In addition, another gotcha is that lower and upper bounds do need to be specified in the correct order (i.e. BETWEEN low AND high).

How to convert a DataTable to a string in C#?

Prerequisite

using System.Linq;

then ...

string res = string.Join(Environment.NewLine, 
    results.Rows.OfType<DataRow>().Select(x => string.Join(" ; ", x.ItemArray)));

What is the difference between Java RMI and RPC?

RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.

Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.

How do I use a C# Class Library in a project?

In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.

Then you can use anything in that assembly.

How can I set a dynamic model name in AngularJS?

What I ended up doing is something like this:

In the controller:

link: function($scope, $element, $attr) {
  $scope.scope = $scope;  // or $scope.$parent, as needed
  $scope.field = $attr.field = '_suffix';
  $scope.subfield = $attr.sub_node;
  ...

so in the templates I could use totally dynamic names, and not just under a certain hard-coded element (like in your "Answers" case):

<textarea ng-model="scope[field][subfield]"></textarea>

Hope this helps.

Exposing a port on a live Docker container

You cannot do this via Docker, but you can access the container's un-exposed port from the host machine.

If you have a container with something running on its port 8000, you can run

wget http://container_ip:8000

To get the container's IP address, run the 2 commands:

docker ps
docker inspect container_name | grep IPAddress

Internally, Docker shells out to call iptables when you run an image, so maybe some variation on this will work.

To expose the container's port 8000 on your localhost's port 8001:

iptables -t nat -A  DOCKER -p tcp --dport 8001 -j DNAT --to-destination 172.17.0.19:8000

One way you can work this out is to setup another container with the port mapping you want, and compare the output of the iptables-save command (though, I had to remove some of the other options that force traffic to go via the docker proxy).

NOTE: this is subverting docker, so should be done with the awareness that it may well create blue smoke.

OR

Another alternative is to look at the (new? post 0.6.6?) -P option - which will use random host ports, and then wire those up.

OR

With 0.6.5, you could use the LINKs feature to bring up a new container that talks to the existing one, with some additional relaying to that container's -p flags? (I have not used LINKs yet.)

OR

With docker 0.11? you can use docker run --net host .. to attach your container directly to the host's network interfaces (i.e., net is not namespaced) and thus all ports you open in the container are exposed.

Environment Variable with Maven

in your code add:

System.getProperty("WSNSHELL_HOME")

Modify or add value property from maven command:

mvn clean test -DargLine=-DWSNSHELL_HOME=yourvalue

If you want to run it in Eclipse, add VM arguments in your Debug/Run configurations

  • Go to Run -> Run configurations
  • Select Tab Arguments
  • Add in section VM Arguments

-DWSNSHELL_HOME=yourvalue

See image example

you don't need to modify the POM

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.

e.g.

System.out.println("printing \"this\" in quotes");

outputs

printing "this" in quotes

Android studio - Failed to find target android-18

I've had a similar problem occurr when I had both Eclipse, Android Studio and the standalone Android SDK installed (the problem lied where the AVD Manager couldn't find target images). I had been using Eclipse for Android development but have moved over to Android Studio, and quickly found that Android Studio couldn't find my previously created AVDs.

The problem could potentially lie in that Android Studio is looking at it's own Android SDK (found in C:\Users\username\AppData\Local\Android\android-studio\sdk) and not a previously installed standalone SDK, which I had installed at C:\adt\sdk.

Renaming Android Studio's SDK folder, in C:\Users... (only rename it, just in case things break) then creating a symbolic link between the Android Studio SDK location and a standalone Android SDK fixes this issue.

I also used the Link Shell Extension (http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html) just to take the tedium out of creating symbolic links.

symfony2 : failed to write cache directory

You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.

Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):

rm -rf app/cache/dev*

Scroll to bottom of Div on page load (jQuery)

You can use below code to scroll to bottom of div on page load.

$(document).ready(function(){
  $('div').scrollTop($('div').scrollHeight);
});

Can't run Curl command inside my Docker Container

Ran into this same issue while using the CURL command inside my Dockerfile. As Gilles pointed out, we have to install curl first. These are the commands to be added in the 'Dockerfile'.

FROM ubuntu:16.04

# Install prerequisites
RUN apt-get update && apt-get install -y \
curl
CMD /bin/bash

brew install mysql on macOS

Had the same problem. Seems like there is something wrong with the set up instructions or the initial tables that are being created. This is how I got mysqld running on my machine.

If the mysqld server is already running on your Mac, stop it first with:

launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist

Start the mysqld server with the following command which lets anyone log in with full permissions.

mysqld_safe --skip-grant-tables

Then run mysql -u root which should now let you log in successfully without a password. The following command should reset all the root passwords.

UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root'; FLUSH PRIVILEGES;

Now if you kill the running copy of mysqld_safe and start it up again without the skip-grant-tables option, you should be able to log in with mysql -u root -p and the new password you just set.

git clone: Authentication failed for <URL>

After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:

cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe

Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html

My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.

delete all from table

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

TRUNCATE TABLE table_name

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

Statement interface Doc

SUMMARY: void setFetchSize(int rows) Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.

Read this ebook J2EE and beyond By Art Taylor

How to loop through a directory recursively to delete files with certain extensions

Without find:

for f in /tmp/* tmp/**/* ; do
  ...
done;

/tmp/* are files in dir and /tmp/**/* are files in subfolders. It is possible that you have to enable globstar option (shopt -s globstar). So for the question the code should look like this:

shopt -s globstar
for f in /tmp/*.pdf /tmp/*.doc tmp/**/*.pdf tmp/**/*.doc ; do
  rm "$f"
done

Note that this requires bash =4.0 (or zsh without shopt -s globstar, or ksh with set -o globstar instead of shopt -s globstar). Furthermore, in bash <4.3, this traverses symbolic links to directories as well as directories, which is usually not desirable.

Closing Application with Exit button

i try this

Button btnexit = (Button)findviewbyId(btn_exit);

btnexit.setOnClicklistenr(new onClicklister(){

     @override
     public void onClick(View v){
            finish();
});

Show/Hide Multiple Divs with Jquery

_x000D_
_x000D_
jQuery(function() {_x000D_
  jQuery('#showall').click(function() {_x000D_
    jQuery('.targetDiv').show();_x000D_
  });_x000D_
  jQuery('.showSingle').click(function() {_x000D_
    jQuery('.targetDiv').hide();_x000D_
    jQuery('#div' + $(this).attr('target')).show();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="buttons">_x000D_
  <a id="showall">All</a>_x000D_
  <a class="showSingle" target="1">Div 1</a>_x000D_
  <a class="showSingle" target="2">Div 2</a>_x000D_
  <a class="showSingle" target="3">Div 3</a>_x000D_
  <a class="showSingle" target="4">Div 4</a>_x000D_
</div>_x000D_
_x000D_
<div id="div1" class="targetDiv">Lorum Ipsum1</div>_x000D_
<div id="div2" class="targetDiv">Lorum Ipsum2</div>_x000D_
<div id="div3" class="targetDiv">Lorum Ipsum3</div>_x000D_
<div id="div4" class="targetDiv">Lorum Ipsum4</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/XwN2L/

Access Enum value using EL with JSTL

I do not have an answer to the question of Kornel, but I've a remark about the other script examples. Most of the expression trust implicitly on the toString(), but the Enum.valueOf() expects a value that comes from/matches the Enum.name() property. So one should use e.g.:

<% pageContext.setAttribute("Status_OLD", Status.OLD.name()); %>
...
<c:when test="${someModel.status == Status_OLD}"/>...</c:when>

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

How to read all files in a folder from Java?

In Java 7 and higher you can use listdir

Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path file: stream) {
        System.out.println(file.getFileName());
    }
} catch (IOException | DirectoryIteratorException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can only be thrown by newDirectoryStream.
    System.err.println(x);
}

You can also create a filter that can then be passed into the newDirectoryStream method above

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
    public boolean accept(Path file) throws IOException {
        try {
            return (Files.isRegularFile(path));
        } catch (IOException x) {
            // Failed to determine if it's a file.
            System.err.println(x);
            return false;
        }
    }
};

For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)

Bootstrap 3 Glyphicons are not working

I also faced the same problem, CSS was fine and there was no issue. It also had all the fonts included.

But the problem got resolved only after I installed the "glyphicons-halflings-regular.ttf" I started getting icons properly on the UI.

ERROR: Google Maps API error: MissingKeyMapError

The same issue i was facing couple of months back and that is because end of free google map usage effective from i think June 11, 2018. Google does not provide free google maps now. You need to have a valid API key and valid billing used, which may give you 200$ of free usage.

Refer link for more details: Google map pricing

Follow the process here to get your api key.

If you are upto using only maps with specific user, you can try other map tools.

Free FTP Library

Why don't you use the libraries that come with the .NET framework: http://msdn.microsoft.com/en-us/library/ms229718.aspx?

EDIT: 2019 April by https://stackoverflow.com/users/1527/ This answer is no longer valid. Other answers are endorsed by Microsoft.

They were designed by Microsoft who no longer recommend that they should be used:

We don't recommend that you use the FtpWebRequest class for new development. For more information and alternatives to FtpWebRequest, see WebRequest shouldn't be used on GitHub. (https://docs.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest?view=netframework-4.7.2)

The 'WebRequest shouldn't be used' page in turn points to this question as the definitive list of libraries!

Why do package names often begin with "com"

This is what Sun-Oracle documentation says:

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

jQuery attr('onclick')

Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use

$('#next').die().live('click', stopMoving);

this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.

How to return first 5 objects of Array in Swift?

Plain & Simple

extension Array {
    func first(elementCount: Int) -> Array {
          let min = Swift.min(elementCount, count)
          return Array(self[0..<min])
    }
}

Location of Django logs and errors

Logs are set in your settings.py file. A new, default project, looks like this:

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

By default, these don't create log files. If you want those, you need to add a filename parameter to your handlers

    'applogfile': {
        'level':'DEBUG',
        'class':'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
        'maxBytes': 1024*1024*15, # 15MB
        'backupCount': 10,
    },

This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.

In the loggers section from above, you need to add applogfile to the handlers for your application

'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'APPNAME': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }

This example will put your logs in your Django root in a file named APPNAME.log

Make a Bash alias that takes a parameter?

Once i did some fun project and i still use it. It's showing some animation while i copy files via cp command coz cp don't show anything and it's kind of frustrating. So i made this alias

alias cp="~/SCR/spiner cp"

And this is the spiner script

#!/bin/bash

#Set timer
T=$(date +%s)

#Add some color
. ~/SCR/color

#Animation sprites
sprite=( "(* )  ( *)" " (* )( *) " " ( *)(* ) " "( *)  (* )" "(* )  ( *)" )

#Print empty line and hide cursor
printf "\n${COF}"

#Exit function
function bye { printf "${CON}"; [ -e /proc/$pid ] && kill -9 $pid; exit; }; trap bye INT

#Run our command and get its pid
"$@" & pid=$!

#Waiting animation
i=0; while [ -e /proc/$pid ]; do sleep 0.1

    printf "\r${GRN}Please wait... ${YLW}${sprite[$i]}${DEF}"
    ((i++)); [[ $i = ${#sprite[@]} ]] && i=0

done

#Print time and exit
T=$(($(date +%s)-$T))
printf "\n\nTime taken: $(date -u -d @${T} +'%T')\n"

bye

It's look like this

enter image description here

Cycled animation)

enter image description here

Here is the link to a color script mentioned above. And new animation cycle)

enter image description here

Direct casting vs 'as' operator?

string s = (string)o; // 1

Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.

string s = o as string; // 2

Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.

string s = o.ToString(); // 3

Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.


Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).

3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

How to convert text to binary code in JavaScript?

Provided you're working in node or a browser with BigInt support, this version cuts costs by saving the expensive string construction for the very end:

const zero = 0n
const shift = 8n

function asciiToBinary (str) {
  const len = str.length
  let n = zero
  for (let i = 0; i < len; i++) {
    n = (n << shift) + BigInt(str.charCodeAt(i))
  }
  return n.toString(2).padStart(len * 8, 0)
}

It's about twice as fast as the other solutions mentioned here including this simple es6+ implementation:

const toBinary = s => [...s]
  .map(x => x
    .codePointAt()
    .toString(2)
    .padStart(8,0)
  )
  .join('')

If you need to handle unicode characters, here's this guy:

const zero = 0n
const shift = 8n
const bigShift = 16n
const byte = 255n

function unicodeToBinary (str) {
  const len = str.length
  let n = zero
  for (let i = 0; i < len; i++) {
    const bits = BigInt(str.codePointAt(i))
    n = (n << (bits > byte ? bigShift : shift)) + bits
  }
  const bin = n.toString(2)
  return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
}

How to get height of entire document with JavaScript?

I lied, jQuery returns the correct value for both pages $(document).height();... why did I ever doubt it?

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

No Title Bar Android Theme

use android:theme="@android:style/Theme.NoTitleBar in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

Adding delay between execution of two following lines

I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:

        let delay = 2.0 * Double(NSEC_PER_SEC) 
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 
        dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }

I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Replace all latters from any language in 'A', and if you wish for example all digits to 0:

return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");

How to uncheck checkbox using jQuery Uniform library

The other way to do is is,

use $('#check2').click();

this causes uniform to check the checkbox and update it's masks

how to show progress bar(circle) in an activity having a listview before loading the listview with data

There are several methods of showing a progress bar (circle) while loading an activity. In your case, one with a ListView in it.

IN ACTIONBAR

If you are using an ActionBar, you can call the ProgressBar like this (this could go in your onCreate()

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
setProgressBarIndeterminateVisibility(true);

And after you are done displaying the list, to hide it.

setProgressBarIndeterminateVisibility(false);

IN THE LAYOUT (The XML)

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:divider="#00000000"
        android:dividerHeight="0dp"
        android:fadingEdge="none"
        android:persistentDrawingCache="scrolling"
        android:smoothScrollbar="false" >
    </ListView>
</LinearLayout>

And in your activity (Java) I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute() I use something like this:

// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

@Override
protected void onPreExecute() {    
    // SHOW THE SPINNER WHILE LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.VISIBLE);
}

and in the onPostExecute(), after setting the adapter to the ListView:

@Override
protected void onPostExecute(Void result) {     
    // SET THE ADAPTER TO THE LISTVIEW
    lv.setAdapter(adapter);

    // CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
    loadingMore = false;

    // HIDE THE SPINNER AFTER LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.GONE);
}

EDIT: This is how it looks in my app while loading one of several ListViews

enter image description here

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Just select all of the files you want to compare, then open the context menu (Right-Click on the file) and choose Compare With, Then select each other..

Swift GET request with parameters

You can extend your Dictionary to only provide stringFromHttpParameter if both key and value conform to CustomStringConvertable like this

extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
  func stringFromHttpParameters() -> String {
    var parametersString = ""
    for (key, value) in self {
      parametersString += key.description + "=" + value.description + "&"
    }
    return parametersString
  }
}

this is much cleaner and prevents accidental calls to stringFromHttpParameters on dictionaries that have no business calling that method

Using Thymeleaf when the value is null

You've done twice the checking when you create

${someObject.someProperty != null} ? ${someObject.someProperty}

You should do it clean and simple as below.

<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>

How to count occurrences of a column value efficiently in SQL?

select s.id, s.age, c.count
from students s
inner join (
    select age, count(*) as count
    from students
    group by age
) c on s.age = c.age
order by id

Calling javascript function in iframe

The first and foremost condition that needs to be met is that both the parent and iframe should belong to the same origin. Once that is done the child can invoke the parent using window.opener method and the parent can do the same for the child as mentioned above

Getting parts of a URL (Regex)

I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (http://example.com/)

also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).

so this is my version slightly modified with the source being the highest voted version here:

^((?P<protocol>http[s]?|ftp):\/)?\/?(?P<host>[^:\/\s]+)(?P<path>((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$

'git' is not recognized as an internal or external command

  • Make sure correct git path is added to Path variable in your Environment Variables. E.g. - C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd. It can be different for your case depending on where your git gets installed.
  • If it doesnt work, try restarting the command prompt so that it reads the updated Environment Variables.
  • If it still doesnt work, try restarting your machine to force command prompt to read the updated Environment variables.

linq where list contains any in list

I guess this is also possible like this?

var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));

Is "TakeWhile" worse than "Where" in sense of performance or clarity?

RichTextBox (WPF) does not have string property "Text"

How about just doing the following:

_richTextBox.SelectAll();
string myText = _richTextBox.Selection.Text;

How to inject window into a service?

There is an opportunity for direct access to the object of window through the document

document.defaultView == window

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

Try this...  
  <script type="text/javascript">

    $(document).ready(function(){

    $("#find").click(function(){
        var username  = $("#username").val();
            $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'includes/find.php',
            data: 'username='+username,
            success: function( data ) {
            //in data you result will be available...
            response = jQuery.parseJSON(data);
//further code..
            },

    error: function(xhr, status, error) {
        alert(status);
        },
    dataType: 'text'

    });
        });

    });



    </script>

    <form name="Find User" id="userform" class="invoform" method="post" />

    <div id ="userdiv">
      <p>Name (Lastname, firstname):</p>
      </label>
      <input type="text" name="username" id="username" class="inputfield" />
      <input type="button" name="find" id="find" class="passwordsubmit" value="find" />
    </div>
    </form>
    <div id="userinfo"><b>info will be listed here.</b></div>

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

How to use the toString method in Java?

Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use

 System.out.println(myObject);

or

System.out.println("text " + myObject);

How can I check if an array contains a specific value in php?

See in_array

<?php
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");    
    if (in_array("kitchen", $arr))
    {
        echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
    }
?>

Using boolean values in C

If you are using a C99 compiler it has built-in support for bool types:

#include <stdbool.h>
int main()
{
  bool b = false;
  b = true;
}

http://en.wikipedia.org/wiki/Boolean_data_type

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting the painted border false?

JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);

It works on my mac :)

Material effect on button with background color

There are two approaches explained in the great tutorial be Alex Lockwood: http://www.androiddesignpatterns.com/2016/08/coloring-buttons-with-themeoverlays-background-tints.html:

Approach #1: Modifying the button’s background color w/ a ThemeOverlay

<!-- res/values/themes.xml -->
<style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">@color/googred500</item>
</style>

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/RedButtonLightTheme"/>

Approach #2: Setting the AppCompatButton’s background tint

<!-- res/color/btn_colored_background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Disabled state. -->
    <item android:state_enabled="false"
          android:color="?attr/colorButtonNormal"
          android:alpha="?android:attr/disabledAlpha"/>

    <!-- Enabled state. -->
    <item android:color="?attr/colorAccent"/>

</selector>

<android.support.v7.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="@color/btn_colored_background_tint"/>

Use table row coloring for cells in Bootstrap

Bottom line is that you'll have to write a new css rule for that.

Depending on which bundle of Twitter Bootstrap you're using, you should have variables for the various colours.

Try something like:

.table tbody tr > td {
  &.success { background-color: $green; }
  &.info { background-color: $blue; }
  ...
}

Surely there's a way to use extend or the LESS equivalent to avoid repeating the same styling.

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

html cellpadding the left side of a cell

This is what css is for... HTML doesn't allow for unequal padding. When you say that you don't want to use style sheets, does this mean you're OK with inline css?

<table>
    <tr>
        <td style="padding: 5px 10px 5px 5px;">Content</td>
        <td style="padding: 5px 10px 5px 5px;">Content</td>
    </tr>
</table>

You could also use JS to do this if you're desperate not to use stylesheets for some reason.

Gradle: Execution failed for task ':processDebugManifest'

I had the same problem and none of the other answers helped.

In my case, a comment in the manifest file was the culprit:

<manifest [...]
    android:installLocation="auto">
    <!-- change installLocation back to external after test -->

    <uses-sdk [...]

(This might be a bug, seeing how comments in other areas of the manifest dont cause any problems.)

Why is visible="false" not working for a plain html table?

If you want use it, use runat="server" for that table. After that use tablename.visible=False in server side code.

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

How to rotate the background image in the container?

Update 2020, May:

Setting position: absolute and then transform: rotate(45deg) will provide a background:

_x000D_
_x000D_
div {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  outline: 2px dashed slateBlue;_x000D_
  overflow: hidden;_x000D_
}_x000D_
div img {_x000D_
  position: absolute;_x000D_
  transform: rotate(45deg);_x000D_
  z-index: -1;_x000D_
  top: 40px;_x000D_
  left: 40px;_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://placekitten.com/120/120" />_x000D_
  <h1>Hello World!</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Original Answer:

In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop. An alternative to photoshop for rotating images is online tool too for rotating images. Once rotated, I'm working with the rotated-image in the background property.

div.with-background {
    background-image: url(/img/rotated-image.png);
    background-size:     contain;
    background-repeat:   no-repeat;
    background-position: top center;
}

Good Luck...

Checking if my Windows application is running

public partial class App : System.Windows.Application
{
    public bool IsProcessOpen(string name)
    {
        foreach (Process clsProcess in Process.GetProcesses()) 
        {
            if (clsProcess.ProcessName.Contains(name))
            {
                return true;
            }
        }

        return false;
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        // Get Reference to the current Process
        Process thisProc = Process.GetCurrentProcess();

        if (IsProcessOpen("name of application.exe") == false)
        {
            //System.Windows.MessageBox.Show("Application not open!");
            //System.Windows.Application.Current.Shutdown();
        }
        else
        {
            // Check how many total processes have the same name as the current one
            if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
            {
                // If ther is more than one, than it is already running.
                System.Windows.MessageBox.Show("Application is already running.");
                System.Windows.Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }
    }

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

Easy and fast fix for me was to npm install the specific package on which it said the sha is wrong. Say your package is called awesome-package.

My solution was:

npm i awesome-package

This updated my sha within the package-lock.json.

How to refer environment variable in POM.xml?

You can use <properties> tag to define a custom variable and ${variable} pattern to use it

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- define -->
    <properties>
        <property.name>1.0</property.name>
    </properties>

    <!-- using -->
    <version>${property.name}</version>

</project>

What does "hard coded" mean?

"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.

Where should I put <script> tags in HTML markup?

If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.

What is the difference between old style and new style classes in Python?

From New-style and classic classes:

Up to Python 2.1, old-style classes were the only flavour available to the user.

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>.

This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.

If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.

It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.

For compatibility reasons, classes are still old-style by default.

New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed.

The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.

Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.

Python 3 only has new-style classes.

No matter if you subclass from object or not, classes are new-style in Python 3.

How to pass a single object[] to a params object[]

Another way to solve this problem (it's not so good practice but looks beauty):

static class Helper
{
    public static object AsSingleParam(this object[] arg)
    {
       return (object)arg;
    }
}

Usage:

f(new object[] { 1, 2, 3 }.AsSingleParam());

Overcoming "Display forbidden by X-Frame-Options"

Edit .htaccess if you want to remove X-Frame-Options from an entire directory.

And add the line: Header always unset X-Frame-Options

[contents from: Overcoming "Display forbidden by X-Frame-Options"

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

Store text file content line by line into array

Just use Apache Commons IO

List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));

How to log Apache CXF Soap Request and Soap Response using Log4j?

Another easy way is to set the logger like this- ensure that you do it before you load the cxf web service related classes. You can use it in some static blocks.

YourClientConstructor() {

  LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);

  URL wsdlURL = YOurURL;//

  //create the service
  YourService = new YourService(wsdlURL, SERVICE_NAME);
  port = yourService.getServicePort(); 

  Client client = ClientProxy.getClient(port);
  client.getInInterceptors().add(new LoggingInInterceptor());
  client.getOutInterceptors().add(new LoggingOutInterceptor());
}

Then the inbound and outbound messages will be printed to Log4j file instead of the console. Make sure your log4j is configured properly

Import Excel spreadsheet columns into SQL Server database

I have used DTS (now known as SQL server Import and Export Wizard). I used the this tutorial which worked great for me even in Sql 2008 and excel 2010 (14.0)

I hope this helps

-D

Unable to import a module that is definitely installed

I had colorama installed via pip and I was getting "ImportError: No module named colorama"

So I searched with "find", found the absolute path and added it in the script like this:

import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama 

And it worked.

How do I reverse a commit in git?

You can do git push --force but be aware that you are rewriting history and anyone using the repo will have issue with this.

If you want to prevent this problem, don't use reset, but instead use git revert

Using Python 3 in virtualenv

I had the same ERROR message. tbrisker's solution did not work in my case. Instead this solved the issue:

$ python3 -m venv .env

Real differences between "java -server" and "java -client"?

When doing a migration from 1.4 to 1.7("1.7.0_55") version.The thing that we observed here is, there is no such differences in default values assigned to heapsize|permsize|ThreadStackSize parameters in client & server mode.

By the way, (http://www.oracle.com/technetwork/java/ergo5-140223.html). This is the snippet taken from above link.

initial heap size of 1/64 of physical memory up to 1Gbyte
maximum heap size of ¼ of physical memory up to 1Gbyte

ThreadStackSize is higher in 1.7, while going through Open JDK forum,there are discussions which stated frame size is somewhat higher in 1.7 version. It is believed real difference could be possible to measure at run time based on your behavior of your application

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

how to customise input field width in bootstrap 3

You can use these classes

input-lg

input

and

input-sm

for input fields and replace input with btn for buttons.

Check this documentation http://getbootstrap.com/getting-started/#migration

This will change only height of the element, to reduce the width you have to use grid system classes like col-xs-* col-md-* col-lg-*.

Example col-md-3. See doc here http://getbootstrap.com/css/#grid

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

Node Express sending image files as API response

There is an api in Express.

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

Why do we check up to the square root of a prime number to determine if it is prime?

It's all really just basic uses of Factorization and Square Roots.

It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:

sqrroot(n) * sqrroot(n) = n.

Given that, if any whole number above 1 and below or up to sqrroot(n) divides evenly into n, then n cannot be a prime number.

Pseudo-code example:

i = 2;

is_prime = true;

while loop (i <= sqrroot(n))
{
  if (n % i == 0)
  {
    is_prime = false;
    exit while;
  }
  ++i;
}

How to set image button backgroundimage for different state?

what you are trying to do is more a segmentedbutton than an imagebutton list.

here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need

Visual Studio Code includePath

I tried this and now working Configuration for c_cpp_properties.json

{
"configurations": [
    {
        "name": "Win32",
        "compilerPath": "C:/MinGW/bin/g++.exe",
        "includePath": [
            "C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
        ],
        "defines": [
            "_DEBUG",
            "UNICODE",
            "_UNICODE"
        ],
        "cStandard": "c17",
        "cppStandard": "c++17",
        "intelliSenseMode": "windows-gcc-x64"
    }
],
"version": 4
  }

task.json configuration File

{
"version": "2.0.0",
"tasks": [
    {
        "type": "cppbuild",
        "label": "C/C++: g++.exe build active file",
        "command": "C:\\MinGW\\bin\\g++.exe",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileDirname}\\${fileBasenameNoExtension}.exe"
        ],
        "options": {
            "cwd": "C:\\MinGW\\bin"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": {
            "kind": "build",
            "isDefault": true
        },
        "detail": "compiler: C:\\MinGW\\bin\\g++.exe"
    }
]}

How to concatenate variables into SQL strings

You can accomplish this (if I understand what you are trying to do) using dynamic SQL.

The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.

So you can use something like this approach:

SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue 
    + ' AS fld1 FROM tbl' + @KeyValue

EXEC (@stmt)

First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:

'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'

At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE (or EXEC for short).

The old-school sp_executesql procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.


FOLLOWUP

EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.

Consider what would happen if @KeyValue contained the string:

'1 AS foo; DROP TABLE students; -- '

The string we would produce as a SQL statement would be:

'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'

When we EXECUTE that string as a SQL statement:

INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...

And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)

One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'. If an illegal character is found, then reject the value, and exit without executing any SQL.

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

What is a singleton in C#?

A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.

There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.

To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.

graphing an equation with matplotlib

This is because in line

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

graph('x**3+2*x-4', range(-10, 11))

Docker: adding a file from a parent directory

The solution for those who use composer is to use a volume pointing to the parent folder:

#docker-composer.yml

foo:
  build: foo
  volumes:
    - ./:/src/:ro

But I'm pretty sure the can be done playing with volumes in Dockerfile.

#pragma pack effect

Note that there are other ways of achieving data consistency that #pragma pack offers (for instance some people use #pragma pack(1) for structures that should be sent across the network). For instance, see the following code and its subsequent output:

#include <stdio.h>

struct a {
    char one;
    char two[2];
    char eight[8];
    char four[4];
};

struct b { 
    char one;
    short two;
    long int eight;
    int four;
};

int main(int argc, char** argv) {
    struct a twoa[2] = {}; 
    struct b twob[2] = {}; 
    printf("sizeof(struct a): %i, sizeof(struct b): %i\n", sizeof(struct a), sizeof(struct b));
    printf("sizeof(twoa): %i, sizeof(twob): %i\n", sizeof(twoa), sizeof(twob));
}

The output is as follows: sizeof(struct a): 15, sizeof(struct b): 24 sizeof(twoa): 30, sizeof(twob): 48

Notice how the size of struct a is exactly what the byte count is, but struct b has padding added (see this for details on the padding). By doing this as opposed to the #pragma pack you can have control of converting the "wire format" into the appropriate types. For instance, "char two[2]" into a "short int" et cetera.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

How to change fontFamily of TextView in Android

An easy way to manage the fonts would be to declare them via resources, as such:

<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>

<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>

<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>

This is based on the source code here and here

How to make a GridLayout fit screen size

For other peeps: If you have to use GridLayout due to project requirements then use it but I would suggest trying out TableLayout as it seems much easier to work with and achieves a similar result.

Docs: https://developer.android.com/reference/android/widget/TableLayout.html

Example:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TableRow>

        <Button
            android:id="@+id/test1"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 1"
            android:drawableTop="@mipmap/android_launcher"
            />

        <Button
            android:id="@+id/test2"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 2"
            android:drawableTop="@mipmap/android_launcher"
            />

        <Button
            android:id="@+id/test3"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 3"
            android:drawableTop="@mipmap/android_launcher"
            />

        <Button
            android:id="@+id/test4"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 4"
            android:drawableTop="@mipmap/android_launcher"
            />

    </TableRow>

    <TableRow>

        <Button
            android:id="@+id/test5"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 5"
            android:drawableTop="@mipmap/android_launcher"
            />

        <Button
            android:id="@+id/test6"
            android:layout_width="wrap_content"
            android:layout_height="90dp"
            android:text="Test 6"
            android:drawableTop="@mipmap/android_launcher"
            />

    </TableRow>

</TableLayout>

How to create a notification with NotificationCompat.Builder?

You can try this code this works fine for me:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());

Grep regex NOT containing string

patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"

for i in {1..3}
 do
grep "${patterns[$i]}" logfile.log
done

should be the the same as

egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"    

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Hide/Show Column in an HTML Table

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var index = $(this).attr('name').substr(3);
        index--;
        $('table tr').each(function() { 
            $('td:eq(' + index + ')',this).toggle();
        });
        $('th.' + $(this).attr('name')).toggle();
    });
});
</script>
<body>
<table>
<thead>
    <tr>
        <th class="col1">Header 1</th>
        <th class="col2">Header 2</th>
        <th class="col3">Header 3</th>
    </tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

<form>
    <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
    <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
    <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

How does the ARM architecture differ from x86?

The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.

Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.

But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.

So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)

failed to open stream: HTTP wrapper does not support writeable connections

Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).

You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.

Dynamic WHERE clause in LINQ

You could use the Any() extension method. The following seems to work for me.

XStreamingElement root = new XStreamingElement("Results",
                from el in StreamProductItem(file)
                where fieldsToSearch.Any(s => el.Element(s) != null && el.Element(s).Value.Contains(searchTerm))
                select fieldsToReturn.Select(r => (r == "product") ? el : el.Element(r))
            );
            Console.WriteLine(root.ToString());

Where 'fieldsToSearch' and 'fieldsToReturn' are both List objects.

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

How to nicely format floating numbers to string without unnecessary decimal 0's

Format price with grouping, rounding, and no unnecessary zeroes (in double).

Rules:

  1. No zeroes at the end (2.0000 = 2; 1.0100000 = 1.01)
  2. Two digits maximum after a point (2.010 = 2.01; 0.20 = 0.2)
  3. Rounding after the 2nd digit after a point (1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)
  4. Returns 0 (null/-0 = 0)
  5. Adds $ (= $56/-$56)
  6. Grouping (101101.02 = $101,101.02)

More examples:

-99.985 = -$99.99

10 = $10

10.00 = $10

20.01000089 = $20.01

It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.

/**
 * 23.0 -> $23
 *
 * 23.1 -> $23.1
 *
 * 23.01 -> $23.01
 *
 * 23.99 -> $23.99
 *
 * 23.999 -> $24
 *
 * -0.0 -> $0
 *
 * -5.00 -> -$5
 *
 * -5.019 -> -$5.02
 */
fun Double?.formatUserAsSum(): String {
    return when {
        this == null || this == 0.0 -> "$0"
        this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
        else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
    }
}

How to use:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20

yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

JBoss debugging in Eclipse

VonC mentioned in his answer how to remote debug from Eclipse.

I would like to add that the JAVA_OPTS settings are already in run.conf.bat. You just have to uncomment them:

in JBOSS_HOME\bin\run.conf.bat on Windows:

rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"

The Linux version is similar and is located at JBOSS_HOME/bin/run.conf

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Use addHeader Instead of using setHeader method,

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains.


For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

Check this blog post.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

WebSocket with SSL

You can't use WebSockets over HTTPS, but you can use WebSockets over TLS (HTTPS is HTTP over TLS). Just use "wss://" in the URI.

I believe recent version of Firefox won't let you use non-TLS WebSockets from an HTTPS page, but the reverse shouldn't be a problem.

Adding an arbitrary line to a matplotlib plot in ipython notebook

Using vlines:

import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p =  plot(x, y, "o")
vlines(70,100,250)

The basic call signatures are:

vlines(x, ymin, ymax)
hlines(y, xmin, xmax)

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

How to print third column to last column?

awk '{a=match($0, $3); print substr($0,a)}'

First you find the position of the start of the third column. With substr you will print the whole line ($0) starting at the position(in this case a) to the end of the line.

How to use both onclick and target="_blank"

you can use

        <p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

What is the effect of encoding an image in base64?

Encoding an image to base64 will make it about 30% bigger.

See the details in the wikipedia article about the Data URI scheme, where it states:

Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

How to download files using axios

It's very simple javascript code to trigger a download for the user:

window.open("<insert URL here>")

You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.

Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.


As for whether it's possible... not with the in-built file downloading mechanism, no.

Use latest version of Internet Explorer in the webbrowser control

I was able to implement Luca's solution, but I had to make a few changes for it to work. My goal was to use D3.js with a Web Browser control for a Windows Forms Application (targeting .NET 2.0). It is working for me now. I hope this can help someone else.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;

namespace ClientUI
{
    static class Program
    {
        static Mutex mutex = new System.Threading.Mutex(false, "jMutex");

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                // Another application instance is running
                return;
            }
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
                int ie_emulation = 11999;
                try
                {
                    string tmp = Properties.Settings.Default.ie_emulation;
                    ie_emulation = int.Parse(tmp);
                }
                catch { }
                SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);

                Application.Run(new MainForm());
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }

        private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
        {
            RegistryKey Regkey = null;
            try
            {
                Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);

                // If the path is not correct or
                // if user doesn't have privileges to access the registry
                if (Regkey == null)
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
                    return;
                }

                string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                // Check if key is already present
                if (FindAppkey == ieval.ToString())
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
                    Regkey.Close();
                    return;
                }

                // If key is not present or different from desired, add/modify the key , key value
                Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);

                // Check for the key after adding
                FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                if (FindAppkey == ieval.ToString())
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
                }
                else
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is  " + ieval);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
            }
            finally
            {
                //Close the Registry
                if (Regkey != null) Regkey.Close();
            }
        }
    }
}

Also, I added a string (ie_emulation) to the project's settings with the value of 11999. This value seems to be working for IE11(11.0.15).

Next, I had to change the permission for my application to allow access to the registry. This can be done by adding a new item to your project (using VS2012). Under the General Items, select Application Manifest File. Change the level from asInvoker to requireAdministrator (as shown below).

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

If someone reading this is trying to use D3.js with a webbrowser control, you may have to modify the JSON data to be stored within a variable inside your HTML page because D3.json uses XmlHttpRequest (easier to use with a webserver). After those changes and the above, my windows forms are able to load local HTML files that call D3.

How to turn off Wifi via ADB?

adb shell "svc wifi enable"

This worked & it makes action in background without opening related option !!

Echo equivalent in PowerShell for script testing

It should also be mentioned, that Set-PSDebug is similar to the old-school echo on batch command:

Set-PSDebug -Trace 1

This command will result in showing every line of the executing script:

When the Trace parameter has a value of 1, each line of script is traced as it runs. When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you're prompted before each line of the script runs.

How to Save Console.WriteLine Output to Text File

Try if this works:

FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

How to change port for jenkins window service when 8080 is being used

In linux,

sudo vi /etc/sysconfig/jenkins

set following configuration with any available port

JENKINS_PORT="8082"

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.

Example:

document.getElementById( 'bottom' ).scrollIntoView();

Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/

Script:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

How to stop asynctask thread in android?

You can't just kill asynctask immediately. In order it to stop you should first cancel it:

task.cancel(true);

and than in asynctask's doInBackground() method check if it's already cancelled:

isCancelled()

and if it is, stop executing it manually.

How to trim white spaces of array values in php

I had trouble with the existing answers when using multidimensional arrays. This solution works for me.

if (is_array($array)) {
    foreach ($array as $key => $val) {
        $array[$key] = trim($val);
    }
}

How to remove stop words using nltk or python

To exclude all type of stop-words including nltk stop-words, you could do something like this:

from stop_words import get_stop_words
from nltk.corpus import stopwords

stop_words = list(get_stop_words('en'))         #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)

output = [w for w in word_list if not w in stop_words]

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

What is Gradle in Android Studio?

by @Brian Gardner:

Gradle is an extensive build tool and dependency manager for programming projects. It has a domain specific language based on Groovy. Gradle also provides build-by-convention support for many types of projects including Java, Android and Scala.

Feature of Gradle:

  1. Dependency Management
  2. Using Ant from Gradle
  3. Gradle Plugins
  4. Java Plugin
  5. Android Plugin
  6. Multi-Project Builds

How does the vim "write with sudo" trick work?

A summary (and very minor improvement) on the most common answers that I found for this as at 2020.

tl;dr

Call with :w!! or :W!!. After it expands, press enter.

  • If you are too slow in typing the !! after the w/W, it will not expand and might report: E492: Not an editor command: W!!

NOTE Use which tee output to replace /usr/bin/tee if it differs in your case.

Put these in your ~/.vimrc file:

    " Silent version of the super user edit, sudo tee trick.
    cnoremap W!! execute 'silent! write !sudo /usr/bin/tee "%" >/dev/null' <bar> edit!
    " Talkative version of the super user edit, sudo tee trick.
    cmap w!! w !sudo /usr/bin/tee >/dev/null "%"

More Info:

First, the linked answer below was about the only other that seemed to mitigate most known problems and differ in any significant way from the others. Worth reading: https://stackoverflow.com/a/12870763/2927555

My answer above was pulled together from multiple suggestions on the conventional sudo tee theme and thus very slightly improves on the most common answers I found. My version above:

  • Works with whitespace in file names

  • Mitigates path modification attacks by specifying the full path to tee.

  • Gives you two mappings, W!! for silent execution, and w!! for not silent, i.e Talkative :-)

  • The difference in using the non-silent version is that you get to choose between [O]k and [L]oad. If you don't care, use the silent version.

    • [O]k - Preserves your undo history, but will cause you to get warned when you try to quit. You have to use :q! to quit.
    • [L]oad - Erases your undo history and resets the "modified flag" allowing you to exit without being warned to save changes.

Information for the above was drawn from a bunch of other answers and comments on this, but notably:

Dr Beco's answer: https://stackoverflow.com/a/48237738/2927555

idbrii's comment to this: https://stackoverflow.com/a/25010815/2927555

Han Seoul-Oh's comment to this: How does the vim "write with sudo" trick work?

Bruno Bronosky comment to this: https://serverfault.com/a/22576/195239

This answer also explains why the apparently most simple approach is not such a good idea: https://serverfault.com/a/26334/195239

Turn a number into star rating display using jQuery and CSS

using jquery without prototype, update the js code to

$( ".stars" ).each(function() { 
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('<span />').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

<span class="stars" data-rating="4" ></span>

How to kill a process in MacOS?

If you know the process name you can use:

killall Dock

If you don't you can open Activity Monitor and find it.

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

Pythonic way to find maximum value and its index in a list?

This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.

import random
from datetime import datetime
import operator
import numpy as np

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

def npmax(l):
    max_idx = np.argmax(l)
    max_val = l[max_idx]
    return (max_idx, max_val)

if __name__ == "__main__":
    from timeit import Timer

t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
      "import random; import operator; import numpy as np;"
      "l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

Results on my computer:

Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you...

How to read a line from a text file in c/c++?

In C, fgets(), and you need to know the maximum size to prevent truncation.

datetime datatype in java

You can use Calendar.

     Calendar rightNow = Calendar.getInstance();

Calendar

Date4j alternative to Date, Calendar, and related Java classes

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

How to add a new row to datagridview programmatically

here is another way to do such

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1.ColumnCount = 3;

        dataGridView1.Columns[0].Name = "Name";
        dataGridView1.Columns[1].Name = "Age";
        dataGridView1.Columns[2].Name = "City";

        dataGridView1.Rows.Add("kathir", "25", "salem");
        dataGridView1.Rows.Add("vino", "24", "attur");
        dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
        dataGridView1.Rows.Add("arun", "27", "chennai"); 
    }

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

Convert JSON String To C# Object

Let's assume you have a class name Student it has following fields and it has a method which will take JSON as a input and return a string Student Object.We can use JavaScriptSerializer here Convert JSON String To C# Object.std is a JSON string here.

  public class Student
{
   public string FirstName {get;set:}
   public string LastName {get;set:}
   public int[] Grades {get;set:}
}

public static Student ConvertToStudent(string std)
{
  var serializer = new JavaScriptSerializer();

  Return serializer.Deserialize<Student>(std);
 }

what is right way to do API call in react js?

This part from React v16 documentation will answer your question, read on about componentDidMount():

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...

How to make a simple modal pop up form using jquery and html?

I have placed here complete bins for above query. you can check demo link too.

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

HTML

<div id="panel">
  <input type="button" class="button" value="1" id="btn1">
  <input type="button" class="button" value="2" id="btn2">
  <input type="button" class="button" value="3" id="btn3">
  <br>
  <input type="text" id="valueFromMyModal">
  <!-- Dialog Box-->
  <div class="dialog" id="myform">
    <form>
      <label id="valueFromMyButton">
      </label>
      <input type="text" id="name">
      <div align="center">
        <input type="button" value="Ok" id="btnOK">
      </div>
    </form>
  </div>
</div>

JQuery

$(function() {
    $(".button").click(function() {
        $("#myform #valueFromMyButton").text($(this).val().trim());
        $("#myform input[type=text]").val('');
        $("#myform").show(500);
    });
    $("#btnOK").click(function() {
        $("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
        $("#myform").hide(400);
    });
});

CSS

.button{
  border:1px solid #333;
  background:#6479fd;
}
.button:hover{
  background:#a4a9fd;
}
.dialog{
  border:5px solid #666;
  padding:10px;
  background:#3A3A3A;
  position:absolute;
  display:none;
}
.dialog label{
  display:inline-block;
  color:#cecece;
}
input[type=text]{
  border:1px solid #333;
  display:inline-block;
  margin:5px;
}
#btnOK{
  border:1px solid #000;
  background:#ff9999;
  margin:5px;
}

#btnOK:hover{
  border:1px solid #000;
  background:#ffacac;
}

Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop

Outline effect to text

Easy! SVG to the rescue.

This is a simplified method:

_x000D_
_x000D_
svg{
  font   : bold 70px Century Gothic, Arial;
  width  : 100%;
  height : 120px;
}

text{
  fill            : none;
  stroke          : black;
  stroke-width    : .5px;
  stroke-linejoin : round;
  animation       : 2s pulsate infinite;
}

@keyframes pulsate {
  50%{ stroke-width:5px }
}
_x000D_
<svg viewBox="0 0 450 50">
  <text y="50">Scalable Title</text>
</svg>
_x000D_
_x000D_
_x000D_

Here's a more complex demo.

How to insert an object in an ArrayList at a specific position

Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:

http://tpcg.io/0KmArS

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list
      arrlist.add(15, 15);
      arrlist.add(22, 22);
      arrlist.add(30, 30);
      arrlist.add(40, 40);

      // adding element 25 at third position
      arrlist.add(2, 25);

      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);
      }  
   }
}

$javac com/tutorialspoint/ArrayListDemo.java

$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0
    at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661)
    at java.util.ArrayList.add(ArrayList.java:473)
    at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)

How to save a plot into a PDF file without a large margin around

What do you mean by "the proper size"? MATLAB figures are like vector graphics, so you can basically choose the size you want on your plot.

You can set the size of the paper and the position of the figure with the function set.

Example:

plot(epx(1:5));
set(gcf, 'PaperPosition', [0 0 5 5]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [5 5]); %Set the paper to have width 5 and height 5.
saveas(gcf, 'test', 'pdf') %Save figure

Enter image description here

The above code will remove most of the borders, but not all. This is because the left-hand corner ([0 0] in the position vector) is not the "true" left-hand corner. To remove more of the borders, you can adjust the PaperPosition and PaperSize vectors.

Example:

plot(exp(1:5))
set(gcf, 'PaperPosition', [-0.5 -0.25 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper.
set(gcf, 'PaperSize', [5 5]); %Keep the same paper size
saveas(gcf, 'test', 'pdf')

Enter image description here

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I agree with above answer. But here is another way of CSS compression.

You can concat your CSS by using YUI compressor:

module.exports = function(grunt) {
  var exec = require('child_process').exec;
   grunt.registerTask('cssmin', function() {
    var cmd = 'java -jar -Xss2048k '
      + __dirname + '/../yuicompressor-2.4.7.jar --type css '
      + grunt.template.process('/css/style.css') + ' -o '
      + grunt.template.process('/css/style.min.css')
    exec(cmd, function(err, stdout, stderr) {
      if(err) throw err;
    });
  });
}; 

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

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

Word count from a txt file program

FILE_NAME = 'file.txt'

wordCounter = {}

with open(FILE_NAME,'r') as fh:
  for line in fh:
    # Replacing punctuation characters. Making the string to lower.
    # The split will spit the line into a list.
    word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
    for word in word_list:
      # Adding  the word into the wordCounter dictionary.
      if word not in wordCounter:
        wordCounter[word] = 1
      else:
        # if the word is already in the dictionary update its count.
        wordCounter[word] = wordCounter[word] + 1

print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)

# printing the words and its occurrence.
for  (word,occurance)  in wordCounter.items(): 
  print('{:15}{:3}'.format(word,occurance))
#
    Word           Count
    ------------------
    of               6
    examples         2
    used             2
    development      2
    modified         2
    open-source      2

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

<form action="" method="POST" enctype="multipart/form-data">
  Select image to upload:
  <input type="file"   name="file[]" multiple/>
  <input type="submit" name="submit" value="Upload Image" />
</form>

Using FOR Loop

<?php    
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    for ($x = 0; $x < count($_FILES['file']['name']); $x++) {               

      $file_name   = $_FILES['file']['name'][$x];
      $file_tmp    = $_FILES['file']['tmp_name'][$x];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }    
?>

Using FOREACH Loop

<?php
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    foreach ($_FILES['file']['name'] as $key => $value) {                   

      $file_name   = $_FILES['file']['name'][$key];
      $file_tmp    = $_FILES['file']['tmp_name'][$key];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }
?>

click or change event on radio using jquery

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.