Programs & Examples On #Multiple makefiles

get everything between <tag> and </tag> with php

You can use the following:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
  • \b ensures that a typo (like <codeS>) is not captured.
  • The first pattern [^>]* captures the content of a tag with attributes (eg a class).
  • Finally, the flag s capture content with newlines.

See the result here : http://lumadis.be/regex/test_regex.php?id=1081

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

How can I update window.location.hash without jumping the document?

I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.

How to fix "set SameSite cookie to none" warning?

If you are experiencing the OP's problem where your cookies have been set using JavaScript - for example:

document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/";

you could instead use:

document.cookie = "my_cookie_name=my_cookie_value; expires=Thu, 11 Jun 2070 11:11:11 UTC; path=/; SameSite=None; Secure";

It worked for me. More info here.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

For me working solution is:

ON REMOTE:

git checkout -b some_tmp_name

ON LOCAL:

git push

ON REMOTE:

git checkout master
git branch -d some_tmp_name

But this is not the real solution it's just workaround.

How can I be notified when an element is added to the page?

The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).

So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)

How do I install cygwin components from the command line?

Usually before installing a package one has to know its exact name:

# define a string to search
export to_srch=perl

# get html output of search and pick only the cygwin package names
wget -qO- "https://cygwin.com/cgi-bin2/package-grep.cgi?grep=$to_srch&arch=x86_64" | \
perl -l -ne 'm!(.*?)<\/a>\s+\-(.*?)\:(.*?)<\/li>!;print $2'

# and install 
# install multiple packages at once, note the
setup-x86_64.exe -q -s http://cygwin.mirror.constant.com -P "<<chosen_package_name>>"

How to break lines in PowerShell?

Try "`n" with double quotes. (not single quotes '`n' )

For a complete list of escaping characters see:

Help about_Escape_character

The code should be

$str += "`n"

How do I see which version of Swift I'm using?

I am using Swift from Google Colab. Here's how to check it in Colab.

!/swift/toolchain/usr/bin/swift --version

The result is 5.0-dev

Entity Framework Core: A second operation started on this context before a previous operation completed

I faced the same issue but the reason was none of the ones listed above. I created a task, created a scope inside the task and asked the container to obtain a service. That worked fine but then I used a second service inside the task and I forgot to also asked for it to the new scope. Because of that, the 2nd service was using a DbContext that was already disposed.

Task task = Task.Run(() =>
    {
        using (var scope = serviceScopeFactory.CreateScope())
        {
            var otherOfferService = scope.ServiceProvider.GetService<IOfferService>();
            // everything was ok here. then I did: 
            productService.DoSomething(); // (from the main scope) and this failed because the db context associated to that service was already disposed.
            ...
        }
    }

I should have done this:

var otherProductService = scope.ServiceProvider.GetService<IProductService>();
otherProductService.DoSomething();

html text input onchange event

I used this line to listen for input events from javascript.
It is useful because it listens for text change and text pasted events.

myElement.addEventListener('input', e => { myEvent() });

How do I get the entity that represents the current user in Symfony2?

Best practice

According to the documentation since Symfony 2.1 simply use this shortcut :

$user = $this->getUser();

The above is still working on Symfony 3.2 and is a shortcut for this :

$user = $this->get('security.token_storage')->getToken()->getUser();

The security.token_storage service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use the getToken() method of the security.context service.

Example : And if you want directly the username :

$username = $this->getUser()->getUsername();

If wrong user class type

The user will be an object and the class of that object will depend on your user provider.

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Correct expression is

"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

how to assign a block of html code to a javascript variable

I recommend to use mustache templating frame work. https://github.com/janl/mustache.js/.

<body>
       ....................
       <!--Put your html variable in a script and set the type to "x-tmpl-mustache"-->
       <script id="template" type="x-tmpl-mustache">
           <div class='saved' >
           <div >test.test</div> <div class='remove'>[Remove]</div></div>
    </script>
</body>

  //You can use it without jquery.
  var template = $('#template').html();
  var rendered = Mustache.render(template);
  $('#target').html(rendered);

Why I recommend this?

Soon or latter you will try to replace some part of the HTML variable and make it dynamic. Dealing with this as an HTML String will be a headache. Here is where Mustache magic can help you.

<script id="template" type="x-tmpl-mustache">
 <div class='remove'>  {{ name }}! </div> ....
</script>

and

 var template = $('#template').html();
 // You can pass dynamic template values
  var rendered = Mustache.render(template, {name: "Luke"});
  $('#target').html(rendered);

There are lot more features.

How to set image in imageview in android?

The images your put into res/drawable are handled by Android. There is no need for you to get the image the way you did. in your case you could simply call iv.setImageRessource(R.drawable.apple)

to just get the image (and not adding it to the ImageView directly), you can call Context.getRessources().getDrawable(R.drawable.apple) to get the image

Angular 2: How to style host element of the component?

I have found a solution how to style just the component element. I have not found any documentation how it works, but you can put attributes values into the component directive, under the 'host' property like this:

@Component({
    ...
    styles: [`
      :host {
        'style': 'display: table; height: 100%',
        'class': 'myClass'
      }`
})
export class MyComponent
{
    constructor() {}

    // Also you can use @HostBinding decorator
    @HostBinding('style.background-color') public color: string = 'lime';
    @HostBinding('class.highlighted') public highlighted: boolean = true;
}

UPDATE: As Günter Zöchbauer mentioned, there was a bug, and now you can style the host element even in css file, like this:

:host{ ... }

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

I fixed this issue. As I'm using UpdatePanel, I added below code in the Page_Load event of the page and it worked for me:

protected void Page_Load(object sender, EventArgs e) {
  ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
  scriptManager.RegisterPostBackControl(this.btnExcelExport);
  //Further code goes here....
}

jwt check if token expired

// Pass in function expiration date to check token 
function checkToken(exp) {
    if (Date.now() <= exp * 1000) {
      console.log(true, 'token is not expired')
    } else { 
      console.log(false, 'token is expired') 
    }
  }

jQuery Validation plugin: disable validation for specified submit buttons

You can add a CSS class of cancel to a submit button to suppress the validation

e.g

<input class="cancel" type="submit" value="Save" />

See the jQuery Validator documentation of this feature here: Skipping validation on submit


EDIT:

The above technique has been deprecated and replaced with the formnovalidate attribute.

<input formnovalidate="formnovalidate" type="submit" value="Save" />

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

How do I add a new column to a Spark DataFrame (using PySpark)?

You can define a new udf when adding a column_name:

u_f = F.udf(lambda :yourstring,StringType())
a.select(u_f().alias('column_name')

"Specified argument was out of the range of valid values"

try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

How do you find what version of libstdc++ library is installed on your linux machine?

To find which library is being used you could run

 $ /sbin/ldconfig -p | grep stdc++
    libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6

The list of compatible versions for libstdc++ version 3.4.0 and above is provided by

 $ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
 GLIBCXX_3.4
 GLIBCXX_3.4.1
 GLIBCXX_3.4.2
 ...

For earlier versions the symbol GLIBCPP is defined.

The date stamp of the library is defined in a macro __GLIBCXX__ or __GLIBCPP__ depending on the version:

// libdatestamp.cxx
#include <cstdio>

int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
    std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
    std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
   return 0;
}

$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208

The table of datestamps of libstdc++ versions is listed in the documentation:

Difference Between Select and SelectMany

Just for an alternate view that may help some functional programmers out there:

  • Select is map
  • SelectMany is bind (or flatMap for your Scala/Kotlin people)

How to deploy a Java Web Application (.war) on tomcat?

  • copy the .war file in the webapps folder
  • upload the file using the manager application - http://host:port/manager. You will have to setup some users beforehand.
  • (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in webapps/webappname

Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:

After you have it deployed (check the /logs dir for any problems), it should be accessible via: http://host:port/yourwebappname/. So in your case, one of those:

http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/

If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)

Best way to get whole number part of a Decimal number

You just need to cast it, as such:

int intPart = (int)343564564.4342

If you still want to use it as a decimal in later calculations, then Math.Truncate (or possibly Math.Floor if you want a certain behaviour for negative numbers) is the function you want.

Media Player called in state 0, error (-38,0)

enter image description here

above the picture,you can get the right way.

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

What permission do I need to access Internet from an Android application?

Just Add these 2 permissions

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

in your app's AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.android.networkusage"
        ...>
    
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application 
            ...>
            ...
        </application>
    </manifest>

Happy Coding:)

Add tooltip to font awesome icon

Simply use title in tag like

<i class="fa fa-edit" title="Edit Mode"></i>

This will show 'Edit Mode' when hover that icon.

When do you use varargs in Java?

I have a varargs-related fear, too:

If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.

If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.

 Object[] args = new Object[] { 1, 2, 3} ;

 varArgMethod(args);  // not varArgMethod(1,2,3);

 args[2] = "something else";  // this could have unexpected side-effects

While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.

Find the min/max element of an array in JavaScript

Using spread operator (ES6)

Math.max(...array);  // the same with "min" => Math.min(...array);

_x000D_
_x000D_
const array = [10, 2, 33, 4, 5];_x000D_
_x000D_
console.log(_x000D_
  Math.max(...array)_x000D_
)
_x000D_
_x000D_
_x000D_

How do I declare and initialize an array in Java?

There are a lot of answers here. I am adding a few tricky ways to create arrays (from an exam point of view it's good to know this)

  1. Declare and define an array

    int intArray[] = new int[3];
    

    This will create an array of length 3. As it holds a primitive type, int, all values are set to 0 by default. For example,

    intArray[2]; // Will return 0
    
  2. Using box brackets [] before the variable name

    int[] intArray = new int[3];
    intArray[0] = 1;  // Array content is now {1, 0, 0}
    
  3. Initialise and provide data to the array

    int[] intArray = new int[]{1, 2, 3};
    

    This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:

    int[] intArray = {1, 2, 3, 4};
    
  4. An array of length 0

    int[] intArray = new int[0];
    int length = intArray.length; // Will return length 0
    

    Similar for multi-dimensional arrays

    int intArray[][] = new int[2][3];
    // This will create an array of length 2 and
    //each element contains another array of length 3.
    // { {0,0,0},{0,0,0} }
    int lenght1 = intArray.length; // Will return 2
    int length2 = intArray[0].length; // Will return 3
    

Using box brackets before the variable:

    int[][] intArray = new int[2][3];

It's absolutely fine if you put one box bracket at the end:

    int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]

Some examples

    int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
    int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
    int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
    // All the 3 arrays assignments are valid
    // Array looks like {{1,2,3},{4,5,6}}

It's not mandatory that each inner element is of the same size.

    int [][] intArray = new int[2][];
    intArray[0] = {1,2,3};
    intArray[1] = {4,5};
    //array looks like {{1,2,3},{4,5}}

    int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.

You have to make sure if you are using the above syntax, that the forward direction you have to specify the values in box brackets. Else it won't compile. Some examples:

    int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3];

