Programs & Examples On #Proj4js

Proj4JS is an open source JavaScript library that transforms map coordinates between different coordinate systems and projections.

How to convert an iterator to a stream?

Use Collections.list(iterator).stream()...

Hide div by default and show it on click with bootstrap

Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.

  1. You need to make sure the target div has an ID.
  2. Bootstrap has a class "collapse", this will hide your block by default. If you want your div to be collapsible AND be shown by default you need to add "in" class to the collapse. Otherwise the toggle behavior will not work properly.
  3. Then, on your hyperlink (also works for buttons), add an href attribute that points to your target div.
  4. Finally, add the attribute data-toggle="collapse" to instruct Bootstrap to add an appropriate toggle script to this tag.

Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):

<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
    This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
    This div (Bar) is shown by default and can toggle
</div>

How to get the size of a string in Python?

Python 3:

user225312's answer is correct:

A. To count number of characters in str object, you can use len() function:

>>> print(len('please anwser my question'))
25

B. To get memory size in bytes allocated to store str object, you can use sys.getsizeof() function

>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50

Python 2:

It gets complicated for Python 2.

A. The len() function in Python 2 returns count of bytes allocated to store encoded characters in a str object.

Sometimes it will be equal to character count:

>>> print(len('abc'))
3

But sometimes, it won't:

>>> print(len('???'))  # String contains Cyrillic symbols
6

That's because str can use variable-length encoding internally. So, to count characters in str you should know which encoding your str object is using. Then you can convert it to unicode object and get character count:

>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols 
3

B. The sys.getsizeof() function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object

>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32

Variable might not have been initialized error

If they were declared as fields of the class then they would be really initialized with 0.

You're a bit confused because if you write:

class Clazz {
  int a;
  int b;

  Clazz () {
     super ();
     b = 0;
  }

  public void printA () {
     sout (a + b);
  }

  public static void main (String[] args) {
     new Clazz ().printA ();
  }
}

Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.

How to get a specific output iterating a hash in Ruby?

hash.keys.sort.each do |key|
  puts "#{key}-----"
  hash[key].each { |val| puts val }
end

Query to list all stored procedures

the best way to get objects is use sys.sql_modules. you can find every thing that you want from this table and join this table with other table to get more information by object_id

SELECT o. object_id,o.name AS name,o.type_desc,m.definition,schemas.name scheamaName
FROM sys.sql_modules        m 
    INNER JOIN sys.objects  o ON m.object_id=o.OBJECT_ID
    INNER JOIN sys.schemas ON schemas.schema_id = o.schema_id
    WHERE [TYPE]='p'

Capitalize only first character of string and leave others alone? (Rails)

str = "this is a Test"
str.sub(/^./, &:upcase)
# => "This is a Test"

Create Test Class in IntelliJ

  1. Right click on project then select new->directory. Create a new directory and name it "test".
  2. Right click on "test" folder then select Mark Directory As->Test Sources Root
  3. Click on Navigate->Test->Create New Test
    Select Testing library(JUnit4 or any)
    Specify Class Name
    Select Member

That's it. We can modify the directory structure as per our need. Good luck!

Numpy: Get random set of rows from 2D array

Another option is to create a random mask if you just want to down-sample your data by a certain factor. Say I want to down-sample to 25% of my original data set, which is currently held in the array data_arr:

# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy.random.choice([False, True], len(data_arr), p=[0.75, 0.25])

Now you can call data_arr[mask] and return ~25% of the rows, randomly sampled.

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

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

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Load CSV data into MySQL in Python

If it is a pandas data frame you could do:

Sending the data

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for.

Check if a key is down?