Another important feature is covariant

    Number[] numArray = {1,2,3,4};   // java.lang.Number
    numArray[0] = new Float(1.5f);   // java.lang.Float
    numArray[1] = new Integer(1);    // java.lang.Integer
   // You can store a subclass object in an array that is declared
   // to be of the type of its superclass.
   // Here 'Number' is the superclass for both Float and Integer.

   Number num[] = new Float[5]; // This is also valid

IMPORTANT: For referenced types, the default value stored in the array is null.

Is there a good Valgrind substitute for Windows?

Why not use Valgrind + Wine to debug your Windows app? See http://wiki.winehq.org/Wine_and_Valgrind

(Chromium uses this to check the Windows version for memory errors; see build.chromium.org and look at the experimental or memory waterfalls, and search for wine.)

There's also Dr. Memory, see dynamorio.org/drmemory.html

How can I recursively find all files in current and subfolders based on wildcard matching?

You can use:

# find . -type f  -name 'text_for_search'

If you want use REGX use -iname

# find . -type f  -iname 'text_for_search'

jQuery scroll to ID from different page

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

cURL equivalent in Node.js?

well if you really need a curl equivalent you can try node-curl

npm install node-curl

you will probably need to add libcurl4-gnutls-dev.

psql: FATAL: Peer authentication failed for user "dev"

Your connection failed because by default psql connects over UNIX sockets using peer authentication, that requires the current UNIX user to have the same user name as psql. So you will have to create the UNIX user dev and then login as dev or use sudo -u dev psql test_development for accessing the database (and psql should not ask for a password).

If you cannot or do not want to create the UNIX user, like if you just want to connect to your database for ad hoc queries, forcing a socket connection using psql --host=localhost --dbname=test_development --username=dev (as pointed out by @meyerson answer) will solve your immediate problem.

But if you intend to force password authentication over Unix sockets instead of the peer method, try changing the following pg_hba.conf* line:

from

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          peer

to

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          md5
  • peer means it will trust the identity (authenticity) of UNIX user. So not asking for a password.

  • md5 means it will always ask for a password, and validate it after hashing with MD5.

You can, of course, also create more specific rules for a specific database or user, with some users having peer and others requiring passwords.

After changing pg_hba.conf if PostgreSQL is running you'll need to make it re-read the configuration by reloading (pg_ctl reload) or restarting (sudo service postgresql restart).

* The file pg_hba.conf will most likely be at /etc/postgresql/9.x/main/pg_hba.conf

Edited: Remarks from @Chloe, @JavierEH, @Jonas Eicher, @fccoelho, @Joanis, @Uphill_What comments incorporated into answer.

How to check if object has been disposed in C#

The reliable solution is catching the ObjectDisposedException.

The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.

Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.

How to print a groupby object

I found a tricky way, just for brainstorm, see the code:

df['a'] = df['A']  # create a shadow column for MultiIndexing
df.sort_values('A', inplace=True)
df.set_index(["A","a"], inplace=True)
print(df)

the output:

             B
A     a
one   one    0
      one    1
      one    5
three three  3
      three  4
two   two    2

The pros is so easy to print, as it returns a dataframe, instead of Groupby Object. And the output looks nice. While the con is that it create a series of redundant data.

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

Angular2 disable button

Update

I'm wondering. Why don't you want to use the [disabled] attribute binding provided by Angular 2? It's the correct way to dealt with this situation. I propose you move your isValid check via component method.

<button [disabled]="! isValid" (click)="onConfirm()">Confirm</button>

The Problem with what you tried explained below

Basically you could use ngClass here. But adding class wouldn't restrict event from firing. For firing up event on valid input, you should change click event code to below. So that onConfirm will get fired only when field is valid.

<button [ngClass]="{disabled : !isValid}" (click)="isValid && onConfirm()">Confirm</button>

Demo Here

How to pass a textbox value from view to a controller in MVC 4?

Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter

@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton

How to display two digits after decimal point in SQL Server

You can also use below code which helps me:

select convert(numeric(10,2), column_name) as Total from TABLE_NAME

where Total is alias of the field you want.

C# error: Use of unassigned local variable

The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue to null when you declare it.

Queue queue = null;

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

All of the answers in this question helped me but I thought I'd add some additional information for posterity.

It turned out that I had a test dependency on gwt-test-utils which brought in the gwt-dev package. Unfortunately gwt-dev contains a full copy of Jetty, JSP, JSTL, etc. which was ahead of the proper packages on the classpath. So even though I had proper dependencies on the JSTL 1.2 it would loading the 1.0 version internal to gwt-dev. Grumble.

The solution for me was to not run with test scope so I don't pick up the gwt-test-utils package at runtime. Removing the gwt-dev package from the classpath in some other manner would also have fixed the problem.

How to get the children of the $(this) selector?

If your DIV tag is immediately followed by the IMG tag, you can also use:

$(this).next();

Adding 30 minutes to time formatted as H:i in PHP

$time = strtotime('10:00');
$startTime = date("H:i", strtotime('-30 minutes', $time));
$endTime = date("H:i", strtotime('+30 minutes', $time));

How can I use an array of function pointers?

This simple example for multidimensional array with function pointers":

void one( int a, int b){    printf(" \n[ ONE ]  a =  %d   b = %d",a,b);}
void two( int a, int b){    printf(" \n[ TWO ]  a =  %d   b = %d",a,b);}
void three( int a, int b){    printf("\n [ THREE ]  a =  %d   b = %d",a,b);}
void four( int a, int b){    printf(" \n[ FOUR ]  a =  %d   b = %d",a,b);}
void five( int a, int b){    printf(" \n [ FIVE ]  a =  %d   b = %d",a,b);}
void(*p[2][2])(int,int)   ;
int main()
{
    int i,j;
    printf("multidimensional array with function pointers\n");

    p[0][0] = one;    p[0][1] = two;    p[1][0] = three;    p[1][1] = four;
    for (  i  = 1 ; i >=0; i--)
        for (  j  = 0 ; j <2; j++)
            (*p[i][j])( (i, i*j);
    return 0;
}

Java List.add() UnsupportedOperationException

instead of using add() we can use addall()

{ seeAlso.addall(groupDn); }

add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Resource leak: 'in' is never closed

Generally, instances of classes that deal with I/O should be closed after you're finished with them. So at the end of your code you could add in.close().

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

How can I exclude directories from grep -R?

Frequently use this:

grep can be used in conjunction with -r (recursive), i (ignore case) and -o (prints only matching part of lines). To exclude files use --exclude and to exclude directories use --exclude-dir.

Putting it together you end up with something like:

grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>

Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.

Example:

Suppose I am searching for current project for all places where I explicitly set the string value debugger during a debugging session, and now wish to review / remove.

I write a script called findDebugger.sh and use grep to find all occurrences. However:

For file exclusions - I wish to ensure that .eslintrc is ignored (this actually has a linting rule about debugger so should be excluded). Likewise, I don't want my own script to be referenced in any results.

For directory exclusions - I wish to exclude node_modules as it contains lots of libraries that do reference debugger and I am not interested in those results. Also I just wish to omit .idea and .git hidden directories because I don't care about those search locations either, and wish to keep the search performant.

So here is the result - I create a script called findDebugger.sh with:

#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .

Detect encoding and make everything UTF-8

I had same issue with phpQuery (ISO-8859-1 instead of UTF-8) and this hack helped me:

$html = '<?xml version="1.0" encoding="UTF-8" ?>' . $html;

mb_internal_encoding('UTF-8'), phpQuery::newDocumentHTML($html, 'utf-8'), mbstring.internal_encoding and other manipulations didn't take any effect.

Changing the image source using jQuery

You should add id attribute to your image tag, like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

How to call a method in MainActivity from another class?

Initialize it first

MainActivity mActivity= new MainActivity();

Then you can continue

mActivity.startChronometer();

Debugging "Element is not clickable at point" error

I have seen this in the situation when the selenium driven Chrome window was opened too small. The element to be clicked on was out of the viewport and therefore it was failing.

That sounds logical... real user would have to either resize the window or scroll so that it is possible to see the element and in fact click on it.

After instructing the selenium driver to set the window size appropriately this issues went away for me. The webdriver API is decribed here.

What are the differences between numpy arrays and matrices? Which one should I use?

As others have mentioned, perhaps the main advantage of matrix was that it provided a convenient notation for matrix multiplication.

However, in Python 3.5 there is finally a dedicated infix operator for matrix multiplication: @.

With recent NumPy versions, it can be used with ndarrays:

A = numpy.ones((1, 3))
B = numpy.ones((3, 3))
A @ B

So nowadays, even more, when in doubt, you should stick to ndarray.

How to get the number of days of difference between two dates on mysql?

Note if you want to count FULL 24h days between 2 dates, datediff can return wrong values for you.

As documentation states:

Only the date parts of the values are used in the calculation.

which results in

select datediff('2016-04-14 11:59:00', '2016-04-13 12:00:00')

returns 1 instead of expected 0.

Solution is using select timestampdiff(DAY, '2016-04-13 11:00:01', '2016-04-14 11:00:00'); (note the opposite order of arguments compared to datediff).

Some examples:

  • select timestampdiff(DAY, '2016-04-13 11:00:01', '2016-04-14 11:00:00'); returns 0
  • select timestampdiff(DAY, '2016-04-13 11:00:00', '2016-04-14 11:00:00'); returns 1
  • select timestampdiff(DAY, '2016-04-13 11:00:00', now()); returns how many full 24h days has passed since 2016-04-13 11:00:00 until now.

Hope it will help someone, because at first it isn't much obvious why datediff returns values which seems to be unexpected or wrong.

How to connect to SQL Server database from JavaScript in the browser?

Playing with JavaScript in an HTA I had no luck with a driver={SQL Server};... connection string, but a named DSN was OK :
I set up TestDSN and it tested OK, and then var strConn= "DSN=TestDSN"; worked, so I carried on experimenting for my in-house testing and learning purposes.

Our server has several instances running, e.g. server1\dev and server1\Test which made things slightly more tricky as I managed to waste some time forgetting to escape the \ as \\ :)
After some dead-ends with server=server1;instanceName=dev in the connection strings, I eventually got this one to work :
var strConn= "Provider=SQLOLEDB;Data Source=server1\\dev;Trusted_Connection=Yes;Initial Catalog=MyDatabase;"

Using Windows credentials rather than supplying a user/pwd, I found an interesting diversion was discovering the subtleties of Integrated Security = true v Integrated Security = SSPI v Trusted_Connection=Yes - see Difference between Integrated Security = True and Integrated Security = SSPI

Beware that RecordCount will come back as -1 if using the default adOpenForwardOnly type. If you're working with small result sets and/or don't mind the whole lot in memory at once, use rs.Open(strQuery, objConnection, 3); (3=adOpenStatic) and this gives a valid rs.RecordCount

Show/Hide the console window of a C# console application

If you don't have a problem integrating a small batch application, there is this program called Cmdow.exe that will allow you to hide console windows based on console title.

Console.Title = "MyConsole";
System.Diagnostics.Process HideConsole = new System.Diagnostics.Process();
HideConsole.StartInfo.UseShellExecute = false;
HideConsole.StartInfo.Arguments = "MyConsole /hid";
HideConsole.StartInfo.FileName = "cmdow.exe";
HideConsole.Start();

Add the exe to the solution, set the build action to "Content", set Copy to Output Directory to what suits you, and cmdow will hide the console window when it is ran.

To make the console visible again, you just change the Arguments

HideConsole.StartInfo.Arguments = "MyConsole /Vis";

How to start/stop/restart a thread in Java?

You can't restart a thread so your best option is to save the current state of the object at the time the thread was stopped and when operations need to continue on that object you can recreate that object using the saved and then start the new thread.

These two articles Swing Worker and Concurrency may help you determine the best solution for your problem.

How to compile and run C files from within Notepad++ using NppExec plugin?

I've made a single powerfull script that will:

-Compile and run multi language code like C, C++, Java, Python and C#.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.

I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.

npp_console 1               //open console
NPP_CONSOLE -               //disable output of commands
npe_console m-              //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5    //set console colors
npp_save                //save the file
cd $(CURRENT_DIRECTORY)         //follow current directory
NPP_CONSOLE +               //enable output
IF $(EXT_PART)==.c GOTO C       //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP       //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA     //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C#     //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON     //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT             // else treat it as a text file and goto EXITSCRIPT
//C label
:C                                                                  
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART)              //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT             //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY:              //print message on console
$(NAME_PART)                                            //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT                         //finally exits

:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT

:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD:              //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT

:EXITSCRIPT
// that's all, folks!

PDO mysql: How to know if insert was successful

If an update query executes with values that match the current database record then $stmt->rowCount() will return 0 for no rows were affected. If you have an if( rowCount() == 1 ) to test for success you will think the updated failed when it did not fail but the values were already in the database so nothing change.

$stmt->execute();
if( $stmt ) return "success";

This did not work for me when I tried to update a record with a unique key field that was violated. The query returned success but another query returns the old field value.

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

Simple export and import of a SQLite database on Android

This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a

    public class ExportImportDB extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
            File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");

               if(!direct.exists())
                {
                    if(direct.mkdir()) 
                      {
                       //directory is created;
                      }

                }
            exportDB();
            importDB();

        }
    //importing database
        private void importDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data  = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File  backupDB= new File(data, currentDBPath);
                    File currentDB  = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }
    //exporting database 
        private void exportDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

Dont forget to add this permission to proceed it

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

Enjoy

Change color of PNG image via CSS?

When changing a picture from black to white, or white to black the hue rotate filter does not work, because black and white are not technically colors. Instead, black and white color changes (from black to white or vice-versa) must be done with the invert filter property.