Other people have asked this kind of question before (though I don't see any obvious dupes here right now).

I think the answer is that the keydown event (and its twin keyup) are all the info you get. Repeating is wired pretty firmly into the operating system, and an application program doesn't get much of an opportunity to query the BIOS for the actual state of the key.

What you can do, and perhaps have to if you need to get this working, is to programmatically de-bounce the key. Essentially, you can evaluate keydown and keyup yourself but ignore a keyupevent if it takes place too quickly after the last keydown... or essentially, you should delay your response to keyup long enough to be sure there's not another keydown event following with something like 0.25 seconds of the keyup.

This would involve using a timer activity, and recording the millisecond times for previous events. I can't say it's a very appealing solution, but...

Bitwise and in place of modulus operator

Not using the bitwise-and (&) operator in binary, there is not. Sketch of proof:

Suppose there were a value k such that x & k == x % (k + 1), but k != 2^n - 1. Then if x == k, the expression x & k seems to "operate correctly" and the result is k. Now, consider x == k-i: if there were any "0" bits in k, there is some i greater than 0 which k-i may only be expressed with 1-bits in those positions. (E.g., 1011 (11) must become 0111 (7) when 100 (4) has been subtracted from it, in this case the 000 bit becomes 100 when i=4.) If a bit from the expression of k must change from zero to one to represent k-i, then it cannot correctly calculate x % (k+1), which in this case should be k-i, but there is no way for bitwise boolean and to produce that value given the mask.

How to make Twitter Bootstrap menu dropdown on hover rather than click

In addition to the answer from "My Head Hurts" (which was great):

ul.nav li.dropdown:hover ul.dropdown-menu{
    display: block;    
}

There are 2 lingering issues:

  1. Clicking on the dropdown link will open the dropdown-menu. And it will stay open unless the user clicks somewhere else, or hovers back over it, creating an awkward UI.
  2. There is a 1px margin between the dropdown link, and dropdown-menu. This causes the dropdown-menu to become hidden if you move slowly between the dropdown and dropdown-menu.

The solution to (1) is removing the "class" and "data-toggle" elements from the nav link

<a href="#">
     Dropdown
     <b class="caret"></b>
</a>

This also gives you the ability to create a link to your parent page - which wasn't possible with the default implementation. You can just replace the "#" with whatever page you want to send the user.

The solution to (2) is removing the margin-top on the .dropdown-menu selector

.navbar .dropdown-menu {
    margin-top: 0px;
}

Excel is not updating cells, options > formula > workbook calculation set to automatic

On Excel 2016, using Alt+Ctrl+F9 work well.

This combination call Application.CalculateFull() VBA Excel function.

This can be time consuming if other Excel files are loaded because all Excel sheets of all opened workbooks will be calculated again!

I have searched a function to calculate a specific sheet but I don't have found something!

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

Android ADT error, dx.jar was not loaded from the SDK folder

If you have updated the ADT tools and also SDK platform and you see the above error, restart Eclipse.

How can I wrap or break long text/word in a fixed width span?

Like this

DEMO

  li span{
    display:block;
    width:50px;
    word-break:break-all;
}

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

If you care about reading that will always return the objects in the order they are inserted in a Dictionary, you may have a look at

OrderedDictionary - values can be accessed via an integer index (by order in which items were added) SortedDictionary - items are automatically sorted

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

Only issue with the solution provided by Greg is that it does not account for number greater than 100 with the "teen" numbers ending. For example, 111 should be 111th, not 111st. This is my solution:

/**
 * Return ordinal suffix (e.g. 'st', 'nd', 'rd', or 'th') for a given number
 * 
 * @param value
 *           a number
 * @return Ordinal suffix for the given number
 */
public static String getOrdinalSuffix( int value )
{
    int hunRem = value % 100;
    int tenRem = value % 10;

    if ( hunRem - tenRem == 10 )
    {
        return "th";
    }
    switch ( tenRem )
    {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

XMLHttpRequest is a standard object in the JavaScript Object model.

According to Wikipedia, XMLHttpRequest first appeared in Internet Explorer 5 as an ActiveX object, but has since been made into a standard and has been included for use in JavaScript in the Mozilla family since 1.0, Apple Safari 1.2, Opera 7.60-p1, and IE 7.0.

The open() method on the object takes the HTTP Method as an argument - and is specified as taking any valid HTTP method (see the item number 5 of the link) - including GET, POST, HEAD, PUT and DELETE, as specified by RFC 2616.

As a side note IE 7–8 only permit the following HTTP methods: "GET", "POST", "HEAD", "PUT", "DELETE", "MOVE", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "LOCK", "UNLOCK", and "OPTIONS".

How to move a marker in Google Maps API

Here is the full code with no errors

        <!DOCTYPE html>
        <html>
        <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }

          #map-canvas 
        { 
        height: 400px; 
        width: 500px;
        }
        </style>

   </script>
        <script type="text/javascript">
        function initialize() {

            var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
                myOptions = {
                    zoom: 5,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                    },
                map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
                marker = new google.maps.Marker( {icon: {
                    url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
                    // This marker is 20 pixels wide by 32 pixels high.
                    size: new google.maps.Size(20, 32),
                    // The origin for this image is (0, 0).
                    origin: new google.maps.Point(0, 0),
                    // The anchor for this image is the base of the flagpole at (0, 32).
                    anchor: new google.maps.Point(0, 32)
                }, position: myLatLng, map: map} );

            marker.setMap( map );
            moveBus( map, marker );

        }



        function moveBus( map, marker ) {
            setTimeout(() => {
                marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
                map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
            }, 1000)


        };



        </script>
        </head>

        <body onload="initialize()">
        <script type="text/javascript">
        //moveBus();
        </script>

        <script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
        <div id="map-canvas" style="height: 500px; width: 500px;"></div>



        </body>
        </html>

Darkening an image with CSS (In any shape)

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

Converting double to string

Complete Info

You can use String.valueOf() for float, double, int, boolean etc.

double d = 0;
float f = 0;
int i = 0;
short i1 = 0;
char c = 0;
boolean bool = false;
char[] chars = {};
Object obj = new Object();


String.valueOf(d);
String.valueOf(i);
String.valueOf(i1);
String.valueOf(f);
String.valueOf(c);
String.valueOf(chars);
String.valueOf(bool);
String.valueOf(obj);

FileNotFoundException..Classpath resource not found in spring?

Two things worth pointing out:

  1. The scope of your spring-context dependency shouldn't be "runtime", but "compile", which is the default, so you can just remove the scope line.
  2. You should configure the compiler plugin to compile to at least java 1.5 to handle the annotations when building with Maven. (Can also affect IDE settings, though Eclipse doesn't tend to care.)

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    

After that, reconfiguring your project from Maven should fix it. I don't recall exactly how to do that in Eclipse, but you should find it if you right click the project node and poke around the menus.

How do I install Composer on a shared hosting?

This tutorial worked for me, resolving my issues with /usr/local/bin permission issues and php-cli (which composer requires, and may aliased differently on shared hosting).

First run these commands to download and install composer:

cd ~
mkdir bin
mkdir bin/composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar bin/composer

Determine the location of your php-cli (needed later on):

which php-cli

(If the above fails, use which php)

It should return the path, such as /usr/bin/php-cli, /usr/php/54/usr/bin/php-cli, etc.

edit ~/.bashrc and make sure this line is at the top, adding it if it is not:

[ -z "$PS1" ] && return

and then add this alias to the bottom (using the php-cli path that you determined earlier):

alias composer="/usr/bin/php-cli ~/bin/composer/composer.phar"

Finish with these commands:

source ~/.bashrc
composer --version

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Twitter Bootstrap 3.0 how do I "badge badge-important" now

If using a SASS version (eg: thomas-mcdonald's one), then you may want to be slightly more dynamic (honor existing variables) and create all badge contexts using the same technique as used for labels:

// Colors
// Contextual variations of badges
// Bootstrap 3.0 removed contexts for badges, we re-introduce them, based on what is done for labels
.badge-default {
  @include label-variant($label-default-bg);
}

.badge-primary {
  @include label-variant($label-primary-bg);
}

.badge-success {
  @include label-variant($label-success-bg);
}

.badge-info {
  @include label-variant($label-info-bg);
}

.badge-warning {
  @include label-variant($label-warning-bg);
}

.badge-danger {
  @include label-variant($label-danger-bg);
}

The LESS equivalent should be straightforward.

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Convert Unix timestamp to a date string

Other examples here are difficult to remember. At its simplest:

date -r 1305712800

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

How to detect installed version of MS-Office?

        public string WinWordVersion
        {
            get
            {
                string _version = string.Empty;
                Word.Application WinWord = new Word.Application();   

                switch (WinWord.Version.ToString())
                {
                    case "7.0":  _version = "95";
                        break;
                    case "8.0": _version = "97";
                        break;
                    case "9.0": _version = "2000";
                        break;
                    case "10.0": _version = "2002";
                        break;
                    case "11.0":  _version = "2003";
                        break;
                    case "12.0": _version = "2007";
                        break;
                    case "14.0": _version = "2010";
                        break;
                    case "15.0":  _version = "2013";
                        break;
                    case "16.0": _version = "2016";
                        break;
                    default:                            
                        break;
                }

                return WinWord.Caption + " " + _version;
            }
        }

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I know this is an old topic. I had the same problem. I tested all the answers about this topic. And nothing worked here... but i found another solution.

Go to pom->overview and add these to you properties:

  • Name: "maven.compiler.target" Value: "1.7"

and

  • Name: "maven.compiler.source" Value: "1.7"

Now do a maven update.

How to Update Multiple Array Elements in mongodb

I tried the following and its working fine.

.update({'events.profile': 10}, { '$set': {'events.$.handled': 0 }},{ safe: true, multi:true }, callback function);

// callback function in case of nodejs

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

Remove a git commit which has not been pushed

Remove the last commit before push

git reset --soft HEAD~1

1 means the last commit, if you want to remove two last use 2, and so forth*

Renaming column names of a DataFrame in Spark Scala

For those of you interested in PySpark version (actually it's same in Scala - see comment below) :

    merchants_df_renamed = merchants_df.toDF(
        'merchant_id', 'category', 'subcategory', 'merchant')

    merchants_df_renamed.printSchema()

Result:

root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)

How do I show the number keyboard on an EditText in android?

editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);

How to get a string between two characters?

Test String test string (67) from which you need to get the String which is nested in-between two Strings.

String str = "test string (67) and (77)", open = "(", close = ")";

Listed some possible ways: Simple Generic Solution:

String subStr = str.substring(str.indexOf( open ) + 1, str.indexOf( close ));
System.out.format("String[%s] Parsed IntValue[%d]\n", subStr, Integer.parseInt( subStr ));

Apache Software Foundation commons.lang3.

StringUtils class substringBetween() function gets the String that is nested in between two Strings. Only the first match is returned.

String substringBetween = StringUtils.substringBetween(subStr, open, close);
System.out.println("Commons Lang3 : "+ substringBetween);

Replaces the given String, with the String which is nested in between two Strings. #395


Pattern with Regular-Expressions: (\()(.*?)(\)).*

The Dot Matches (Almost) Any Character .? = .{0,1}, .* = .{0,}, .+ = .{1,}

String patternMatch = patternMatch(generateRegex(open, close), str);
System.out.println("Regular expression Value : "+ patternMatch);

Regular-Expression with the utility class RegexUtils and some functions.
      Pattern.DOTALL: Matches any character, including a line terminator.
      Pattern.MULTILINE: Matches entire String from the start^ till end$ of the input sequence.

public static String generateRegex(String open, String close) {
    return "(" + RegexUtils.escapeQuotes(open) + ")(.*?)(" + RegexUtils.escapeQuotes(close) + ").*";
}

public static String patternMatch(String regex, CharSequence string) {
    final Pattern pattern  = Pattern.compile(regex, Pattern.DOTALL);
    final Matcher matcher = pattern .matcher(string);

    String returnGroupValue = null;
    if (matcher.find()) { // while() { Pattern.MULTILINE }
        System.out.println("Full match: " + matcher.group(0));
        System.out.format("Character Index [Start:End]«[%d:%d]\n",matcher.start(),matcher.end());
        for (int i = 1; i <= matcher.groupCount(); i++) {
            System.out.println("Group " + i + ": " + matcher.group(i));
            if( i == 2 ) returnGroupValue = matcher.group( 2 );
        }
    }
    return returnGroupValue;
}

Function that creates a timestamp in c#

I believe you can create a unix style datestamp accurate to a second using the following

//Find unix timestamp (seconds since 01/01/1970)
long ticks = DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;
ticks /= 10000000; //Convert windows ticks to seconds
timestamp = ticks.ToString();

Adjusting the denominator allows you to choose your level of precision

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Python NoneType object is not callable (beginner)

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

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

loop(hi, 5)            # Do not use hi() function inside loop() function

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components html.

I followed some of the solutions proposed on this page but any of them worked for me, at least not completely.

What did actually solve my error was to write the below code snippet inside the father html tag of the elements .

I was binding to the variable.

Code:

    *ngIf="variable-name"

The error was caused, apparently by the project trying to render the page, apparently at the moment of evaluating the variable, the project just could no find its value. With the above code snippet you make sure that before rendering the page you ask if the variable has being initialized.

This is my component.ts code:

import { Component, OnInit } from '@angular/core';
import { InvitationService } from 'src/app/service/invitation.service';
import { BusinessService } from 'src/app/service/business.service';
import { Invitation } from 'src/app/_models/invitation';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
  selector: 'app-invitation-details',
  templateUrl: './invitation-details.component.html',
  styleUrls: ['./invitation-details.component.scss']
})
export class InvitationDetailsComponent implements OnInit {
  invitationsList: any;
  currentInvitation: any;
  business: any;
  invitationId: number;
  invitation: Invitation;

  constructor(private InvitationService: InvitationService, private BusinessService: 
BusinessService) { 
this.invitationId = 1; //prueba temporal con invitacion 1
this.getInvitations();
this.getInvitationById(this.invitationId);
  }

   ngOnInit() {

  }

  getInvitations() {
    this.InvitationService.getAllInvitation().subscribe(result => {
      this.invitationsList = result;
      console.log(result);
    }, error => {
      console.log(JSON.stringify(error));
    });
  }

  getInvitationById(invitationId:number){
    this.InvitationService.getInvitationById(invitationId).subscribe(result => {
      this.currentInvitation = result;
      console.log(result);
      //this.business=this.currentInvitation['business'];
       //console.log(this.currentInvitation['business']); 
     }, error => {
     console.log(JSON.stringify(error));
    });
  }
      ...

Here is my html markup:

<div class="container-fluid mt--7">
  <div class="row">
    <div class="container col-xl-10 col-lg-8">
      <div class="card card-stats ">
        <div class="card-body container-fluid form-check-inline" 
         *ngIf="currentInvitation">
          <div class="col-4">
             ...

I hope this can be helpful.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Use of @Service and @Repository annotations are important from database connection perspective.

  1. Use @Service for all your web service type of DB connections
  2. Use @Repository for all your stored proc DB connections

If you do not use the proper annotations, you may face commit exceptions overridden by rollback transactions. You will see exceptions during stress load test that is related to roll back JDBC transactions.

MySQL table is marked as crashed and last (automatic?) repair failed

If your MySQL process is running, stop it. On Debian:

sudo service mysql stop

Go to your data folder. On Debian:

cd /var/lib/mysql/$DATABASE_NAME

Try running:

myisamchk -r $TABLE_NAME

If that doesn't work, you can try:

myisamchk -r -v -f $TABLE_NAME

You can start your MySQL server again. On Debian:

sudo service mysql start

Re-order columns of table in Oracle

It's sad that Oracle doesn't allow this, I get asked to do this by developers all the time..

Here's a slightly dangerous, somewhat quick and dirty method:

  1. Ensure you have enough space to copy the Table
  2. Note any Constraints, Grants, Indexes, Synonyms, Triggers, um.. maybe some other stuff - that belongs to a Table - that I haven't thought about?
  3. CREATE TABLE table_right_columns AS SELECT column1 column3, column2 FROM table_wrong_columns; -- Notice how we correct the position of the columns :)
  4. DROP TABLE table_wrong_columns;
  5. 'ALTER TABLE table_right_columns RENAME TO table_wrong_columns;`
  6. Now the yucky part: recreate all those items you noted in step 2 above
  7. Check what code is now invalid, and recompile to check for errors

And next time you create a table, please consider the future requirements! ;)

Checking for a null int value from a Java ResultSet

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet ordinarily would not.

public final class ResultSetWrapper {

    private final ResultSet rs;

    public ResultSetWrapper(ResultSet rs) {
        this.rs = rs;
    }

    public ResultSet getResultSet() {
        return rs;
    }

    public Boolean getBoolean(String label) throws SQLException {
        final boolean b = rs.getBoolean(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    public Byte getByte(String label) throws SQLException {
        final byte b = rs.getByte(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    // ...

}

How do I generate a list with a specified increment step?

The following example shows benchmarks for a few alternatives.

library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
##                     test replications elapsed  relative user.self sys.self
## 2          (0:5e+05) * 2          100   0.587  3.536145     0.344    0.244
## 1     seq(0, 1e6, by = 2)         100   2.760 16.626506     1.832    0.900
## 3 seq.int(0, 1e6, by = 2)         100   0.166  1.000000     0.056    0.096

In this case, seq.int is the fastest method and seq the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq as the most readable solution.

Getting the 'external' IP address in Java

How about this? It's simple and worked the best for me :)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


public class IP {
    public static void main(String args[]) {
        new IP();
    }

    public IP() {
        URL ipAdress;

        try {
            ipAdress = new URL("http://myexternalip.com/raw");

            BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));

            String ip = in.readLine();
            System.out.println(ip);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to use hex() without 0x in Python?

Use this code:

'{:x}'.format(int(line))

it allows you to specify a number of digits too:

'{:06x}'.format(123)
# '00007b'

For Python 2.6 use

'{0:x}'.format(int(line))

or

'{0:06x}'.format(int(line))

call javascript function on hyperlink click

The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:

<div class="menu">
    <a href="http://example.org">Example</a>
    <a href="http://foobar.com">Foobar.com</a>
</div>

<script>
jQuery( 'div.menu a' )
    .click(function() {
        do_the_click( this.href );
        return false;
    });

// play the funky music white boy
function do_the_click( url )
{
    alert( url );
}
</script>

Python coding standards/best practices

To add to bhadra's list of idiomatic guides:

Checkout Anthony Baxter's presentation on Effective Python Programming (from OSON 2005).

An excerpt:

# dict's setdefault method turns this:
if key in dictobj:
    dictobj[key].append(val)
else:
    dictobj[key] = [val]
# into this:
dictobj.setdefault(key,[]).append(val)

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

Detect URLs in text with JavaScript

tmp.innerText is undefined. You should use tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

How can I add some small utility functions to my AngularJS application?

EDIT 7/1/15:

I wrote this answer a pretty long time ago and haven't been keeping up a lot with angular for a while, but it seems as though this answer is still relatively popular, so I wanted to point out that a couple of the point @nicolas makes below are good. For one, injecting $rootScope and attaching the helpers there will keep you from having to add them for every controller. Also - I agree that if what you're adding should be thought of as Angular services OR filters, they should be adopted into the code in that manner.

Also, as of the current version 1.4.2, Angular exposes a "Provider" API, which is allowed to be injected into config blocks. See these resources for more:

https://docs.angularjs.org/guide/module#module-loading-dependencies

AngularJS dependency injection of value inside of module.config

I don't think I'm going to update the actual code blocks below, because I'm not really actively using Angular these days and I don't really want to hazard a new answer without feeling comfortable that it's actually conforming to new best practices. If someone else feels up to it, by all means go for it.

EDIT 2/3/14:

After thinking about this and reading some of the other answers, I actually think I prefer a variation of the method brought up by @Brent Washburne and @Amogh Talpallikar. Especially if you're looking for utilities like isNotString() or similar. One of the clear advantages here is that you can re-use them outside of your angular code and you can use them inside of your config function (which you can't do with services).

That being said, if you're looking for a generic way to re-use what should properly be services, the old answer I think is still a good one.

What I would do now is:

app.js:

var MyNamespace = MyNamespace || {};

 MyNamespace.helpers = {
   isNotString: function(str) {
     return (typeof str !== "string");
   }
 };

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', function($scope) {
    $scope.helpers = MyNamespace.helpers;
  });

Then in your partial you can use:

<button data-ng-click="console.log(helpers.isNotString('this is a string'))">Log String Test</button>

Old answer below:

It might be best to include them as a service. If you're going to re-use them across multiple controllers, including them as a service will keep you from having to repeat code.

If you'd like to use the service functions in your html partial, then you should add them to that controller's scope:

$scope.doSomething = ServiceName.functionName;

Then in your partial you can use:

<button data-ng-click="doSomething()">Do Something</button>

Here's a way you might keep this all organized and free from too much hassle:

Separate your controller, service and routing code/config into three files: controllers.js, services.js, and app.js. The top layer module is "app", which has app.controllers and app.services as dependencies. Then app.controllers and app.services can be declared as modules in their own files. This organizational structure is just taken from Angular Seed:

app.js:

 angular.module('app', ['app.controllers', 'app.services']).                             
   config(['$routeProvider', function($routeProvider) {
     // Routing stuff here...
   }]);  

services.js:

 /* Generic Services */                                                                                                                                                                                                    
 angular.module('app.services', [])                                                                                                                                                                        
   .factory("genericServices", function() {                                                                                                                                                   
     return {                                                                                                                                                                                                              
       doSomething: function() {   
         //Do something here
       },
       doSomethingElse: function() {
         //Do something else here
       }
    });

controller.js:

angular.module('app.controllers', []).                                                                                                                                                                                  
  controller('firstCtrl', ['$scope', 'genericServices', function($scope, genericServices) {
    $scope.genericServices = genericServices;
  });

Then in your partial you can use:

<button data-ng-click="genericServices.doSomething()">Do Something</button>
<button data-ng-click="genericServices.doSomethingElse()">Do Something Else</button>

That way you only add one line of code to each controller and are able to access any of the services functions wherever that scope is accessible.

How to convert NUM to INT in R?

Use as.integer:

set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819


as.integer(x)
[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
str(xx)
 int [1:5] 26 37 57 90 20

Could not find the main class, program will exit

I was facing the same problem. What I did is I right clicked the project->properties and from "Select/Binary Format" combo box, I selected JDK 6. Then I did clean and built and now when I click the Jar, It works just fine.

Insert a row to pandas dataframe

We can use numpy.insert. This has the advantage of flexibility. You only need to specify the index you want to insert to.

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

df = pd.DataFrame([list(s1), list(s2)],  columns =  ["A", "B", "C"])

pd.DataFrame(np.insert(df.values, 0, values=[2, 3, 4], axis=0))

    0   1   2
0   2   3   4
1   5   6   7
2   7   8   9

For np.insert(df.values, 0, values=[2, 3, 4], axis=0), 0 tells the function the place/index you want to place the new values.

jQuery AJAX submit form

I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input"); 
let formData = new FormData(); 
for (let input of formInputs) {
    formData.append(input.name, input.value); 
}

fetch(form.action,
    {
        method: form.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

find if an integer exists in a list of integers

Here is a extension method, this allows coding like the SQL IN command.

public static bool In<T>(this T o, params T[] values)
{
    if (values == null) return false;

    return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
    if (values == null) return false;

    return values.Contains(o);
}

This allows stuff like that:

List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);

Or:

int i = 5;
bool isIn = i.In(1,2,3,4,5);

How to delete session cookie in Postman?

Manually deleting it in the chrome browser removes the cookie from Postman.

In your chrome browser go to chrome://settings/cookies

Find the cookie and delete it

Edit: As per Max890 comment below (in my version of Google Chrome (ver 63)) this is now chrome://settings/content/cookies Then go to "See all cookies and site data"

Update for Google Chrome 79.0.3945.88

chrome://settings/siteData?search=cookies

How to compile a 64-bit application using Visual C++ 2010 Express?

As what Jakob said: windows sdk 7.1 cannot be installed if MS VC++ x64 and x86 runtimes and redisrtibutables of version 10.0.40219 are present. after removing them win sdk install is okay, VS C++ SP1 can be installed fine again.

Kind regards

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

What you need is a quadrangle instead of a rotated rectangle. RotatedRect will give you incorrect results. Also you will need a perspective projection.

Basicly what must been done is:

  • Loop through all polygon segments and connect those which are almost equel.
  • Sort them so you have the 4 most largest line segments.
  • Intersect those lines and you have the 4 most likely corner points.
  • Transform the matrix over the perspective gathered from the corner points and the aspect ratio of the known object.

I implemented a class Quadrangle which takes care of contour to quadrangle conversion and will also transform it over the right perspective.

See a working implementation here: Java OpenCV deskewing a contour

Constants in Objective-C

As Abizer said, you could put it into the PCH file. Another way that isn't so dirty is to make a include file for all of your keys and then either include that in the file you're using the keys in, or, include it in the PCH. With them in their own include file, that at least gives you one place to look for and define all of these constants.

Using HTML5/JavaScript to generate and save a file

When testing the "ahref" method, I found that the web developer tools of Firefox and Chrome gets confused. I needed to restart the debugging after the a.click() was issued. Same happened with the FileSaver (it uses the same ahref method to actually make the saving). To work around it, I created new temporary window, added the element a into that and clicked it there.

    function download_json(dt) {
        var csv = ' var data = ';
        csv += JSON.stringify(dt, null, 3);

        var uricontent = 'data:application/octet-stream,' + encodeURI(csv);

        var newwin = window.open( "", "_blank" );
        var elem = newwin.document.createElement('a');
        elem.download = "database.js";
        elem.href = uricontent;
        elem.click();
        setTimeout(function(){ newwin.close(); }, 3000);
        
    }

Sending a mail from a linux shell script

Generally, you'd want to use mail command to send your message using local MTA (that will either deliver it using SMTP to the destination or just forward it into some more powerful SMTP server, for example, at your ISP). If you don't have a local MTA (although it's a bit unusual for a UNIX-like system to omit one), you can either use some minimalistic MTA like ssmtp.

ssmtp is quite easy to configure. Basically, you'll just need to specify where your provider's SMTP server is:

# The place where the mail goes. The actual machine name is required
# no MX records are consulted. Commonly mailhosts are named mail.domain.com
# The example will fit if you are in domain.com and you mailhub is so named.
mailhub=mail

Another option is to use one of myriads scripts that just connect to SMTP server directly and try to post a message there, such as Smtp-Auth-Email-Script, smtp-cli, SendEmail, etc.

openpyxl - adjust column width size

Even more pythonic way to set the width of all columns that works at least in openpyxl version 2.4.0:

for column_cells in worksheet.columns:
    length = max(len(as_text(cell.value)) for cell in column_cells)
    worksheet.column_dimensions[column_cells[0].column].width = length

The as_text function should be something that converts the value to a proper length string, like for Python 3:

def as_text(value):
    if value is None:
        return ""
    return str(value)

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

parsing JSONP $http.jsonp() response in angular.js

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);

$http.jsonp(url, {jsonpCallbackParam: 'callback'})
    .then(function(data){
        console.log(data.found);
    });

How to set the image from drawable dynamically in android?

Here is the best way that works in every phone at today. Most of those answer are deprecated or need an API >= 19 or 22. You can use the fragment code or the activity code depends what you need.

Fragment

//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.my_image);

//set the image to the imageView
imageView.setImageBitmap(bitmap);

Activity

//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(MyActivity.this.getResources(), R.drawable.my_image);

//set the image to the imageView
imageView.setImageBitmap(bitmap);

Cheers!

Improve INSERT-per-second performance of SQLite

After reading this tutorial, I tried to implement it to my program.

I have 4-5 files that contain addresses. Each file has approx 30 million records. I am using the same configuration that you are suggesting but my number of INSERTs per second is way low (~10.000 records per sec).

Here is where your suggestion fails. You use a single transaction for all the records and a single insert with no errors/fails. Let's say that you are splitting each record into multiple inserts on different tables. What happens if the record is broken?

The ON CONFLICT command does not apply, cause if you have 10 elements in a record and you need each element inserted to a different table, if element 5 gets a CONSTRAINT error, then all previous 4 inserts need to go too.

So here is where the rollback comes. The only issue with the rollback is that you lose all your inserts and start from the top. How can you solve this?

My solution was to use multiple transactions. I begin and end a transaction every 10.000 records (Don't ask why that number, it was the fastest one I tested). I created an array sized 10.000 and insert the successful records there. When the error occurs, I do a rollback, begin a transaction, insert the records from my array, commit and then begin a new transaction after the broken record.

This solution helped me bypass the issues I have when dealing with files containing bad/duplicate records (I had almost 4% bad records).

The algorithm I created helped me reduce my process by 2 hours. Final loading process of file 1hr 30m which is still slow but not compared to the 4hrs that it initially took. I managed to speed the inserts from 10.000/s to ~14.000/s

If anyone has any other ideas on how to speed it up, I am open to suggestions.

UPDATE:

In Addition to my answer above, you should keep in mind that inserts per second depending on the hard drive you are using too. I tested it on 3 different PCs with different hard drives and got massive differences in times. PC1 (1hr 30m), PC2 (6hrs) PC3 (14hrs), so I started wondering why would that be.

After two weeks of research and checking multiple resources: Hard Drive, Ram, Cache, I found out that some settings on your hard drive can affect the I/O rate. By clicking properties on your desired output drive you can see two options in the general tab. Opt1: Compress this drive, Opt2: Allow files of this drive to have contents indexed.

By disabling these two options all 3 PCs now take approximately the same time to finish (1hr and 20 to 40min). If you encounter slow inserts check whether your hard drive is configured with these options. It will save you lots of time and headaches trying to find the solution

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Using PowerShell credentials without being prompted for a password

I saw one example that uses Import/Export-CLIXML.

These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.

$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
    $cred = Get-Credential -Username domain\username -message 'Please login.'
    Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath

So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.

Finally just use the credential like you normally do.

Restart-Computer -ComputerName ... -Credentail $cred

Note on Securty:

Securely store credentials on disk

When reading the Solution, you might at first be wary of storing a password on disk. While it is natural (and prudent) to be cautious of littering your hard drive with sensitive information, the Export-CliXml cmdlet encrypts credential objects using the Windows standard Data Protection API. This ensures that only your user account can properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also encrypts the password you provide.

Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

How do I remove version tracking from a project cloned from git?

It's not a clever choice to move all .git* by hand, particularly when these .git files are hidden in sub-folders just like my condition: when I installed Skeleton Zend 2 by composer+git, there are quite a number of .git files created in folders and sub-folders.

I tried rm -rf .git on my GitHub shell, but the shell can not recognize the parameter -rf of Remove-Item.

www.montanaflynn.me introduces the following shell command to remove all .git files one time, recursively! It's really working!

find . | grep "\.git/" | xargs rm -rf

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

How to check Elasticsearch cluster health?

You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:

$ curl -XGET 'localhost:9200/_cluster/health?pretty'

This will give you the status and other related data you need.

{
 "cluster_name" : "xxxxxxxx",
 "status" : "green",
 "timed_out" : false,
 "number_of_nodes" : 2,
 "number_of_data_nodes" : 2,
 "active_primary_shards" : 15,
 "active_shards" : 12,
 "relocating_shards" : 0,
 "initializing_shards" : 0,
 "unassigned_shards" : 0,
 "delayed_unassigned_shards" : 0,
 "number_of_pending_tasks" : 0,
 "number_of_in_flight_fetch" : 0
}

How to execute a JavaScript function when I have its name as a string

Could you not just do this:

var codeToExecute = "My.Namespace.functionName()";
var tmpFunc = new Function(codeToExecute);
tmpFunc();

You can also execute any other JavaScript using this method.

How do I escape double and single quotes in sed?

It's hard to escape a single quote within single quotes. Try this:

sed "s@['\"]http://www.\([^.]\+).com['\"]@URL_\U\1@g" 

Example:

$ sed "s@['\"]http://www.\([^.]\+\).com['\"]@URL_\U\1@g" <<END
this is "http://www.fubar.com" and 'http://www.example.com' here
END

produces

this is URL_FUBAR and URL_EXAMPLE here

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

get current page from url

Path.GetFileName( Request.Url.AbsolutePath )

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

CSS display:inline property with list-style-image: property on <li> tags

If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.

The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.

Edit: Yeah, I guess I was wrong. See top entry. :)

Is there possibility of sum of ArrayList without looping

Then write it yourself:

public int sum(List<Integer> list) {
     int sum = 0; 

     for (int i : list)
         sum = sum + i;

     return sum;
}

Setting up a git remote origin

Using SSH

git remote add origin ssh://login@IP/path/to/repository

Using HTTP

git remote add origin http://IP/path/to/repository

However having a simple git pull as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

MySQL: Curdate() vs Now()

Just for the fun of it:

CURDATE() = DATE(NOW())

Or

NOW() = CONCAT(CURDATE(), ' ', CURTIME())

Get the key corresponding to the minimum value within a dictionary

min(zip(d.values(), d.keys()))[1]

Use the zip function to create an iterator of tuples containing values and keys. Then wrap it with a min function which takes the minimum based on the first key. This returns a tuple containing (value, key) pair. The index of [1] is used to get the corresponding key

How to add a changed file to an older (not last) commit in Git

Use git rebase. Specifically:

  1. Use git stash to store the changes you want to add.
  2. Use git rebase -i HEAD~10 (or however many commits back you want to see).
  3. Mark the commit in question (a0865...) for edit by changing the word pick at the start of the line into edit. Don't delete the other lines as that would delete the commits.[^vimnote]
  4. Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
  5. Pop the stash by using git stash pop
  6. Add your file with git add <file>.
  7. Amend the commit with git commit --amend --no-edit.
  8. Do a git rebase --continue which will rewrite the rest of your commits against the new one.
  9. Repeat from step 2 onwards if you have marked more than one commit for edit.

[^vimnote]: If you are using vim then you will have to hit the Insert key to edit, then Esc and type in :wq to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano".

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Changing the name of model name starting with Uppercase works. Example : Login_model.php instead of login_model.php

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

boardRepo.deleteByBoardId(id);

Faced the same issue. GOT javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread

I resolved it by adding @Transactional annotation above the controller/service.

Writing a dictionary to a csv file with one line for every 'key: value'

I've personally always found the csv module kind of annoying. I expect someone else will show you how to do this slickly with it, but my quick and dirty solution is:

with open('dict.csv', 'w') as f:  # This creates the file object for the context 
                                  # below it and closes the file automatically
    l = []
    for k, v in mydict.iteritems(): # Iterate over items returning key, value tuples
        l.append('%s: %s' % (str(k), str(v))) # Build a nice list of strings
    f.write(', '.join(l))                     # Join that list of strings and write out

However, if you want to read it back in, you'll need to do some irritating parsing, especially if it's all on one line. Here's an example using your proposed file format.

with open('dict.csv', 'r') as f: # Again temporary file for reading
    d = {}
    l = f.read().split(',')      # Split using commas
    for i in l:
        values = i.split(': ')   # Split using ': '
        d[values[0]] = values[1] # Any type conversion will need to happen here

IndexError: tuple index out of range ----- Python

Probably one of the indexes is wrong, either the inner one or the outer one.

I suspect you mean to say [0] where you say [1] and [1] where you say [2]. Indexes are 0-based in Python.

How to read/write from/to file using Go?

With newer Go versions, reading/writing to/from file is easy. To read from a file:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    data, err := ioutil.ReadFile("text.txt")
    if err != nil {
        return
    }
    fmt.Println(string(data))
}

To write to a file:

package main

import "os"

func main() {
    file, err := os.Create("text.txt")
    if err != nil {
        return
    }
    defer file.Close()

    file.WriteString("test\nhello")
}

This will overwrite the content of a file (create a new file if it was not there).

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

How do I set the selenium webdriver get timeout?

I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:

  1. You can timeout the complete test by using @Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.

  2. Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time

How to do an update + join in PostgreSQL?

First Table Name: tbl_table1 (tab1). Second Table Name: tbl_table2 (tab2).

Set the tbl_table1's ac_status column to "INACTIVE"

update common.tbl_table1 as tab1
set ac_status= 'INACTIVE' --tbl_table1's "ac_status"
from common.tbl_table2 as tab2
where tab1.ref_id= '1111111' 
and tab2.rel_type= 'CUSTOMER';

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

fatal: does not appear to be a git repository

I met a similar problem when I tried to store my existing repo in my Ubunt One account, I fixed it by the following steps:

Step-1: create remote repo

$ cd ~/Ubuntu\ One/
$ mkdir <project-name>
$ cd <project-name>
$ mkdir .git
$ cd .git
$ git --bare init

Step-2: add the remote

$ git remote add origin /home/<linux-user-name>/Ubuntu\ One/<project-name>/.git

Step-3: push the exising git reop to the remote

$ git push -u origin --all

Kill all processes for a given user

The following kills all the processes created by this user:

kill  -9  -1

Selenium WebDriver findElement(By.xpath()) not working for me

Just need to add * at the beginning of xpath and closing bracket at last.

element = findElement(By.xpath("//*[@test-id='test-username']"));

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

Raise an event whenever a property's value changed?

If you change your property to use a backing field (instead of an automatic property), you can do the following:

public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;

public string ImageFullPath1 
{
  get
  {
    return imageFullPath1 ;
  }
  set
  {
    if (_imageFullPath1 != value)
    { 
      _imageFullPath1 = value;

      EventHandler handler = ImageFullPathChanged;
      if (handler != null)
        handler(this, e);
    }
  }
}

How do I initialize Kotlin's MutableList to empty MutableList?

I do like below to :

var book: MutableList<Books> = mutableListOf()

/** Returns a new [MutableList] with the given elements. */

public fun <T> mutableListOf(vararg elements: T): MutableList<T>
    = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

How to refresh Gridview after pressed a button in asp.net

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :

protected void bLoanButton_Click(object sender, EventArgs e)
{

//your same code
........

GridView1.DataBind();


}

regards

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

Go to beginning of line without opening new line in VI

Try this Vi/Vim cheatsheet solution to many problems.

For normal mode :
0 - [zero] to beginning of line, first column.
$ - to end of line

Making sure at least one checkbox is checked

You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?

Here's a non-jQuery solution to check if any checkboxes on the page are checked.

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);

You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.

Keras, how do I predict after I trained a model?

You can just "call" your model with an array of the correct shape:

model(np.array([[6.7, 3.3, 5.7, 2.5]]))

Full example:

from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np

X, y = load_iris(return_X_y=True)

model = Sequential([
    Dense(16, activation='relu'),
    Dense(32, activation='relu'),
    Dense(1)])

model.compile(loss='mean_absolute_error', optimizer='adam')

history = model.fit(X, y, epochs=10, verbose=0)

print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>

Remove file from SVN repository without deleting local copy

Rename your file, commit the changes including the "deleted" file, and don't include the new (renamed) file.

Rename your file back.

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1579542560:1
        )

    [_edit_last] => Array
        (
            [0] => 1
        )

    [example_field] => Array
        (
            [0] => 13
        )
)

Hope that helps someone, go make a ruckus!

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

Subtract one day from datetime

Try this

SELECT DATEDIFF(DAY,  DATEADD(day, -1, '2013-03-13 00:00:00.000'), GETDATE())

OR

SELECT DATEDIFF(DAY,  DATEADD(day, -1, @CreatedDate), GETDATE())

Empty set literal?

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something

Python: Finding differences between elements of a list

The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:

v = numpy.diff(t)

How to drop all tables from a database with one SQL query?

Use the following script to drop all constraints:

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' ALTER TABLE ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) +    ' NOCHECK CONSTRAINT all; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

Then run the following to drop all tables:

select @sql='';

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

This worked for me in Azure SQL Database where 'sp_msforeachtable' was not available!

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

PHP + MySQL transactions examples

The idea I generally use when working with transactions looks like this (semi-pseudo-code):

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();
    
    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');
    
    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (\Throwable $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
    throw $e; // but the error must be handled anyway
}

Note that, with this idea, if a query fails, an Exception must be thrown:
  • PDO can do that, depending on how you configure it
  • else, with some other API, you might have to test the result of the function used to execute a query, and throw an exception yourself.

Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.

For example, quite often you'll have a couple of queries before the transaction (before the begin) and another couple of queries after the transaction (after either commit or rollback) and you'll want those queries executed no matter what happened (or not) in the transaction.

Unzip a file with php

Just change

system('unzip $master.zip');

To this one

system('unzip ' . $master . '.zip');

or this one

system("unzip {$master}.zip");

How to get the size of a file in MB (Megabytes)?

Since Java 7 you can use java.nio.file.Files.size(Path p).

Path path = Paths.get("C:\\1.txt");

long expectedSizeInMB = 27;
long expectedSizeInBytes = 1024 * 1024 * expectedSizeInMB;

long sizeInBytes = -1;
try {
    sizeInBytes = Files.size(path);
} catch (IOException e) {
    System.err.println("Cannot get the size - " + e);
    return;
}

if (sizeInBytes > expectedSizeInBytes) {
    System.out.println("Bigger than " + expectedSizeInMB + " MB");
} else {
    System.out.println("Not bigger than " + expectedSizeInMB + " MB");
}

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

Refresh Page and Keep Scroll Position

UPDATE

You can use document.location.reload(true) as mentioned below instead of the forced trick below.

Replace your HTML with this:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body { 
                background-image: url('../Images/Black-BackGround.gif');
                background-repeat: repeat;
            }
            body td {
               font-Family: Arial; 
               font-size: 12px; 
            }
            #Nav a { 
                position:relative; 
                display:block; 
                text-decoration: none; 
                color:black; 
            }
        </style>
        <script type="text/javascript">
            function refreshPage () {
                var page_y = document.getElementsByTagName("body")[0].scrollTop;
                window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
            }
            window.onload = function () {
                setTimeout(refreshPage, 35000);
                if ( window.location.href.indexOf('page_y') != -1 ) {
                    var match = window.location.href.split('?')[1].split("&")[0].split("=");
                    document.getElementsByTagName("body")[0].scrollTop = match[1];
                }
            }
        </script>
    </head>
    <body><!-- BODY CONTENT HERE --></body>
</html>

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

After enabling annotation processors and installing the lombok plugin, it still didn't work. We worked around it by checking the Idea option "Delegate IDE build to gradle"

How do I sort strings alphabetically while accounting for value when a string is numeric?

Expanding on Jeff Paulsen answer. I wanted to make sure it didn't matter how many number or char groups were in the strings:

public class SemiNumericComparer : IComparer<string>
{
    public int Compare(string s1, string s2)
    {
        if (int.TryParse(s1, out var i1) && int.TryParse(s2, out var i2))
        {
            if (i1 > i2)
            {
                return 1;
            }

            if (i1 < i2)
            {
                return -1;
            }

            if (i1 == i2)
            {
                return 0;
            }
        }

        var text1 = SplitCharsAndNums(s1);
        var text2 = SplitCharsAndNums(s2);

        if (text1.Length > 1 && text2.Length > 1)
        {

            for (var i = 0; i < Math.Max(text1.Length, text2.Length); i++)
            {

                if (text1[i] != null && text2[i] != null)
                {
                    var pos = Compare(text1[i], text2[i]);
                    if (pos != 0)
                    {
                        return pos;
                    }
                }
                else
                {
                    //text1[i] is null there for the string is shorter and comes before a longer string.
                    if (text1[i] == null)
                    {
                        return -1;
                    }
                    if (text2[i] == null)
                    {
                        return 1;
                    }
                }
            }
        }

        return string.Compare(s1, s2, true);
    }