.img1 { filter: invert(100%); }

Create thumbnail image

The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height)
{
    Bitmap srcBmp = new Bitmap(path);
    float ratio = srcBmp.Width / srcBmp.Height;
    SizeF newSize = new SizeF(width, height * ratio);
    Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "image/jpeg";
    using (Graphics graphics = Graphics.FromImage(target))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);
        using (MemoryStream memoryStream = new MemoryStream()) 
        {
            target.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.WriteTo(HttpContext.Response.OutputStream);
        }
    }
    Response.End();
}

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

libxml/tree.h no such file or directory

Don't put libxml2.dylib under frameworks folder put it under root just below the root(Top left blue icon )

Then Click on the Project (TOP Left blue icon) ,GO to Build Settings,in the search box type "Header Search Paths" and then add the this "$(SDKROOT)/usr/include/libxml2"

This code resolve my issue hope it will help you fix this

How to get main window handle from process id?

Old question but appears to have a lot of traffic, here is a simple solution:

IntPtr GetMainWindowHandle(IntPtr aHandle) {
        return System.Diagnostics.Process.GetProcessById(aHandle.ToInt32()).MainWindowHandle;
}

go get results in 'terminal prompts disabled' error for github private repo

I had the same problem on windows "error: failed to execute prompt script (exit code 1) fatal: could not read Username for 'https://github.com': No error" trying to login to github through the login dialog. When I canceled the dialog git asked me for login and password in the command line and it worked fine.

Javascript How to define multiple variables on a single line?

Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:

_x000D_
_x000D_
let [a, b, c, d] = Array(4).fill(0);_x000D_
_x000D_
console.log(a, b, c, d);
_x000D_
_x000D_
_x000D_

How do you input command line arguments in IntelliJ IDEA?

There's an "edit configurations" item on the Run menu, and on the pull-down to the left of the two green "run" and "debug" arrows on the toolbar. In that panel, you create a configuration with the "+" button in the top left, and then you can choose the Class containing main(), add VM parameters and command-line args, specify the working directory and any environment variables.

There are other options there as well: code coverage, logging, build, JRE, etc.

What is the best data type to use for money in C#?

Agree with the Money pattern: Handling currencies is just too cumbersome when you use decimals.

If you create a Currency-class, you can then put all the logic relating to money there, including a correct ToString()-method, more control of parsing values and better control of divisions.

Also, with a Currency class, there is no chance of unintentionally mixing money up with other data.

How to insert a newline in front of a pattern?

echo pattern | sed -E -e $'s/^(pattern)/\\\n\\1/'

worked fine on El Captitan with () support

Pretty-print an entire Pandas Series / DataFrame

Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().

display(dataframe)

display() supports proper alignment also.

However if you want to make the dataset more beautiful you can check pd.option_context(). It has lot of options to clearly show the dataframe.

Note - I am using Jupyter Notebooks.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

SDK represents to software development kit, and IDE represents to integrated development environment. The IDE is the software or the program is used to write, compile, run, and debug such as Xcode. The SDK is the underlying engine of the IDE, includes all the platform's libraries an app needs to access. It's more basic than an IDE because it doesn't usually have graphical tools.

bypass invalid SSL certificate in .net core

Came here looking for an answer to the same problem, but I'm using WCF for NET Core. If you're in the same boat, use:

client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = 
    new X509ServiceCertificateAuthentication()
    {
        CertificateValidationMode = X509CertificateValidationMode.None,
        RevocationMode = X509RevocationMode.NoCheck
    };

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Chrome print is usually an extension page so there is no dom attachment happening in your existing page. You can trigger the print command using command line apis(window.print()) but then they have not provided apis for closing it becoz of vary reason like choosing print options, print machine,count etc.

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

If you don't have to support IE, you can use selectionStart and selectionEnd attributes of textarea.

To get caret position just use selectionStart:

function getCaretPosition(textarea) {
  return textarea.selectionStart
}

To get the strings surrounding the selection, use following code:

function getSurroundingSelection(textarea) {
  return [textarea.value.substring(0, textarea.selectionStart)
         ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
         ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}

Demo on JSFiddle.

See also HTMLTextAreaElement docs.

How to use multiple LEFT JOINs in SQL?

You have two choices, depending on your table order

create table aa (sht int)
create table cc (sht int)
create table cd (sht int)
create table ab (sht int)

-- type 1    
select * from cd
inner join cc on cd.sht = cc.sht
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cc.sht

-- type 2
select * from cc
inner join cc on cd.sht = cc.sht
LEFT JOIN ab
LEFT JOIN aa
ON aa.sht = ab.sht
ON ab.sht = cd.sht

Force browser to refresh css, javascript, etc

I have a case, where I need to be able to create and change my stylesheets remotely affecting thousands of clients, but due to risk of heavy network load, I'm not turning off cache.

Since I can change the HTML contents remotely, I then link the stylesheet with a hashcode matching the contents of the stylesheet.

https://example.com/contents/stylesheetctrl?id=12345&hash=-1456405808

That said, I also use a client-side javascript function to carefully replace nodes and attributes when HTML contents change, meaning the stylesheet link tag will not be replaced, only the href attribute will change.

This scenario works fine in Chrome, Firefox and Edge on Windows, also Chrome on Android, but doesn't always work in webclients on Android to my surprise. So I'm more or less looking for something to force/trigger the update using javascript - optimally without needing to reload the page.

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

How to get the next auto-increment id in mysql

For me it works, and looks simple:

 $auto_inc_db = mysql_query("SELECT * FROM my_table_name  ORDER BY  id  ASC ");
 while($auto_inc_result = mysql_fetch_array($auto_inc_db))
 {
 $last_id = $auto_inc_result['id'];
 }
 $next_id = ($last_id+1);


 echo $next_id;//this is the new id, if auto increment is on

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

To direct to the point , you can easily use xapth .The exact and simple way to do this using the below code . Kindly try and provide feedback .Thank you .

JavascriptExecutor js = (JavascriptExecutor) driver;

    //To click an element 
    WebElement element=driver.findElement(By.xpath(Xpath));
    js.executeScript(("arguments[0].click();", element);

    //To gettext

    String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));

Further readings - https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f

Set selected item in Android BottomNavigationView

IF YOU NEED TO DYNAMICALLY PASS FRAGMENT ARGUMENTS DO THIS

There are plenty of (mostly repeated or outdated) answers here but none of them handles a very common need: dynamically passing different arguments to the Fragment loaded into a tab.

You can't dynamically pass different arguments to the loaded Fragment by using setSelectedItemId(R.id.second_tab), which ends up calling the static OnNavigationItemSelectedListener. To overcome this limitation I've ended up doing this in my MainActivity that contains the tabs:

fun loadArticleTab(articleId: String) {
    bottomNavigationView.menu.findItem(R.id.tab_article).isChecked = true // use setChecked() in Java
    supportFragmentManager
        .beginTransaction()
        .replace(R.id.main_fragment_container, ArticleFragment.newInstance(articleId))
        .commit()
}

The ArticleFragment.newInstance() method is implemented as usual:

private const val ARG_ARTICLE_ID = "ARG_ARTICLE_ID"

class ArticleFragment : Fragment() {

    companion object {
        /**
         * @return An [ArticleFragment] that shows the article with the given ID.
         */
        fun newInstance(articleId: String): ArticleFragment {
            val args = Bundle()
            args.putString(ARG_ARTICLE_ID, day)
            val fragment = ArticleFragment()
            fragment.arguments = args
            return fragment
        }
    }

}

jQuery UI Slider (setting programmatically)

Mal's answer was the only one that worked for me (maybe jqueryUI has changed), here is a variant for dealing with a range:

$( "#slider-range" ).slider('values',0,lowerValue);
$( "#slider-range" ).slider('values',1,upperValue);
$( "#slider-range" ).slider("refresh");

What's the reason I can't create generic array types in Java?

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

Android map v2 zoom to show all the markers

I couldnt use the onGlobalLayoutlistener, so here is another solution to prevent the "Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions." error:

mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { 
@Override 
public void onMapLoaded() { 
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 15));
 } 
});

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

UIImage: Resize, then Crop

I found that the Swift 3 posted by Evgenii Kanvets does not uniformly scale the image.