    private string[] SplitCharsAndNums(string text)
    {
        var sb = new StringBuilder();
        for (var i = 0; i < text.Length - 1; i++)
        {
            if ((!char.IsDigit(text[i]) && char.IsDigit(text[i + 1])) ||
                (char.IsDigit(text[i]) && !char.IsDigit(text[i + 1])))
            {
                sb.Append(text[i]);
                sb.Append(" ");
            }
            else
            {
                sb.Append(text[i]);
            }
        }

        sb.Append(text[text.Length - 1]);

        return sb.ToString().Split(' ');
    }
}

I also took SplitCharsAndNums from an SO Page after amending it to deal with file names.

Get refresh token google api

It is access_type=offline that you want.

This will return the refresh token the first time the user authorises the app. Subsequent calls do not force you to re-approve the app (approval_prompt=force).

See further detail: https://developers.google.com/accounts/docs/OAuth2WebServer#offline

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Explanation of <script type = "text/template"> ... </script>

To add to Box9's answer:

Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.

If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates. http://documentcloud.github.com/jammit/#jst

By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.

urllib2.HTTPError: HTTP Error 403: Forbidden

NSE website has changed and the older scripts are semi-optimum to current website. This snippet can gather daily details of security. Details include symbol, security type, previous close, open price, high price, low price, average price, traded quantity, turnover, number of trades, deliverable quantities and ratio of delivered vs traded in percentage. These conveniently presented as list of dictionary form.

Python 3.X version with requests and BeautifulSoup

from requests import get
from csv import DictReader
from bs4 import BeautifulSoup as Soup
from datetime import date
from io import StringIO 

SECURITY_NAME="3MINDIA" # Change this to get quote for another stock
START_DATE= date(2017, 1, 1) # Start date of stock quote data DD-MM-YYYY
END_DATE= date(2017, 9, 14)  # End date of stock quote data DD-MM-YYYY


BASE_URL = "https://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={security}&segmentLink=3&symbolCount=1&series=ALL&dateRange=+&fromDate={start_date}&toDate={end_date}&dataType=PRICEVOLUMEDELIVERABLE"




def getquote(symbol, start, end):
    start = start.strftime("%-d-%-m-%Y")
    end = end.strftime("%-d-%-m-%Y")

    hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
         'Referer': 'https://cssspritegenerator.com',
         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
         'Accept-Encoding': 'none',
         'Accept-Language': 'en-US,en;q=0.8',
         'Connection': 'keep-alive'}

    url = BASE_URL.format(security=symbol, start_date=start, end_date=end)
    d = get(url, headers=hdr)
    soup = Soup(d.content, 'html.parser')
    payload = soup.find('div', {'id': 'csvContentDiv'}).text.replace(':', '\n')
    csv = DictReader(StringIO(payload))
    for row in csv:
        print({k:v.strip() for k, v in row.items()})


 if __name__ == '__main__':
     getquote(SECURITY_NAME, START_DATE, END_DATE)

Besides this is relatively modular and ready to use snippet.

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

Press TAB and then ENTER key in Selenium WebDriver

WebElement webElement = driver.findElement(By.xpath(""));

//Enter the xpath or ID.

     webElement.sendKeys("");

//Input the string to pass.

     webElement.sendKeys(Keys.TAB);

//This will enter the string which you want to pass and will press "Tab" button .

java.math.BigInteger cannot be cast to java.lang.Long

Your error might be in this line:

List<Long> result = query.list();

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list();

TypeError: method() takes 1 positional argument but 2 were given

Newcomer to Python, I had this issue when I was using the Python's ** feature in a wrong way. Trying to call this definition from somewhere:

def create_properties_frame(self, parent, **kwargs):

using a call without a double star was causing the problem:

self.create_properties_frame(frame, kw_gsp)

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

T-SQL split string

This is based on Andy Robertson's answer, I needed a delimiter other than comma.

CREATE FUNCTION dbo.splitstring ( @stringToSplit nvarchar(MAX), @delim nvarchar(max))
RETURNS
 @returnList TABLE ([value] [nvarchar] (MAX))
AS
BEGIN

 DECLARE @value NVARCHAR(max)
 DECLARE @pos INT

 WHILE CHARINDEX(@delim, @stringToSplit) > 0
 BEGIN
  SELECT @pos  = CHARINDEX(@delim, @stringToSplit)  
  SELECT @value = SUBSTRING(@stringToSplit, 1, @pos - 1)

  INSERT INTO @returnList 
  SELECT @value

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos + LEN(@delim), LEN(@stringToSplit) - @pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END
GO

And to use it:

SELECT * FROM dbo.splitstring('test1 test2 test3', ' ');

(Tested on SQL Server 2008 R2)

EDIT: correct test code

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

Using Case/Switch and GetType to determine the object

You can do this:

if (node is CasusNodeDTO)
{
    ...
}
else if (node is BucketNodeDTO)
{
    ...
}
...

While that would be more elegant, it's possibly not as efficient as some of the other answers here.

How to use custom font in a project written in Android Studio

I want to add my answer for Android-O and Android Studio 2.4

  1. Create folder called font under res folder. Download the various fonts you wanted to add to your project example Google fonts

  2. Inside your xml user font family

    example :

    <TextView
        android:fontFamily="@font/indie_flower"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/sample_text" />
    

3.If you want it to be in programmatic way use following code

Typeface typeface = getResources().getFont(R.font.indie_flower);
textView.setTypeface(typeface);

for more information follow the link to my blog post Font styles for Android with Android Studio 2.4

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

how to display variable value in alert box?

Clean way with no jQuery:

function check(some_id) {
    var content = document.getElementById(some_id).childNodes[0].nodeValue;
    alert(content);
}

This is assuming each span has only the value as a child and no embedded HTML.

What is Persistence Context?

Persistence Context is an environment or cache where entity instances(which are capable of holding data and thereby having the ability to be persisted in a database) are managed by Entity Manager.It syncs the entity with database.All objects having @Entity annotation are capable of being persisted. @Entity is nothing but a class which helps us create objects in order to communicate with the database.And the way the objects communicate is using methods.And who supplies those methods is the Entity Manager.

How to "log in" to a website using Python's Requests module?

Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

How can I confirm a database is Oracle & what version it is using SQL?

SQL> SELECT version FROM v$instance;
VERSION
-----------------
11.2.0.3.0

Date format in the json output using spring boot

You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.

You should do two things

  • add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")

get dataframe row count based on conditions

You are asking for the condition where all the conditions are true, so len of the frame is the answer, unless I misunderstand what you are asking

In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))

In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]: 
           A         B         C         D
12  0.491683  0.137766  0.859753 -1.041487
13  0.376200  0.575667  1.534179  1.247358
14  0.428739  1.539973  1.057848 -1.254489

In [19]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)].count()
Out[19]: 
A    3
B    3
C    3
D    3
dtype: int64

In [20]: len(df[(df['A']>0) & (df['B']>0) & (df['C']>0)])
Out[20]: 3

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

package javax.mail and javax.mail.internet do not exist

If using maven, just add to your pom.xml:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

Of course, you need to check the current version.

How can I one hot encode in Python?

This works for me:

pandas.factorize( ['B', 'C', 'D', 'B'] )[0]

Output:

[0, 1, 2, 0]

How can I ping a server port with PHP?

Try this :

echo exec('ping -n 1 -w 1 72.10.169.28');

html select option separator

You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)

In HTML:

<option value="—————————————" disabled>—————————————</option>

Or in XHTML:

<option value="—————————————" disabled="disabled">—————————————</option>

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

Normalizing a list of numbers in Python

There isn't any function in the standard library (to my knowledge) that will do it, but there are absolutely modules out there which have such functions. However, its easy enough that you can just write your own function:

def normalize(lst):
    s = sum(lst)
    return map(lambda x: float(x)/s, lst)

Sample output:

>>> normed = normalize(raw)
>>> normed
[0.25, 0.5, 0.25]

How do I resolve this "ORA-01109: database not open" error?

The same problem takes me here. After all, I found that link, it's good for me.

Source link

CHECK THE STATUS OF PLUGGABLE DATABASE.

SQL> STARTUP; ORACLE instance started.

Total System Global Area 788529152 bytes Fixed Size 2929352 bytes Variable Size 541068600 bytes Database Buffers 239075328 bytes Redo Buffers 5455872 bytes Database mounted. Database opened. SQL> select name,open_mode from v$pdbs;

NAME OPEN_MODE ------------------------------ ---------- PDB$SEED MOUNTED PDBORCL MOUNTED PDBORCL2 MOUNTED PDBORCL1
MOUNTED

WE NEED TO START PDB$SEED PLUGGABLE DATABASE in UPGRADE STATE FOR THAT

SQL> SHUTDOWN IMMEDIATE;

Database closed. Database dismounted. ORACLE instance shut down.

SQL> STARTUP UPGRADE;

ORACLE instance started.

Total System Global Area 788529152 bytes Fixed Size 2929352 bytes Variable Size 541068600 bytes Database Buffers 239075328 bytes Redo Buffers 5455872 bytes Database mounted. Database opened.

SQL> ALTER PLUGGABLE DATABASE ALL OPEN UPGRADE; Pluggable database altered.

SQL> select name,open_mode from v$pdbs;

NAME OPEN_MODE ------------------------------ ---------- PDB$SEED MIGRATE PDBORCL MIGRATE PDBORCL2 MIGRATE PDBORCL1
MIGRATE

How to test which port MySQL is running on and whether it can be connected to?

On a mac os X, there are two options. netstat or lsof

Using netstat will not show the process on Mac OS X. so using netstat you can only search by port.
Using lsof will show the process name.

I did the following as I was encountering port conflicts (docker containers):

netstat -aln | grep 3306

Outputs: tcp46 0 0 *.3306 *.* LISTEN

sudo lsof -i -P | grep -i "LISTEN" | grep -i 3306

Outputs: mysqld 60608 _mysql 31u IPv6 0x2ebc4b8d88d9ec6b 0t0 TCP *:3306 (LISTEN)

Remove #N/A in vlookup result

if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.

How to overlay image with color in CSS?

You may use negative superthick semi-transparent border...

_x000D_
_x000D_
.red {_x000D_
    outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
    outline-offset: -100px;_x000D_
    overflow: hidden;_x000D_
    position: relative;_x000D_
    height: 200px;_x000D_
    width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
_x000D_
_x000D_

This solution requires you to know exact sizes of covered object.

How to trim a list in Python

To trim a list in place without creating copies of it, use del:

>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>> 

Track a new remote branch created on GitHub

When the branch is no remote branch you can push your local branch direct to the remote.

git checkout master
git push origin master

or when you have a dev branch

git checkout dev
git push origin dev

or when the remote branch exists

git branch dev -t origin/dev

There are some other posibilites to push a remote branch.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How to get the string size in bytes?

If you use sizeof()then a char *str and char str[] will return different answers. char str[] will return the length of the string(including the string terminator) while char *str will return the size of the pointer(differs as per compiler).

How can I get the current user's username in Bash?

Two commands:

  1. id prints the user id along with the groups. Format: uid=usernumber(username) ...

  2. whoami gives the current user name

Download a file from HTTPS using download.file()

Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.

I resolved the problem doing as follows:

  1. Using RStudio instead of R console.

  2. Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).

  3. I typed the URL address as https (secure connection) and with / instead of backslashes \\.

  4. Setting method = "auto".

It works for me now. You should see the message:

Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by

what is the use of Eval() in asp.net

IrishChieftain didn't really address the question, so here's my take:

eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

Count number of tables in Oracle

These documents describe data dictionary views:

all_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4473.htm#REFRN26286

user_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091

dba_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4155.htm#i1627762

You can run queries on these views to count what you need.

To add something more to @Anurag Thakre's answer:

Use this query which will give you the actual no of counts respect to the owners

SELECT COUNT(*),tablespace_name  FROM USER_TABLES group by tablespace_name;

Or by table owners:

SELECT COUNT(*), owner  FROM ALL_TABLES group by owner;

Tablespace itself does not identify an unique object owner. Multiple users can create objects in the same tablespace and a single user can create objects in various tablespaces. It is a common practice to separate tables and indexes into different tablespaces.

How to loop over directories in Linux?

find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"

Is there a 'foreach' function in Python 3?

Here is the example of the "foreach" construction with simultaneous access to the element indexes in Python:

for idx, val in enumerate([3, 4, 5]):
    print (idx, val)

How to exit an if clause

Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.

However, cleaner still would be:

if some_condition:
   ...
   if condition_a:
       your_function1()
   else:
       your_function2()

...

def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
   else:
       # more code here

Can't find how to use HttpContent

While the final version of HttpContent and the entire System.Net.Http namespace will come with .NET 4.5, you can use a .NET 4 version by adding the Microsoft.Net.Http package from NuGet

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

this is what i used:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

Android: How do bluetooth UUIDs work?

UUID is just a number. It has no meaning except you create on the server side of an Android app. Then the client connects using that same UUID.