Here is my Swift 4 version of the function that does not squish the image:

static func resizedCroppedImage(image: UIImage, newSize:CGSize) -> UIImage? {

    // This function returns a newImage, based on image
    // - image is scaled uniformaly to fit into a rect of size newSize
    // - if the newSize rect is of a different aspect ratio from the source image
    //     the new image is cropped to be in the center of the source image
    //     (the excess source image is removed)

    var ratio: CGFloat = 0
    var delta: CGFloat = 0
    var drawRect = CGRect()

    if newSize.width > newSize.height {

        ratio = newSize.width / image.size.width
        delta = (ratio * image.size.height) - newSize.height
        drawRect = CGRect(x: 0, y: -delta / 2, width: newSize.width, height: newSize.height + delta)

    } else {

        ratio = newSize.height / image.size.height
        delta = (ratio * image.size.width) - newSize.width
        drawRect = CGRect(x: -delta / 2, y: 0, width: newSize.width + delta, height: newSize.height)

    }

    UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
    image.draw(in: drawRect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
} 

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library: https://lokesh-coder.github.io/pretty-checkbox/

Thanks

Scanner is skipping nextLine() after using next() or nextFoo()?

The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

LINQ Contains Case Insensitive

StringComparison.InvariantCultureIgnoreCase just do the job for me:

.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));

Hibernate: best practice to pull all lazy collections

It's probably not anywhere approaching a best practice, but I usually call a SIZE on the collection to load the children in the same transaction, like you have suggested. It's clean, immune to any changes in the structure of the child elements, and yields SQL with low overhead.

What is the most appropriate way to store user settings in Android application

I use the Android KeyStore to encrypt the password using RSA in ECB mode and then save it in the SharedPreferences.

When I want the password back I read the encrypted one from the SharedPreferences and decrypt it using the KeyStore.

With this method you generate a public/private Key-pair where the private one is safely stored and managed by Android.

Here is a link on how to do this: Android KeyStore Tutorial

Where can I find the API KEY for Firebase Cloud Messaging?

Enter here:

https: //console.firebase.google.com/project/your-project-name/overview

(replace your-project with your project-name) and click in "Add firebase in your web app"(the red circle icon) this action show you a dialog with:

  • apiKey
  • authDomain
  • databaseURL
  • storageBucket
  • messagingSenderId

Use the auto keyword in C++ STL

The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization.

Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int>s;
    s.push_back(11);
    s.push_back(22);
    s.push_back(33);
    s.push_back(55);
    for (int it=s.begin();it!=s.end();it++){
        cout<<*it<<endl;
    }
}

Line 12: error: cannot convert '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >' to 'int' in initialization

The auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

What does "publicPath" in Webpack do?

filename specifies the name of file into which all your bundled code is going to get accumulated after going through build step.

path specifies the output directory where the app.js(filename) is going to get saved in the disk. If there is no output directory, webpack is going to create that directory for you. for example:

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js"
  } 
}

This will create a directory myproject/examples/dist and under that directory it creates app.js, /myproject/examples/dist/app.js. After building, you can browse to myproject/examples/dist/app.js to see the bundled code

publicPath: "What should I put here?"

publicPath specifies the virtual directory in web server from where bundled file, app.js is going to get served up from. Keep in mind, the word server when using publicPath can be either webpack-dev-server or express server or other server that you can use with webpack.

for example

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js",
    publicPath: path.resolve("/public/assets/js")   
  } 
}

this configuration tells webpack to bundle all your js files into examples/dist/app.js and write into that file.

publicPath tells webpack-dev-server or express server to serve this bundled file ie examples/dist/app.js from specified virtual location in server ie /public/assets/js. So in your html file, you have to reference this file as

<script src="public/assets/js/app.js"></script>

So in summary, publicPath is like mapping between virtual directory in your server and output directory specified by output.path configuration, Whenever request for file public/assets/js/app.js comes, /examples/dist/app.js file will be served

Can we overload the main method in Java?

Yes, you can.

The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.

  • The normal main method acts as an entry point for the JVM to start the execution of program.

  • We can overload the main method in Java. But the program doesn’t
    execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only.

    // A Java program with overloaded main()
    import java.io.*;     
    public class Test {         
      // Normal main()
      public static void main(String[] args) {
        System.out.println("Hi Geek (from main)");
        Test.main("Geek");
      }     
      // Overloaded main methods
      public static void main(String arg1) {
        System.out.println("Hi, " + arg1);
        Test.main("Dear Geek","My Geek");
      }
      public static void main(String arg1, String arg2) {
        System.out.println("Hi, " + arg1 + ", " + arg2);
      }
    }
    

    Valid variants of main() in Java

Automatically scroll down chat div

Let's review a few useful concepts about scrolling first:

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don't want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;
}

Full chat simulator (with JavaScript):

https://jsfiddle.net/apvtL9xa/

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3

After some modifications in my Web.config CORS suddenly stopped working in my Web API 2 project (at least for OPTIONS request during the preflight). It seems that you need to have the section mentioned below in your Web.config or otherwise the (global) EnableCorsAttribute will not work on OPTIONS requests. Note that this is the exact same section Visual Studio will add in a new Web API 2 project.

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
  </handlers>
</system.webServer>

jQuery - simple input validation - "empty" and "not empty"

    jQuery("#input").live('change', function() {
        // since we check more than once against the value, place it in a var.
        var inputvalue = $("#input").attr("value");

        // if it's value **IS NOT** ""
        if(inputvalue !== "") {
            jQuery(this).css('outline', 'solid 1px red'); 
        }   

        // else if it's value **IS** ""
        else if(inputvalue === "") {
            alert('empty'); 
        }

    });

How to use regex in file find

find /home/test -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip' -mtime +3
  1. -name uses globular expressions, aka wildcards. What you want is -regex
  2. To use intervals as you intend, you need to tell find to use Extended Regular Expressions via the -regextype posix-extended flag
  3. You need to escape out the periods because in regex a period has the special meaning of any single character. What you want is a literal period denoted by \.
  4. To match only those files that are greater than 3 days old, you need to prefix your number with a + as in -mtime +3.

Proof of Concept

$ find . -regextype posix-extended -regex '^.*test\.log\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.zip'
./test.log.1234-12-12.zip

Commit history on remote repository

I don't believe this is possible. I believe you have to clone that remote repo locally and perform git fetch on it before you can issue a git log against it.

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

Check if list is empty in C#

var dataSource = lst!=null && lst.Any() ? lst : null;
// bind dataSource to gird source

How to use the read command in Bash?

I really only use read with "while" and a do loop:

echo "This is NOT a test." | while read -r a b c theRest; do  
echo "$a" "$b" "$theRest"; done  

This is a test.
For what it's worth, I have seen the recommendation to always use -r with the read command in bash.

Get current category ID of the active page

$cats = wp_get_post_terms( $post->ID, 'product_cat' );
foreach($cats as $cat){
/*check for category having parent or not except category id=1 which is wordpress default category (Uncategorized)*/
  if($cat->parent != '0' && $cat->term_id != 1){
    echo '<h2 class="link"><a href="'.get_category_link($cat->term_id ).'">'.$cat->name.'</a></h2>';
    break;
  }
}

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

How to echo shell commands as they are executed

You can execute a Bash script in debug mode with the -x option.

This will echo all the commands.

bash -x example_script.sh

# Console output
+ cd /home/user
+ mv text.txt mytext.txt

You can also save the -x option in the script. Just specify the -x option in the shebang.

######## example_script.sh ###################
#!/bin/bash -x

cd /home/user
mv text.txt mytext.txt

##############################################

./example_script.sh

# Console output
+ cd /home/user
+ mv text.txt mytext.txt

how to make a specific text on TextView BOLD

wtsang02 answer is the best way to go about it, since, Html.fromHtml("") is now deprecated. Here I'm just going to enhance it a little bit for whoever is having problem in dynamically making the first word bold, no matter whats the size of the sentence.

First lets create a method to get the first word:

 private String getFirstWord(String input){

    for(int i = 0; i < input.length(); i++){

        if(input.charAt(i) == ' '){

            return input.substring(0, i);
        }
    }

    return input;
}

Now let's say you have a long string like this:

String sentence = "[email protected] want's to be your friend!"

And you want your sentence to be like [email protected] want's to be your friend! All you have to do is- get the firstWord and get the lenght of it to make the firstWord bold, something like this:

String myFirstWord = getFirstWord(sentence);
int start = 0; // bold will start at index 0
int end = myFirstWord.length(); // and will finish at whatever the length of your first word

Now just follow wtsang02 's steps, like this:

SpannableStringBuilder fancySentence = new SpannableStringBuilder(sentence);
fancySentence.setSpan(new android.text.style.StyleSpan(Typeface.BOLD), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(fancySentence);

And that's it! Now you should be able to bold a word with any size from long/short sentence. Hope it will help someone, happy coding :)

Purge or recreate a Ruby on Rails database

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

How to apply filters to *ngFor?

Here's an example that I created a while back, and blogged about, that includes a working plunk. It provides a filter pipe that can filter any list of objects. You basically just specify the property and value {key:value} within your ngFor specification.

It's not a lot different from @NateMay's response, except that I explain it in relatively verbose detail.

In my case, I filtered an unordered list on some text (filterText) the user entered against the "label" property of the objects in my array with this sort of mark-up:

<ul>
  <li *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
</ul>

https://long2know.com/2016/11/angular2-filter-pipes/

Conversion of System.Array to List

I hope this is helpful.

enum TESTENUM
    {
        T1 = 0,
        T2 = 1,
        T3 = 2,
        T4 = 3
    }

get string value

string enumValueString = "T1";

        List<string> stringValueList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m => 
            Convert.ToString(m)
            ).ToList();

        if(!stringValueList.Exists(m => m == enumValueString))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertString;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);

get integer value

        int enumValueInt = 1;

        List<int> enumValueIntList =  typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
            Convert.ToInt32(m)
            ).ToList();

        if(!enumValueIntList.Exists(m => m == enumValueInt))
        {
            throw new Exception("cannot find type");
        }

        TESTENUM testEnumValueConvertInt;
        Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);

What is N-Tier architecture?

N-tier data applications are data applications that are separated into multiple tiers. Also called "distributed applications" and "multitier applications," n-tier applications separate processing into discrete tiers that are distributed between the client and the server. When you develop applications that access data, you should have a clear separation between the various tiers that make up the application.

A typical n-tier application includes a presentation tier, a middle tier, and a data tier. The easiest way to separate the various tiers in an n-tier application is to create discrete projects for each tier that you want to include in your application. For example, the presentation tier might be a Windows Forms application, whereas the data access logic might be a class library located in the middle tier. Additionally, the presentation layer might communicate with the data access logic in the middle tier through a service such as a service. Separating application components into separate tiers increases the maintainability and scalability of the application. It does this by enabling easier adoption of new technologies that can be applied to a single tier without the requirement to redesign the whole solution. In addition, n-tier applications typically store sensitive information in the middle-tier, which maintains isolation from the presentation tier.

Taken from Microsoft website.

Not able to start Genymotion device

This worked for me..

Open Virtual Box and select your mobile VM. Right click->Settings

Change Promiscuous mode to Allow VMS and click ok

Last Run Date on a Stored Procedure in SQL Server

In a nutshell, no.

However, there are "nice" things you can do.

  1. Run a profiler trace with, say, the stored proc name
  2. Add a line each proc (create a tabel of course)
    • "INSERT dbo.SPCall (What, When) VALUES (OBJECT_NAME(@@PROCID), GETDATE()"
  3. Extend 2 with duration too

There are "fun" things you can do:

  1. Remove it, see who calls
  2. Remove rights, see who calls
  3. Add RAISERROR ('Warning: pwn3d: call admin', 16, 1), see who calls
  4. Add WAITFOR DELAY '00:01:00', see who calls

You get the idea. The tried-and-tested "see who calls" method of IT support.

If the reports are Reporting Services, then you can mine the RS database for the report runs if you can match code to report DataSet.

You couldn't rely on DMVs anyway because they are reset om SQL Server restart. Query cache/locks are transient and don't persist for any length of time.

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

Read Session Id using Javascript

you can receive the session id by issuing the following regular expression on document.cookie:

alert(document.cookie.match(/PHPSESSID=[^;]+/));

in my example the cookie name to store session id is PHPSESSID (php server), just replace the PHPSESSID with the cookie name that holds the session id. (configurable by the web server)

Filter array to have unique values

Array.prototype.unique = function () {
  return [...new Set(this)]
}

then we can write:

const arr = [1, 5, 2, 2, 2, 3, 4, 3, 2, 1, 5]
const uniqueArr = arr.unique()

Android draw a Horizontal line between views

You should use the new lightweight View Space to draw dividers. Your layout will load faster if you will use Space instead of View.

Horizontal divider:

<android.support.v4.widget.Space
        android:layout_height="1dp"
        android:layout_width="match_parent" /> 

Vertical divider:

<android.support.v4.widget.Space
        android:layout_height="match_parent"
        android:layout_width="1dp" />

You can also add a background:

<android.support.v4.widget.Space
        android:layout_height="match_parent"
        android:layout_width="1dp"
        android:background="?android:attr/listDivider"/>

Usage example:

....
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="One"/>

<android.support.v4.widget.Space
    android:layout_height="match_parent"
    android:layout_width="1dp"
    android:background="?android:attr/listDivider"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Two"/>

<android.support.v4.widget.Space
    android:layout_height="match_parent"
    android:layout_width="1dp"
    android:background="?android:attr/listDivider"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Three"/>
....

In order to use Space you should add the dependency in your build.gradle:

dependencies {
    compile 'com.android.support:support-v4:22.1.+'
}

Documentation https://developer.android.com/reference/android/support/v4/widget/Space.html

How to source virtualenv activate in a Bash script

Here is the script that I use often. Run it as $ source script_name

#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
    . $PWD/venv/bin/activate
}

activate

How do I restrict a float value to only two places after the decimal point in C?

Code definition :

#define roundz(x,d) ((floor(((x)*pow(10,d))+.5))/pow(10,d))

Results :

a = 8.000000
sqrt(a) = r = 2.828427
roundz(r,2) = 2.830000
roundz(r,3) = 2.828000
roundz(r,5) = 2.828430

How to convert a command-line argument to int?

As WhirlWind has pointed out, the recommendations to use atoi aren't really very good. atoi has no way to indicate an error, so you get the same return from atoi("0"); as you do from atoi("abc");. The first is clearly meaningful, but the second is a clear error.

He also recommended strtol, which is perfectly fine, if a little bit clumsy. Another possibility would be to use sscanf, something like:

if (1==sscanf(argv[1], "%d", &temp))
    // successful conversion
else
    // couldn't convert input

note that strtol does give slightly more detailed results though -- in particular, if you got an argument like 123abc, the sscanf call would simply say it had converted a number (123), whereas strtol would not only tel you it had converted the number, but also a pointer to the a (i.e., the beginning of the part it could not convert to a number).

Since you're using C++, you could also consider using boost::lexical_cast. This is almost as simple to use as atoi, but also provides (roughly) the same level of detail in reporting errors as strtol. The biggest expense is that it can throw exceptions, so to use it your code has to be exception-safe. If you're writing C++, you should do that anyway, but it kind of forces the issue.

C++ - Assigning null to a std::string

Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:

    mosqpp::tls_set(
        MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
        MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
        MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
        MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
    );

It is a little cumbersome, but allows one to keep everything as a std::string up until the API call itself.

How to display all elements in an arraylist?

It's not at all clear what you're up to. Your function getAll() should return a List<Car>, not a Car. Otherwise, why call it getAll?

If you have

Car[] arrayOfCars

and want a List, you can simply do this:

List<Car> listOfCars = Arrays.asList(arrayOfCars);

Arrays is documented Here.

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

String.Replace ignoring case

Use this, Tested and 100% Worked!

For VB.NET

Dim myString As String
Dim oldValue As String
Dim newValue As String

myString = Form1.TextBox1.Text
oldValue = TextBox1.Text
newValue = TextBox2.Text

Dim working As String = myString
Dim index As Integer = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase)

While index <> -1
    working = working.Remove(index, oldValue.Length)
    working = working.Insert(index, newValue)
    index = index + newValue.Length
    index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase)
    Form1.TextBox1.Text = working
End While

For C#