For example, on the server side you can first run uuid = UUID.randomUUID() to generate a random number like fb36491d-7c21-40ef-9f67-a63237b5bbea. Then save that and then hard code that into your listener program like this:

 UUID uuid = UUID.fromString("fb36491d-7c21-40ef-9f67-a63237b5bbea"); 

Your Android server program will listen for incoming requests with that UUID like this:

    BluetoothServerSocket server = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("anyName", uuid);

BluetoothSocket socket = server.accept();

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Open Android Studio, Go to Tools then Android and then SDK, uncheck NDK If you do not need this, and restart android studio.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

My two cents: In my case, cacerts was not a folder, but a file, and also it was presents on two paths After discover it, error disappeared after copy the .jks file over that file.

# locate cacerts    
/usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
/usr/java/jre1.8.0_221-amd64/lib/security/cacerts

After backup them, I copy the .jks over.

cp /path_of_jks_file/file.jks /usr/java/jdk1.8.0_221-amd64/jre/lib/security/cacerts
cp /path_of_jks_file/file.jks /usr/java/jre1.8.0_221-amd64/lib/security/cacerts

Note: this basic trick resolves this error on a Genexus project, in spite file.jks is also on the server.xml file of the Tomcat.

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Check string length in PHP

An XPath solution is to use:

string-length((//div[@class='contest'])[$k])

where $k should be substituted by a number.

This evaluates to the string length of the $k-th (in document order) div in the XML document that has a class attribute with value 'contest'.

UILabel Align Text to center

From iOS 6 and later UITextAlignment is deprecated. use NSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Swift Version from iOS 6 and later

myLabel.textAlignment = .center

Task continuation on UI thread

If you have a return value you need to send to the UI you can use the generic version like this:

This is being called from an MVVM ViewModel in my case.

var updateManifest = Task<ShippingManifest>.Run(() =>
    {
        Thread.Sleep(5000);  // prove it's really working!

        // GenerateManifest calls service and returns 'ShippingManifest' object 
        return GenerateManifest();  
    })

    .ContinueWith(manifest =>
    {
        // MVVM property
        this.ShippingManifest = manifest.Result;

        // or if you are not using MVVM...
        // txtShippingManifest.Text = manifest.Result.ToString();    

        System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);

    }, TaskScheduler.FromCurrentSynchronizationContext());

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Creating and appending text to txt file in VB.NET

Try this:

Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
    sw.WriteLine( _
        IIf(fileExists, _
            "Error Message in  Occured at-- " & DateTime.Now, _
            "Start Error Log for today"))
End Using

MVVM Passing EventArgs As Command Parameter

I know this is a fairly old question, but I ran into the same problem today and wasn't too interested in referencing all of MVVMLight just so I can use event triggers with event args. I have used MVVMLight in the past and it's a great framework, but I just don't want to use it for my projects any more.

What I did to resolve this problem was create an ULTRA minimal, EXTREMELY adaptable custom trigger action that would allow me to bind to the command and provide an event args converter to pass on the args to the command's CanExecute and Execute functions. You don't want to pass the event args verbatim, as that would result in view layer types being sent to the view model layer (which should never happen in MVVM).

Here is the EventCommandExecuter class I came up with:

public class EventCommandExecuter : TriggerAction<DependencyObject>
{
    #region Constructors

    public EventCommandExecuter()
        : this(CultureInfo.CurrentCulture)
    {
    }

    public EventCommandExecuter(CultureInfo culture)
    {
        Culture = culture;
    }

    #endregion

    #region Properties

    #region Command

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    #region EventArgsConverterParameter

    public object EventArgsConverterParameter
    {
        get { return (object)GetValue(EventArgsConverterParameterProperty); }
        set { SetValue(EventArgsConverterParameterProperty, value); }
    }

    public static readonly DependencyProperty EventArgsConverterParameterProperty =
        DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));

    #endregion

    public IValueConverter EventArgsConverter { get; set; }

    public CultureInfo Culture { get; set; }

    #endregion

    protected override void Invoke(object parameter)
    {
        var cmd = Command;

        if (cmd != null)
        {
            var param = parameter;

            if (EventArgsConverter != null)
            {
                param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
            }

            if (cmd.CanExecute(param))
            {
                cmd.Execute(param);
            }
        }
    }
}

This class has two dependency properties, one to allow binding to your view model's command, the other allows you to bind the source of the event if you need it during event args conversion. You can also provide culture settings if you need to (they default to the current UI culture).

This class allows you to adapt the event args so that they may be consumed by your view model's command logic. However, if you want to just pass the event args on verbatim, simply don't specify an event args converter.

The simplest usage of this trigger action in XAML is as follows:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter Command="{Binding Path=Update, Mode=OneTime}" EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

If you needed access to the source of the event, you would bind to the owner of the event

<i:Interaction.Triggers>
    <i:EventTrigger EventName="NameChanged">
        <cmd:EventCommandExecuter 
            Command="{Binding Path=Update, Mode=OneTime}" 
            EventArgsConverter="{x:Static c:NameChangedArgsToStringConverter.Default}"
            EventArgsConverterParameter="{Binding ElementName=SomeEventSource, Mode=OneTime}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

(this assumes that the XAML node you're attaching the triggers to has been assigned x:Name="SomeEventSource"

This XAML relies on importing some required namespaces

xmlns:cmd="clr-namespace:MyProject.WPF.Commands"
xmlns:c="clr-namespace:MyProject.WPF.Converters"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and creating an IValueConverter (called NameChangedArgsToStringConverter in this case) to handle the actual conversion logic. For basic converters I usually create a default static readonly converter instance, which I can then reference directly in XAML as I have done above.

The benefit of this solution is that you really only need to add a single class to any project to use the interaction framework much the same way that you would use it with InvokeCommandAction. Adding a single class (of about 75 lines) should be much more preferable to an entire library to accomplish identical results.

NOTE

this is somewhat similar to the answer from @adabyron but it uses event triggers instead of behaviours. This solution also provides an event args conversion ability, not that @adabyron's solution could not do this as well. I really don't have any good reason why I prefer triggers to behaviours, just a personal choice. IMO either strategy is a reasonable choice.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

build and listener objects are presenting during system groovy execution. You can do this:

def myVar = build.getEnvironment(listener).get('myVar')

What is the meaning of "POSIX"?

A specification (blueprint) about how to make an OS compatible with late UNIX OS (may God bless him!). This is why macOS and GNU/Linux have very similar terminal command lines, GUI's, libraries, etc. Because they both were designed according to POSIX blueprint.

POSIX does not tell engineers and programmers how to code but what to code.

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

<style>
    body {
        background-color: red;
        transition: background-color 2s ease-in;
    }
</style>

<script>
    window.onload = function() {
        document.body.style.backgroundColor = '#00f';
    }
</script>

<body>
    <p>test</p>
</body>

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Just in case you don't want to bump Windows SDK to Windows 10 (you could be for example working on an open source project where the decision isn't yours to make), you can solve this problem in a Windows SDK 8.1 project by navigating Tools -> Get Tools and Features... -> Individual Compontents tab and installing the individual components "Windows 8.1 SDK" (under SDKs, libraries and frameworks) and "Windows Universal CRT SDK" (under Compilers, build tools and runtimes):

How to grant permission to users for a directory using command line in Windows?

Use cacls command. See information here.

CACLS files /e /p {USERNAME}:{PERMISSION}

Where,

/p : Set new permission

/e : Edit permission and kept old permission as it is i.e. edit ACL instead of replacing it.

{USERNAME} : Name of user

{PERMISSION} : Permission can be:

R - Read

W - Write

C - Change (write)

F - Full control

For example grant Rocky Full (F) control with following command (type at Windows command prompt):

C:> CACLS files /e /p rocky:f

Read complete help by typing following command:

C:> cacls /?

Update Angular model after setting input value with jQuery

You have to use the following code in order to update the scope of the specific input model as follows

$('button').on('click', function(){
    var newVal = $(this).data('val');
    $('select').val(newVal).change();

    var scope = angular.element($("select")).scope();
    scope.$apply(function(){
        scope.selectValue = newVal;
    });
});

How to run DOS/CMD/Command Prompt commands from VB.NET?

Sub systemcmd(ByVal cmd As String)
    Shell("cmd /c """ & cmd & """", AppWinStyle.MinimizedFocus, True)
End Sub

Android draw a Horizontal line between views

----> Simple one

 <TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#c0c0c0"
    android:id="@+id/your_id"
    android:layout_marginTop="160dp" />

javac: file not found: first.java Usage: javac <options> <source files>

So I had the same problem because I wasn't in the right directory where my file was located. So when I ran javac Example.java (for me) it said it couldn't find it. But I needed to go to where my Example.java file was located. So I used the command cd and right after that the location of the file. That worked for me. Tell me if it helps! Thanks!