private void Button2_Click(System.Object sender, System.EventArgs e)
{
    string myString;
    string oldValue;
    string newValue;

    myString = Form1.TextBox1.Text;
    oldValue = TextBox1.Text;
    newValue = TextBox2.Text;

    string working = myString;
    int index = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase);

    while (index != -1)
    {
        working = working.Remove(index, oldValue.Length);
        working = working.Insert(index, newValue);
        index = index + newValue.Length;
        index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase);
        Form1.TextBox1.Text = working;
    }
}

Opposite of append in jquery

Use the remove() method:

$(this).children("ul").remove();

Add new attribute (element) to JSON object using JavaScript

You can also dynamically add attributes with variables directly in an object literal.

const amountAttribute = 'amount';
const foo = {
                [amountAttribute]: 1
            };
foo[amountAttribute + "__more"] = 2;

Results in:

{
    amount: 1, 
    amount__more: 2
}

Getting value of select (dropdown) before change

_x000D_
_x000D_
var last_value;
var current_value;
$(document).on("click","select",function(){
    last_value = $(this).val();
}).on("change","select",function(){
    current_value = $(this).val();

    console.log('last value - '+last_value);
    console.log('current value - '+current_value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
_x000D_
_x000D_
_x000D_

In Javascript/jQuery what does (e) mean?

e doesn't have any special meaning. It's just a convention to use e as function parameter name when the parameter is event.

It can be

$(this).click(function(loremipsumdolorsitamet) {
    // does something
}

as well.

Responsive design with media query : screen size?

The screen widths Bootstrap v3.x uses are as follows:

  • Extra small devices Phones (<768px) / .col-xs-
  • Small devices Tablets (=768px) / .col-sm-
  • Medium devices Desktops (=992px) / .col-md-
  • Large devices Desktops (=1200px) / .col-lg-

So, these are good to use and work well in practice.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

How to set initial value and auto increment in MySQL?

First you need to add column for auto increment

alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST

This query for add column at first. Now you have to reset auto increment initial value. So use this query

alter table users AUTO_INCREMENT=1001

Now your table started with 1001

Locate current file in IntelliJ

There is no direct shortcut for such operation in IntelliJ IDEA 14 but you can install the plugin and set it the keyboard shortcut to the function that called "Scroll From Source" in keymap settings.

enter image description here

How to append strings using sprintf?

Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?

It might be easier to abstract this out into its own function (the following assumes C99):

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
  va_list args;
  char temp[targetSize];
  int result;

  va_start(args, format);
  result = vsnprintf(temp, targetSize, format, args);
  if (result != EOF)
  {
    if (strlen(temp) + strlen(target) > targetSize)
    {
      fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
      return 0;
    }
    strcat(target, temp);
  }
  va_end(args);
  return result;
}

And you would use it like so:

char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");

etc.

The function returns the value from vsprintf, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.

Install Node.js on Ubuntu

Here is the full description to create the first program using the express generator,

Ubuntu's package manager

To install Node.js and npm via apt-get, run these commands:

sudo apt-get update
sudo apt-get install nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo apt-get install npm

Express application generator:

$ npm install express-generator -g

Display the command options with the -h option:

$ express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

For example, the following creates an Express application named myapp in the current working directory:

$ express myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.jade
   create : myapp/views/layout.jade
   create : myapp/views/error.jade
   create : myapp/bin
   create : myapp/bin/www

Then install dependencies:

$ cd myapp
$ npm install

Run the app with this command:

$ DEBUG=myapp:* npm start

Then load http://localhost:3000/ in your browser to access the application.

The generated application has the following directory structure:

+-- app.js
+-- bin
¦   +-- www
+-- package.json
+-- public
¦   +-- images
¦   +-- javascripts
¦   +-- stylesheets
¦       +-- style.css
+-- routes
¦   +-- index.js
¦   +-- users.js
+-- views
    +-- error.jade
    +-- index.jade
    +-- layout.jade

7 directories, 9 files

Method to Add new or update existing item in Dictionary

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

DevTools failed to load SourceMap: Could not load content for chrome-extension

I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (EDIT: this fix seems to massively speed up the browser too) was by adding a dead file

  1. physically create the file it wants\ where it wants, as a blank file (EG: "popper.min.js.map")

  2. put this in the blank file

    {
     "version": 1,
     "mappings": "",
     "sources": [],
     "names": [],
     "file": "popper.min.js"
    }
    
  3. make sure that "file": "*******" in the content of the blank file MATCHES the name of your file ******.map (minus the word ".map")

(EDIT: I suspect you could physically add this dead file method to the addon yourself)

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

angularjs - ng-repeat: access key and value from JSON array object

try this..

<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

Ellipsis for overflow text in dropdown boxes

You can use this jQuery function instead of plus Bootstrap tooltip

function DDLSToolTipping(ddlsArray) {
    $(ddlsArray).each(function (index, ddl) {
        DDLToolTipping(ddl)
    });
}

function DDLToolTipping(ddlID, maxLength, allowDots) {
    if (maxLength == null) { maxLength = 12 }
    if (allowDots == null) { allowDots = true }

    var selectedOption = $(ddlID).find('option:selected').text();

    if (selectedOption.length > maxLength) {
        $(ddlID).attr('data-toggle', "tooltip")
                .attr('title', selectedOption);

        if (allowDots) {
            $(ddlID).prev('sup').remove();
            $(ddlID).before(
            "<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
               )
        }
    }

    else if ($(ddlID).attr('title') != null) {
        $(ddlID).removeAttr('data-toggle')
                .removeAttr('title');
    }
}

Change drawable color programmatically

You can try this for ImageView. using setColorFilter().

imageViewIcon.setColorFilter(ContextCompat.getColor(context, R.color.colorWhite));

AngularJS - Multiple ng-view in single template

UI-Router is a project that can help: https://github.com/angular-ui/ui-router One of it's features is Multiple Named Views

UI-Router has many features and i recommend you using it if you're working on an advanced app.

Check documentation of Multiple Named Views here.

Can I change the color of Font Awesome's icon color?

You can change the Font Awesome's icon color with the bootstrap class

use

text-color

example

text-white

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

How do I get the type of a variable?

You can definitely go for typeid(x).name() where x is the variable name. It actually returns a const char pointer to the data type. Now, look at the following code.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n = 36;
    char c = 'A';
    double d = 1.2;
    if(*(typeid(n).name()) == 'i'){
        cout << "I am an Integer variable" << endl;
    }
    if(*((char *) typeid(d).name()) == 'd'){
        cout << "I am a Double variable" << endl;
    }
    if(*((char *) typeid(c).name()) == 'c'){
        cout << "I am a Char variable" << endl;
    }
    return 0;
}

Notice how first and second both if works.

jQuery check if an input is type checkbox?

$("#myinput").attr('type') == 'checkbox'

How can I compare two dates in PHP?

in the database the date looks like this 2011-10-2

Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

How to create a database from shell command?

Use

$ mysqladmin -u <db_user_name> -p create <db_name>

You will be prompted for password. Also make sure the mysql user you use has privileges to create database.

"SMTP Error: Could not authenticate" in PHPMailer

I had the same issue and did all the tips including Gmail setting (e.g. less secure apps access) with no luck. But finally when I changed password to something different, for some reason it worked! FYI, the initial password did not have any special characters.

Get the latest date from grouped MySQL data

Subquery giving dates. We are not linking with the model. So below query solves the problem.

If there are duplicate dates/model can be avoided by the following query.

select t.model, t.date
from doc t
inner join (select model, max(date) as MaxDate from doc  group by model)
tm on t.model = tm.model and t.date = tm.MaxDate

SQL Insert Query Using C#

class Program
{
    static void Main(string[] args)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
        sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();
            Console.WriteLine(" Connection Opened ");
            command = new SqlCommand(sql, connection);                
            SqlDataReader dr1 = command.ExecuteReader();         

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
        }
    }
}

Use PHP to convert PNG to JPG with compression?

Be careful of what you want to convert. JPG doesn't support alpha-transparency while PNG does. You will lose that information.

To convert, you may use the following function:

// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

This function uses the imagecreatefrompng() and the imagejpeg() functions from the GD library.

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

list.groupBy(i=>i).mapValues(_.size)

gives

Map[Int, Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)

Note that you can replace (i=>i) with built in identity function:

list.groupBy(identity).mapValues(_.size)

Why does DEBUG=False setting make my django Static Files Access fail?

Although it's not safest, but you can change in the source code. navigate to Python/2.7/site-packages/django/conf/urls/static.py

Then edit like following:

if settings.DEBUG or (prefix and '://' in prefix):

So then if settings.debug==False it won't effect on the code, also after running try python manage.py runserver --runserver to run static files.

NOTE: Information should only be used for testing only

Is there a .NET/C# wrapper for SQLite?

A barebones wrapper of the functions as provided by the sqlite library. Latest version supports functions provided sqlite library 3.7.10

SQLiteWrapper project

How do I remove an object from an array with JavaScript?

Well splice works:

var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []

Do NOT use the delete operator on Arrays. delete will not remove an entry from an Array, it will simply replace it with undefined.

var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]

But maybe you want something like this?

var removeByAttr = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i] 
           && arr[i].hasOwnProperty(attr) 
           && (arguments.length > 2 && arr[i][attr] === value ) ){ 

           arr.splice(i,1);

       }
    }
    return arr;
}

Just an example below.

var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);   
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]

removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]

Bootstrap visible and hidden classes not working properly

No CSS required, visible class should like this: visible-md-block not just visible-md and the code should be like this:

<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">

        </div>
    </div>
</div>

<div class="mobile hidden-md hidden-lg ">
    test
</div>

Extra css is not required at all.

Including jars in classpath on commandline (javac or apt)

Use the -cp or -classpath switch.

$ java -help  
Usage: java [-options] class [args...]  
           (to execute a class)  
   or  java [-options] -jar jarfile [args...]  
           (to execute a jar file)  

where options include:  
...  
    -cp <class search path of directories and zip/jar files>  
    -classpath <class search path of directories and zip/jar files>  
                  A ; separated list of directories, JAR archives,  
                  and ZIP archives to search for class files.  

(Note that the separator used to separate entries on the classpath differs between OSes, on my Windows machine it is ;, in *nix it is usually :.)

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

Command not found after npm install in zsh

For me the accepted answer for adding export PATH=/usr/local/share/npm/bin:$PATH to .zshrc didn't work. I tried adding the NVM_DIR as well which solved my issue.

  1. Try vi .bashrc
  2. You will find a line like the following. Copy it.

    export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion

  3. Paste the copied content to .zshrc file

  4. Restart the terminal

I hope this solves your issue.

How to document a method with parameter(s)?

Conventions:

Tools:


Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:

from typing import Dict, Union

def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
    """
    Explanation: this function takes two arguments: `i` and `d`.
    `i` is annotated simply as `int`. `d` is a dictionary with `str` keys
    and values that can be either `str` or `int`.

    The return type is `int`.

    """

The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.

Access a global variable in a PHP function

You can do one of the following:

<?php
    $data = 'My data';

    function menugen() {
        global $data;
        echo "[" . $data . "]";
    }

    menugen();

Or

<?php
    $data = 'My data';

    function menugen() {
        echo "[" . $GLOBALS['data'] . "]";
    }

    menugen();

That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

How to programmatically round corners and set random background colors

Instead of setBackgroundColor, retrieve the background drawable and set its color:

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

Also, you can define the padding within your tags_rounded_corners.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <padding
    android:top="2dp"
    android:left="2dp"
    android:bottom="2dp"
    android:right="2dp" />
</shape> 

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

Automatically open default email client and pre-populate content

JQuery:

$(function () {
      $('.SendEmail').click(function (event) {
        var email = '[email protected]';
        var subject = 'Test';
        var emailBody = 'Hi Sample,';
        var attach = 'path';
        document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
            "?attach="+attach;
      });
    });

HTML:

 <button class="SendEmail">Send Email</button>

How to upgrade pip3?

To upgrade your pip3, try running:

sudo -H pip3 install --upgrade pip3

To upgrade pip as well, you can follow it by:

sudo -H pip2 install --upgrade pip

Git push error pre-receive hook declined

GitLab by default marks master branch as protected (See part Protecting your code in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:

Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.

via https://gitlab.com/gitlab-com/support-forum/issues/40

For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users

How display only years in input Bootstrap Datepicker?

For bootstrap datetimepicker, assign decade value as follow:

$(".years").datetimepicker({
    format: "yyyy",
    startView: 'decade',
    minView: 'decade',
    viewSelect: 'decade',
    autoclose: true,
});

Splitting words into letters in Java

"Stack Me 123 Heppa1 oeu".toCharArray() ?

Iterating through list of list in Python

two nested for loops?

 for a in x:
     print "--------------"
     for b in a:
             print b

It would help if you gave an example of what you want to do with the lists

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

CSS "color" vs. "font-color"

I would think that one reason could be that the color is applied to things other than font. For example:

div {
    border: 1px solid;
    color: red;
}

Yields both a red font color and a red border.

Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.

Positioning <div> element at center of screen

Another easy flexible approach to display block at center: using native text alignment with line-height and text-align.

Solution:

.parent {
    line-height: 100vh;        
    text-align: center;
}

.child {
    display: inline-block;
    vertical-align: middle;
    line-height: 100%;
}

And html sample:

<div class="parent">
  <div class="child">My center block</div>
</div>

We make div.parent fullscreen, and his single child div.child align as text with display: inline-block.

Advantages:

  • flexebility, no absolute values
  • support resize
  • works fine on mobile

Simple example on JSFiddle: https://jsfiddle.net/k9u6ma8g

APK signing error : Failed to read key from keystore

Check your keystore file for first, in you example you creating file with name my-release-key.keystore. If its correct and really present in folder Users/bournewang/Documents/Project check alias, in your example it is -alias alias_name, but in config you specified alias mike

Vuex - passing multiple parameters to mutation

i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

Setting up Action

instead of

actions: {
        authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
    }

do

actions: {
        authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
    }

Calling (dispatching) Action

instead of

this.$store.dispatch({
                  type: 'authenticate',
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

do

this.$store.dispatch('authenticate',{
                  token: response.body.access_token,
                  expiration: response.body.expires_in + Date.now()
              })

hope this gonna help

Convert month name to month number in SQL Server

You can use below code

DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`

SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric

How can I export a GridView.DataSource to a datatable or dataset?

If you do gridview.bind() at:

if(!IsPostBack)

{

//your gridview bind code here...

}

Then you can use DataTable dt = Gridview1.DataSource as DataTable; in function to retrieve datatable.

But I bind the datatable to gridview when i click button, and recording to Microsoft document:

HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests.

If you have same condition, then i will recommend you to use Session to persist the value.

Session["oldData"]=Gridview1.DataSource;

After that you can recall the value when the page postback again.

DataTable dt=(DataTable)Session["oldData"];

References: https://msdn.microsoft.com/en-us/library/ms178581(v=vs.110).aspx#Anchor_0

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/

Maximum number of rows of CSV data in excel sheet

Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link

How does `scp` differ from `rsync`?

The major difference between these tools is how they copy files.

scp basically reads the source file and writes it to the destination. It performs a plain linear copy, locally, or over a network.

rsync also copies files locally or over a network. But it employs a special delta transfer algorithm and a few optimizations to make the operation a lot faster. Consider the call.

rsync A host:B
  • rsync will check files sizes and modification timestamps of both A and B, and skip any further processing if they match.

  • If the destination file B already exists, the delta transfer algorithm will make sure only differences between A and B are sent over the wire.

  • rsync will write data to a temporary file T, and then replace the destination file B with T to make the update look "atomic" to processes that might be using B.

Another difference between them concerns invocation. rsync has a plethora of command line options, allowing the user to fine tune its behavior. It supports complex filter rules, runs in batch mode, daemon mode, etc. scp has only a few switches.

In summary, use scp for your day to day tasks. Commands that you type once in a while on your interactive shell. It's simpler to use, and in those cases rsync optimizations won't help much.

For recurring tasks, like cron jobs, use rsync. As mentioned, on multiple invocations it will take advantage of data already transferred, performing very quickly and saving on resources. It is an excellent tool to keep two directories synchronized over a network.

Also, when dealing with large files, use rsync with the -P option. If the transfer is interrupted, you can resume it where it stopped by reissuing the command. See Sid Kshatriya's answer.