Programs & Examples On #Oracleexception

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

This error message can be thrown in the application logs when the actual issue is that the oracle database server ran out of space.

After correcting the space issue, this particular error message disappeared.

Difference between Interceptor and Filter in Spring MVC

From HandlerIntercepter's javadoc:

HandlerInterceptor is basically similar to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

With that being said:

So where is the difference between Interceptor#postHandle() and Filter#doFilter()?

postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it's already committed.

doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing.

Also, in preHandle and postHandle methods, you have access to the HandlerMethod that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.

What is the best practise in which use cases it should be used?

As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

REACT - toggle class onclick

Thanks to @cssko for providing the correct answer, but if you tried it yourself you will realise it does not work. A suggestion has been made by @Matei Radu, but was rejected by @cssko, so the code remains unrunnable (it will throw error 'Cannot read property bind of undefined'). Below is the working correct answer:

_x000D_
_x000D_
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.addActiveClass = this.addActiveClass.bind(this);
    this.state = {
      active: false,
    };
  }
  addActiveClass() {
    const currentState = this.state.active;
    this.setState({
      active: !currentState
    });
  };

  render() {
    return ( <
      div className = {
        this.state.active ? 'your_className' : null
      }
      onClick = {
        this.addActiveClass
      } >
      <
      p > {
        this.props.text
      } < /p> < /
      div >
    )
  }
}

class Test extends React.Component {
  render() {
    return ( <
      div >
      <
      MyComponent text = {
        'Clicking this will toggle the opacity through css class'
      }
      /> < /
      div >
    );
  }
}

ReactDOM.render( <
  Test / > ,
  document.body
);
_x000D_
.your_className {
  opacity: 0.3
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

In PHP, how do you change the key of an array element?

Simple benchmark comparison of both solution.

Solution 1 Copy and remove (order lost, but way faster) https://stackoverflow.com/a/240676/1617857

<?php
$array = ['test' => 'value'];

$array['test2'] = $array['test'];
unset($array['test']);

Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857

<?php
$array = ['test' => 'value'];

$keys = array_keys( $array );
$keys[array_search('test', $keys, true)] = 'test2';
array_combine( $keys, $array );

Benchmark:

<?php
$array = ['test' => 'value'];


for ($i =0; $i < 100000000; $i++){
    // Solution 1
}


for ($i =0; $i < 100000000; $i++){
    // Solution 2
}

Results:

php solution1.php  6.33s  user 0.02s system 99% cpu 6.356  total
php solution1.php  6.37s  user 0.01s system 99% cpu 6.390  total
php solution2.php  12.14s user 0.01s system 99% cpu 12.164 total
php solution2.php  12.57s user 0.03s system 99% cpu 12.612 total

Converting milliseconds to a date (jQuery/JavaScript)

One line code.

var date = new Date(new Date().getTime());

or

var date = new Date(1584120305684);

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

Commenting out code blocks in Atom

Command + / or Ctrl + shift + 7 doesn't work for me (debian + colombian keyboard). In my case I changed the Atom keymap.cson file adding the following:

'.editor':
  'ctrl-7': 'editor:toggle-line-comments'

and now it works!

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

Here's an extension to Tony's extension... :-)

For Entity Framework 4.x, if you want to get the name and value of the key field so that you know which entity instance (DB record) has the problem, you can add the following. This provides access to the more powerful ObjectContext class members from your DbContext object.

// Get the key field name & value.
// This assumes your DbContext object is "_context", and that it is a single part key.
var e = ((IObjectContextAdapter)_context).ObjectContext.ObjectStateManager.GetObjectStateEntry(validationErrors.Entry.Entity);
string key = e.EntityKey.EntityKeyValues[0].Key;
string val = e.EntityKey.EntityKeyValues[0].Value;

Create a rounded button / button with border-radius in Flutter

Another cool solution that works in 2021

TextButton(
      child: Padding(
        padding: const EdgeInsets.all(5.0),
        child: Text('Follow Us'.toUpperCase()),
      ),
      style: TextButton.styleFrom(
      backgroundColor: Colors.amber,
      shadowColor: Colors.red,
      elevation: 2,
      textStyle: TextStyle(fontSize: 18,  fontWeight: FontWeight.bold),
      shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(5.0),)
    ),
    onPressed: () {
      print('Pressed');
    },
    ),

Extract Month and Year From Date in R

Here's another solution using a package solely dedicated to working with dates and times in R:

library(tidyverse)
library(lubridate)

(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#>      ID Date      
#>   <int> <chr>     
#> 1     1 2004-02-06
#> 2     2 2006-03-14
#> 3     3 2007-07-16

df %>%
  mutate(
    Date = ymd(Date),
    Month_Yr = format_ISO8601(Date, precision = "ym")
  )
#> # A tibble: 3 x 3
#>      ID Date       Month_Yr
#>   <int> <date>     <chr>   
#> 1     1 2004-02-06 2004-02 
#> 2     2 2006-03-14 2006-03 
#> 3     3 2007-07-16 2007-07

Created on 2020-09-01 by the reprex package (v0.3.0)

How do I simulate placeholder functionality on input date field?

You can do something like this:

<input onfocus="(this.type='date')" class="js-form-control" placeholder="Enter Date">

How to read a text file directly from Internet using Java?

Alternatively, you can use Guava's Resources object:

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);

Failed to execute removeChild on Node

For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:

// Didn't work
<div>
     <TroubledComponent/>
</div>

// Worked
<div key='uniqueKey'>
     <TroubledComponent/>
</div>

Why compile Python code?

Something not touched upon is source-to-source-compiling. For example, nuitka translates Python code to C/C++, and compiles it to binary code which directly runs on the CPU, instead of Python bytecode which runs on the slower virtual machine.

This can lead to significant speedups, or it would let you work with Python while your environment depends on C/C++ code.

How do I round a double to two decimal places in Java?

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

DecimalFormat twoDForm = new DecimalFormat("#.00");

What is the { get; set; } syntax in C#?

So as I understand it { get; set; } is an "auto property" which just like @Klaus and @Brandon said is shorthand for writing a property with a "backing field." So in this case:

public class Genre
{
    private string name; // This is the backing field
    public string Name   // This is your property
    {
        get => name;
        set => name = value;
    }
}

However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.

get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).

There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.

Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
                        //called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();

//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)

Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.

public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now 

We can set the name of 'g1' to Hip Hop by writing the following

g1.Name = "Hip Hop";

What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property

set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:

public class g1 //We've created an instance of the Genre Class called "g1"
{
    private string name;
    public string Name
    {
        get => name;
        set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because 
                              //'value' in 'g1' was set to "Hip Hop" by previously
                              //writing 'g1.Name = "Hip Hop"'
    }
}

It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.

So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing

console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property 
                             //and returns the field 'name' which we just set to
                             //"Hip Hop"

and if we ran this we would get "Hip Hop" in our console.

So for the purpose of this explanation I'll complete the example with outputs as well

using System;
public class Genre
{
    public string Name { get; set; }
}

public class MainClass
{
    public static void Main()
    {
        Genre g1 = new Genre();
        Genre g2 = new Genre();
        Genre g3 = new Genre();

        g1.Name = "Hip Hop";
        g2.Name = "Rock";
        g3.Name = "Country";

        Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
    }
}

Output:

"Genres: Hip Hop, Rock, Country"

Match line break with regular expression

You could search for:

<li><a href="#">[^\n]+

And replace with:

$0</a>

Where $0 is the whole match. The exact semantics will depend on the language are you using though.


WARNING: You should avoid parsing HTML with regex. Here's why.

jQuery.ajax returns 400 Bad Request

Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.

$.ajax({
    type: 'get',

must be met with

app.get('/', function(req, res) {

=============== and for post

$.ajax({
    type: 'post',

must be met with

app.post('/', function(req, res) {

MS SQL compare dates?

SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...

Should do what you need.

Test Case

WITH dates(date1, date2, date3, date4)
     AS (SELECT CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME),
                CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME))
SELECT CASE
         WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITH_CAST,
       CASE
         WHEN date3 <= date4 THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITHOUT_CAST
FROM   dates 

Returns

COMPARISON_WITH_CAST   |  COMPARISON_WITHOUT_CAST
Y                         N

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Error using eclipse for Android - No resource found that matches the given name

tried what KennyH write but it didn't solved my problem that appear while trying edit style.xml file in my android app, so I just delete the project from eclipse (not from disk of course !!) and import it back ,solved it for me in that case.

Java to Jackson JSON serialization: Money fields

I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.

private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
    return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}

Pycharm: run only part of my Python file

You can select a code snippet and use right click menu to choose the action "Execute Selection in console".

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

A little bit late to the party... but I found this as a solution for me when having "blocked"-Error in chrome:

Blocking resources whose URLs contain both \n and < characters.

More info here: https://www.chromestatus.com/feature/5735596811091968

Convert to/from DateTime and Time in Ruby

You can use to_date, e.g.

> Event.last.starts_at
=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00
> Event.last.starts_at.to_date
=> Wed, 13 Jan 2021

'ls' in CMD on Windows is not recognized

enter image description here

First

Make a dir c:\command

Second Make a ll.bat

ll.bat

dir

Third Add to Path C:/commands enter image description here

Cannot attach the file *.mdf as database

I recently ran into the same problem. Here is one thing to check. in visual studio there are three place we should check and remove the database.

1. Solution Explorer's App_Data folder
2. Server Explorer's Data Connection menu
3. SQL Server Object Explorer

When I delete database from the first two point, the error still occurs. So, I needed to delete the database from the SQL Server Object Explorer as well. Then I could easily run the 'update-database' command without error. Hope this helps.

websocket closing connection automatically

I found another, rather quick and dirty, solution. If you use the low level approach to implement the WebSocket and you Implement the onOpen method yourself you receive an object implementing the WebSocket.Connection interface. This object has a setMaxIdleTime method which you can adjust.

Grep to find item in Perl array

You seem to be using grep() like the Unix grep utility, which is wrong.

Perl's grep() in scalar context evaluates the expression for each element of a list and returns the number of times the expression was true. So when $match contains any "true" value, grep($match, @array) in scalar context will always return the number of elements in @array.

Instead, try using the pattern matching operator:

if (grep /$match/, @array) {
    print "found it\n";
}

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

"Initializing" variables in python?

def grade(inlist):
    grade_1, grade_2, grade_3, average =inlist
    print (grade_1)
    print (grade_2)

mark=[1,2,3,4]
grade(mark)

Globally catch exceptions in a WPF application?

In addition what others mentioned here, note that combining the Application.DispatcherUnhandledException (and its similars) with

<configuration>
  <runtime>  
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

in the app.config will prevent your secondary threads exception from shutting down the application.

Why am I getting AttributeError: Object has no attribute

I have encountered the same error as well. I am sure my indentation did not have any problem. Only restarting the python sell solved the problem.

Time part of a DateTime Field in SQL

This should strip away the date part:

select convert(datetime,convert(float, getdate()) - convert(int,getdate())), getdate()

and return a datetime with a default date of 1900-01-01.

CSS submit button weird rendering on iPad/iPhone

oops! just found myself: just add this line on any element you need

   -webkit-appearance: none;

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

Remove specific characters from a string in Javascript

Another way to do it:

rnum = rnum.split("F0").pop()

It splits the string into two: ["", "123456"], then selects the last element.

How to remove multiple deleted files in Git repository

If you want to delete all of them by using "git rm". This is what I do:

git ls-files --deleted -z | xargs -0 git rm

This query lists of all the files that have been removed and deletes them from your git repository. Hope it helps.

How to Add Incremental Numbers to a New Column Using Pandas

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

What is the max size of localStorage values?

Once I developed Chrome (desktop browser) extension and tested Local Storage real max size for this reason.

My results:

Ubuntu 18.04.1 LTS (64-bit)
Chrome 71.0.3578.98 (Official Build) (64-bit)
Local Storage content size 10240 KB (10 MB)

More than 10240 KB usage returned me the error:

Uncaught DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'notes' exceeded the quota.

Edit on Oct 23, 2020

For a Chrome extensions available chrome.storage API. If you declare the "storage" permission in manifest.js:

{
    "name": "My extension",
    ...
    "permissions": ["storage"],
    ...
}

You can access it like this:

chrome.storage.local.QUOTA_BYTES // 5242880 (in bytes)

Deploy a project using Git push

Giddyup are language-agnostic just-add-water git hooks to automate deployment via git push. It also allows you to have custom start/stop hooks for restarting web server, warming up cache etc.

https://github.com/mpalmer/giddyup

Check out examples.

Checking host availability by using ping in bash scripts

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi

How does Tomcat locate the webapps directory?

I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/", for example, I kept getting "This localhost page can't be found" in the browser.

I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/" as changing it to appBase="C:/Java Project/ROOT" will cause "This localhost page can't be found" to be displayed again.

Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:

Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)

EDIT:

Modify last line to :

cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) 

if you want it to work even if there are spaces or other funny characters in the sheet name.

How to change the color of the axis, ticks and labels for a plot in matplotlib

  • For those using pandas.DataFrame.plot(), matplotlib.axes.Axes is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax, which enables the usage of the associated formatting methods.
  • The default plotting backend for pandas, is matplotlib.
import pandas as pd

# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)

# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))

# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red') 
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both')  # 'both' refers to minor and major axes

enter image description here

How to add a .dll reference to a project in Visual Studio

For Visual Studio 2019 you may not find Project -> Add Reference option. Use Project -> Add Project Reference. Then in dialog window navigate to Browse tab and use Browse to find and attach your dll.

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

@ variables in Ruby on Rails

@ variables are instance variables, without are local variables.

Read more at http://ruby.about.com/od/variables/a/Instance-Variables.htm

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

PHP: Possible to automatically get all POSTed data?

No one mentioned Raw Post Data, but it's good to know, if posted data has no key, but only value, use Raw Post Data:

$postdata = file_get_contents("php://input");

PHP Man:

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

JavaScript property access: dot notation vs. brackets?

You need to use brackets if the property names has special characters:

var foo = {
    "Hello, world!": true,
}
foo["Hello, world!"] = false;

Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).

How to get dictionary values as a generic list

Another variation you could also use

MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();

VB.NET: how to prevent user input in a ComboBox

Seeing a user banging away at a control that overrides her decisions is a sad sight. Set the control's Enabled property to False. If you don't like that then change its Items property so only one item is selectable.

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

Get img src with PHP

$imgTag = <<< LOB
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
<img border="0" src="/images/not_match_image.jpg" alt="Image" width="100" height="100" />
LOB;

preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $imgTag, $matches);
$imgSrc = $matches[1];

DEMO


NOTE: You should use an HTML Parser like DOMDocument and NOT a regex.

How do you test your Request.QueryString[] variables?

Use int.TryParse instead to get rid of the try-catch block:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

RegEx for matching UK Postcodes

I have the regex for UK Postcode validation.

This is working for all type of Postcode either inner or outer

^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))) || ^((GIR)[ ]?(0AA))$|^(([A-PR-UWYZ][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][0-9][A-HJKS-UW0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$|^(([A-PR-UWYZ][A-HK-Y0-9][0-9][ABEHMNPRVWXY0-9])[ ]?([0-9][ABD-HJLNPQ-UW-Z]{0,2}))$

This is working for all type of format.

Example:

AB10-------------------->ONLY OUTER POSTCODE

A1 1AA------------------>COMBINATION OF (OUTER AND INNER) POSTCODE

WC2A-------------------->OUTER

Remove an item from an IEnumerable<T> collection

There is now an extension method to convert the IEnumerable<> to a Dictionary<,> which then has a Remove method.

public readonly IEnumerable<User> Users = new User[]; // or however this would be initialized

// To take an item out of the collection
Users.ToDictionary(u => u.Id).Remove(1123);

// To take add an item to the collection
Users.ToList().Add(newuser);

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

This should fix your problem:

$credentials = New-Object Management.Automation.PSCredential “[email protected]”, (“password” | ConvertTo-SecureString -AsPlainText -Force)

Then use the credential in your call to Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];

For example you have a NSString with special characters in NSString strChangetoJSON. Then you can convert that string to JSON response using above code.

Xampp Access Forbidden php

I had the same problem. So I got remembere. Yesterday I had commented this code in htttp-xampp.conf

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
#        AllowOverride AuthConfig
#        Require local
#        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

SO I can access my localhost using other system on same network(LAN/WIFI) as it make localhost require local.

So I just make it like

Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
#        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

and now its working on my local machine and also localhost is accessible using other systems on same LAN/WIFI.

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

Returning a value from callback function in Node.js

I am facing small trouble in returning a value from callback function in Node.js

This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.

Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        // call the function that needs the value
        callback(finalData);
        // we are done
        return;
    });
}

Line callback(finalData); is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)

Getting number of days in a month

I made it calculate days in month from datetimepicker selected month and year , and I but the code in datetimepicker1 textchanged to return the result in a textbox with this code

private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    int s = System.DateTime.DaysInMonth(DateTimePicker1.Value.Date.Year, DateTimePicker1.Value.Date.Month);

    TextBox1.Text = s.ToString();
} 

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

How to create JSON Object using String?

In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value) no add(value).

https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)

(Android API 19-27. Kotlin 1.2.50)

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

What exactly does stringstream do?

To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

I saw it used mainly for the formatted output/input goodness.

One good example would be c++ implementation of converting number to stream object.

Possible example:

template <class T>
string num2str(const T& num, unsigned int prec = 12) {
    string ret;
    stringstream ss;
    ios_base::fmtflags ff = ss.flags();
    ff |= ios_base::floatfield;
    ff |= ios_base::fixed;
    ss.flags(ff);
    ss.precision(prec);
    ss << num;
    ret = ss.str();
    return ret;
};

Maybe it's a bit complicated but it is quite complex. You create stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

Also in this example the string buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

not None test in Python

The best bet with these types of questions is to see exactly what python does. The dis module is incredibly informative:

>>> import dis
>>> dis.dis("val != None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               3 (!=)
              6 RETURN_VALUE
>>> dis.dis("not (val is None)")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>> dis.dis("val is not None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None) and uses the is not operator. The first uses the != operator when comparing with None.

As pointed out by other answers, using != when comparing with None is a bad idea.

IndentationError: unexpected indent error

import urllib.request
import requests
from bs4 import BeautifulSoup

        r = requests.get('https://icons8.com/icons/set/favicon')

If you try to connect to such a site, you will get an indent error.

import urllib.request
import requests
from bs4 import BeautifulSoup


r = requests.get('https://icons8.com/icons/set/favicon')

Python cares about indents

How to show text in combobox when no item selected?

    private void comboBox1_TextChanged(object sender, EventArgs e)
    {
        if (comboBox1.Text == "")
            comboBox1.Text = "Select one of the answers"; 
    }

should do the trick at startup this line is present, when selected an item on combobox, this items text will appear. when deleling the text this text will appear again

How can I clone a JavaScript object except for one key?

Hey seems like you run in to reference issues when you're trying to copy an object then deleting a property. Somewhere you have to assign primitive variables so javascript makes a new value.

Simple trick (may be horrendous) I used was this

var obj = {"key1":"value1","key2":"value2","key3":"value3"};

// assign it as a new variable for javascript to cache
var copy = JSON.stringify(obj);
// reconstitute as an object
copy = JSON.parse(copy);
// now you can safely run delete on the copy with completely new values
delete copy.key2

console.log(obj)
// output: {key1: "value1", key2: "value2", key3: "value3"}
console.log(copy)
// output: {key1: "value1", key3: "value3"}

Passing a String by Reference in Java?

All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.

The assignment

zText += foo;

is equivalent to:

zText = new String(zText + "foo");

That is, it (locally) reassigns the parameter zText as a new reference, which points to a new memory location, in which is a new String that contains the original contents of zText with "foo" appended.

The original object is not modified, and the main() method's local variable zText still points to the original (empty) string.

class StringFiller {
  static void fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value:

If you want to modify the string, you can as noted use StringBuilder or else some container (an array or an AtomicReference or a custom container class) that gives you an additional level of pointer indirection. Alternatively, just return the new value and assign it:

class StringFiller2 {
  static String fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
    return zText;
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    zText = fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value: foo

This is probably the most Java-like solution in the general case -- see the Effective Java item "Favor immutability."

As noted, though, StringBuilder will often give you better performance -- if you have a lot of appending to do, particularly inside a loop, use StringBuilder.

But try to pass around immutable Strings rather than mutable StringBuilders if you can -- your code will be easier to read and more maintainable. Consider making your parameters final, and configuring your IDE to warn you when you reassign a method parameter to a new value.

Automatically capture output of last command into a variable using Bash?

This is not strictly a bash solution but you can use piping with sed to get the last row of previous commands output.

First lets see what i have in folder "a"

rasjani@helruo-dhcp022206::~$ find a
a
a/foo
a/bar
a/bat
a/baz
rasjani@helruo-dhcp022206::~$ 

Then, your example with ls and cd would turn to sed & piping into something like this:

rasjani@helruo-dhcp022206::~$ cd `find a |sed '$!d'`
rasjani@helruo-dhcp022206::~/a/baz$ pwd
/home/rasjani/a/baz
rasjani@helruo-dhcp022206::~/a/baz$

So, the actual magic happens with sed, you pipe what ever output of what ever command into sed and sed prints the last row which you can use as parameter with back ticks. Or you can combine that to xargs also. ("man xargs" in shell is your friend)

Escape double quotes for JSON in Python

Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes

How to scroll to top of the page in AngularJS?

You can use

$window.scrollTo(x, y);

where x is the pixel along the horizontal axis and y is the pixel along the vertical axis.

  1. Scroll to top

    $window.scrollTo(0, 0);
    
  2. Focus on element

    $window.scrollTo(0, angular.element('put here your element').offsetTop);   
    

Example

Update:

Also you can use $anchorScroll

Example

Creating a system overlay window (always on top)

This might be a stupid solution. But it works. If you can improve it, please let me know.

OnCreate of your Service: I have used WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH flag. This is the only change in service.

@Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
        mView = new HUDView(this);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
    }

Now, you will start getting each and every click event. So, you need to rectify in your event handler.

In your ViewGroup touch event

@Override
public boolean onTouchEvent(MotionEvent event) {

    // ATTENTION: GET THE X,Y OF EVENT FROM THE PARAMETER
    // THEN CHECK IF THAT IS INSIDE YOUR DESIRED AREA


    Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
    return true;
}

Also you may need to add this permission to your manifest:

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

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Append Char To String in C?

You can use strncat()

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

int main(void){
  char hi[6];
  char ch = '!';
  strcpy(hi, "hello");

  strncat(hi, &ch, 1);
  printf("%s\n", hi);
}

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

How do I use a file grep comparison inside a bash if/else statement?

just use bash

while read -r line
do
  case "$line" in
    *MYSQL_ROLE=master*)
       echo "do your stuff";;
    *) echo "doesn't exist";;      
  esac
done <"/etc/aws/hosts.conf"

Is there a Google Voice API?

Well... These are PHP. There is an sms one from google here.

And github has one here.

Another sms one is here. However, this one has a lot more code, so it may take up more space.

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

How to read keyboard-input?

Non-blocking, multi-threaded example:

As blocking on keyboard input (since the input() function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.

This works by creating one thread to run in the background, continually calling input() and then passing any data it receives to a queue.

In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.

1. Bare Python 3 code example (no comments):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

2. Same Python 3 code as above, but with extensive explanatory comments:

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

Sample output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.

The Python Queue library is thread-safe:

Note that Queue.put() and Queue.get() and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

References:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *****https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *****https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. Python: How do I make a subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html

Related/Cross-Linked:

  1. PySerial non-blocking read loop

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Type npm list graceful-fs and you will see which versions of graceful-fs are currently installed.

In my case I got:

npm list graceful-fs

@request/[email protected] /projects/request/promise-core
+-- [email protected]
| `-- [email protected]
|   +-- [email protected]
|   | `-- [email protected]
|   |   `-- [email protected]
|   |     `-- [email protected]
|   |       `-- [email protected]        <==== !!!
|   `-- [email protected] 
`-- [email protected]
  +-- [email protected]
  | `-- [email protected]
  |   `-- [email protected]
  |     `-- [email protected]
  |       `-- [email protected] 
  `-- [email protected]
    `-- [email protected]
      `-- [email protected]

As you can see gulp deep down depends on a very old version. Unfortunately, I can't update that myself using npm update graceful-fs. gulp would need to update their dependencies. So if you have a case like this you are out of luck. But you may open an issue for the project with the old dependency - i.e. gulp.

Convert file path to a file URI?

UrlCreateFromPath to the rescue! Well, not entirely, as it doesn't support extended and UNC path formats, but that's not so hard to overcome:

public static Uri FileUrlFromPath(string path)
{
    const string prefix = @"\\";
    const string extended = @"\\?\";
    const string extendedUnc = @"\\?\UNC\";
    const string device = @"\\.\";
    const StringComparison comp = StringComparison.Ordinal;

    if(path.StartsWith(extendedUnc, comp))
    {
        path = prefix+path.Substring(extendedUnc.Length);
    }else if(path.StartsWith(extended, comp))
    {
        path = prefix+path.Substring(extended.Length);
    }else if(path.StartsWith(device, comp))
    {
        path = prefix+path.Substring(device.Length);
    }

    int len = 1;
    var buffer = new StringBuilder(len);
    int result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(len == 1) Marshal.ThrowExceptionForHR(result);

    buffer.EnsureCapacity(len);
    result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(result == 1) throw new ArgumentException("Argument is not a valid path.", "path");
    Marshal.ThrowExceptionForHR(result);
    return new Uri(buffer.ToString());
}

[DllImport("shlwapi.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int UrlCreateFromPath(string path, StringBuilder url, ref int urlLength, int reserved);

In case the path starts with with a special prefix, it gets removed. Although the documentation doesn't mention it, the function outputs the length of the URL even if the buffer is smaller, so I first obtain the length and then allocate the buffer.

Some very interesting observation I had is that while "\\device\path" is correctly transformed to "file://device/path", specifically "\\localhost\path" is transformed to just "file:///path".

The WinApi function managed to encode special characters, but leaves Unicode-specific characters unencoded, unlike the Uri construtor. In that case, AbsoluteUri contains the properly encoded URL, while OriginalString can be used to retain the Unicode characters.

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

How to set environment variables from within package.json?

UPDATE: This changes in npm v7 due to npm RFC 21.


npm (and yarn) passes a lot of data from package.json into scripts as environment variables. Use npm run env to see them all. This is documented in https://docs.npmjs.com/misc/scripts#environment and is not only for "lifecycle" scripts like prepublish but also any script executed by npm run.

You can access these inside code (e.g. process.env.npm_package_config_port in JS) but they're already available to the shell running the scripts so you can also access them as $npm_... expansions in the "scripts" (unix syntax, might not work on windows?).

The "config" section seems intended for this use:

  "name": "myproject",
  ...
  "config": {
    "port": "8010"
  },
  "scripts": {
    "start": "node server.js $npm_package_config_port",
    "test": "wait-on http://localhost:$npm_package_config_port/ && node test.js http://localhost:$npm_package_config_port/"
  } 

An important quality of these "config" fields is that users can override them without modifying package.json!

$ npm run start

> [email protected] start /home/cben/mydir
> node server.js $npm_package_config_port

Serving on localhost:8010

$ npm config set myproject:port 8020
$ git diff package.json  # no change!
$ cat ~/.npmrc
myproject:port=8020

$ npm run start

> [email protected] start /home/cben/mydir
> node server.js $npm_package_config_port

Serving on localhost:8020

See npm config and yarn config docs.
It appears that yarn reads ~/.npmrc so npm config set affects both, but yarn config set writes to ~/.yarnrc, so only yarn will see it :-(

Right query to get the current number of connections in a PostgreSQL DB

Number of TCP connections will help you. Remember that it is not for a particular database

netstat -a -n | find /c "127.0.0.1:13306"

How can I prevent the backspace key from navigating back?

Not sure why no-one's just answered this - seems like a perfectly reasonable technical question to ask whether it's possible.

No, I don't think there's a cross-browser way to disable the backspace button. I know it's not enabled by default in FF these days though.

How to insert array of data into mysql using php

if(is_array($EMailArr)){
    foreach($EMailArr as $key => $value){

    $R_ID = (int) $value['R_ID'];
    $email = mysql_real_escape_string( $value['email'] );
    $name = mysql_real_escape_string( $value['name'] );

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
    mysql_query($sql) or exit(mysql_error()); 
    }
}

A better example solution with PDO:

 $q = $sql->prepare("INSERT INTO `email_list` 
                     SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");

 foreach($EMailArr as $value){
   $q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
 }

Remove Top Line of Text File with PowerShell

I just learned from a website:

Get-ChildItem *.txt | ForEach-Object { (get-Content $_) | Where-Object {(1) -notcontains $_.ReadCount } | Set-Content -path $_ }

Or you can use the aliases to make it short, like:

gci *.txt | % { (gc $_) | ? { (1) -notcontains $_.ReadCount } | sc -path $_ }

How to avoid 'undefined index' errors?

Same idea as Michael Waterfall

From CodeIgniter

// Lets you determine whether an array index is set and whether it has a value.
// If the element is empty it returns FALSE (or whatever you specify as the default value.)
function element($item, $array, $default = FALSE)
{
    if ( ! isset($array[$item]) OR $array[$item] == "")
    {
        return $default;
    }

    return $array[$item];
}

XSLT string replace

replace isn't available for XSLT 1.0.

Codesling has a template for string-replace you can use as a substitute for the function:

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

invoked as:

<xsl:variable name="newtext">
    <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="$text" />
        <xsl:with-param name="replace" select="a" />
        <xsl:with-param name="by" select="b" />
    </xsl:call-template>
</xsl:variable>

On the other hand, if you literally only need to replace one character with another, you can call translate which has a similar signature. Something like this should work fine:

<xsl:variable name="newtext" select="translate($text,'a','b')"/>

Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo like you had in your original code.

How do I install Python libraries in wheel format?

For windows, there are automatic installer packages available at this site

It includes most of the python packages.

But the best way for it is of course using pip.

How do I pass a variable to the layout using Laravel' Blade templating?

class PagesController extends BaseController {
    protected $layout = 'layouts.master';

    public function index()
    {
        $this->layout->title = "Home page";
        $this->layout->content = View::make('pages/index');
    }
}

At the Blade Template file, REMEMBER to use @ in front the variable.

...
<title>{{ $title or '' }}</title>
...
@yield('content')
...

How to create query parameters in Javascript?

This thread points to some code for escaping URLs in php. There's escape() and unescape() which will do most of the work, but the you need add a couple extra things.

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function urldecode(str) {
str = str.replace('+', ' ');
str = unescape(str);
return str;
}

Hibernate: "Field 'id' doesn't have a default value"

The same exception was thrown if a DB table had an old unremoved column.

For example: attribute_id NOT NULL BIGINT(20), and attributeId NOT NULL BIGINT(20),

After removing the not used attribute, in my case contractId, the problem was resolved.

How can I send and receive WebSocket messages on the server side?

C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Execute Stored Procedure from a Function

Here is another possible workaround:

if exists (select * from master..sysservers where srvname = 'loopback')
    exec sp_dropserver 'loopback'
go
exec sp_addlinkedserver @server = N'loopback', @srvproduct = N'', @provider = N'SQLOLEDB', @datasrc = @@servername
go

create function testit()
    returns int
as
begin
    declare @res int;
    select @res=count(*) from openquery(loopback, 'exec sp_who');
    return @res
end
go

select dbo.testit()

It's not so scary as xp_cmdshell but also has too many implications for practical use.

Tracing XML request/responses with JAX-WS

am I correct in understanding that you want to change/access the raw XML message?

If so, you (or since this is five years old, the next guy) might want to have a look at the Provider interface that is part of the JAXWS. The client counterpart is done using the "Dispatch" class. Anyway, you don't have to add handlers or interceptors. You still CAN, of course. The downside is this way, you are COMPLETELY responsible for building the SOAPMessage, but its easy, and if that's what you want(like I did) this is perfect.

Here is an example for the server side(bit clumsy, it was just for experimenting)-

@WebServiceProvider(portName="Provider1Port",serviceName="Provider1",targetNamespace = "http://localhost:8123/SoapContext/SoapPort1")
@ServiceMode(value=Service.Mode.MESSAGE)
public class Provider1 implements Provider<SOAPMessage>
{
  public Provider1()
  {
  }

  public SOAPMessage invoke(SOAPMessage request)
  { try{


        File log= new File("/home/aneeshb/practiceinapachecxf/log.txt");//creates file object
        FileWriter fw=new FileWriter(log);//creates filewriter and actually creates file on disk

            fw.write("Provider has been invoked");
            fw.write("This is the request"+request.getSOAPBody().getTextContent());

      MessageFactory mf = MessageFactory.newInstance();
      SOAPFactory sf = SOAPFactory.newInstance();

      SOAPMessage response = mf.createMessage();
      SOAPBody respBody = response.getSOAPBody();
      Name bodyName = sf.createName("Provider1Insertedmainbody");
      respBody.addBodyElement(bodyName);
      SOAPElement respContent = respBody.addChildElement("provider1");
      respContent.setValue("123.00");
      response.saveChanges();
      fw.write("This is the response"+response.getSOAPBody().getTextContent());
      fw.close();
      return response;}catch(Exception e){return request;}


   }
}

You publish it like you would an SEI,

public class ServerJSFB {

    protected ServerJSFB() throws Exception {
        System.out.println("Starting Server");
        System.out.println("Starting SoapService1");

        Object implementor = new Provider1();//create implementor
        String address = "http://localhost:8123/SoapContext/SoapPort1";

        JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();//create serverfactorybean

        svrFactory.setAddress(address);
        svrFactory.setServiceBean(implementor);

        svrFactory.create();//create the server. equivalent to publishing the endpoint
        System.out.println("Starting SoapService1");
  }

public static void main(String args[]) throws Exception {
    new ServerJSFB();
    System.out.println("Server ready...");

    Thread.sleep(10 * 60 * 1000);
    System.out.println("Server exiting");
    System.exit(0);
}
}

Or you can use an Endpoint class for it. Hope that has been helpful.

And oh, if you want you needn't deal with headers and stuff, if you change the service mode to PAYLOAD(You'll only get the Soap Body).

How do you comment out code in PowerShell?

In PowerShell V1 there's only # to make the text after it a comment.

# This is a comment in Powershell

In PowerShell V2 <# #> can be used for block comments and more specifically for help comments.

#REQUIRES -Version 2.0

<#
.SYNOPSIS
    A brief description of the function or script. This keyword can be used
    only once in each topic.
.DESCRIPTION
    A detailed description of the function or script. This keyword can be
    used only once in each topic.
.NOTES
    File Name      : xxxx.ps1
    Author         : J.P. Blanc ([email protected])
    Prerequisite   : PowerShell V2 over Vista and upper.
    Copyright 2011 - Jean Paul Blanc/Silogix
.LINK
    Script posted over:
    http://silogix.fr
.EXAMPLE
    Example 1
.EXAMPLE
    Example 2
#>
Function blabla
{}

For more explanation about .SYNOPSIS and .* see about_Comment_Based_Help.

Remark: These function comments are used by the Get-Help CmdLet and can be put before the keyword Function, or inside the {} before or after the code itself.

Speed up rsync with Simultaneous/Concurrent File Transfers?

rsync transfers files as fast as it can over the network. For example, try using it to copy one large file that doesn't exist at all on the destination. That speed is the maximum speed rsync can transfer data. Compare it with the speed of scp (for example). rsync is even slower at raw transfer when the destination file exists, because both sides have to have a two-way chat about what parts of the file are changed, but pays for itself by identifying data that doesn't need to be transferred.

A simpler way to run rsync in parallel would be to use parallel. The command below would run up to 5 rsyncs in parallel, each one copying one directory. Be aware that the bottleneck might not be your network, but the speed of your CPUs and disks, and running things in parallel just makes them all slower, not faster.

run_rsync() {
    # e.g. copies /main/files/blah to /main/filesTest/blah
    rsync -av "$1" "/main/filesTest/${1#/main/files/}"
}
export -f run_rsync
parallel -j5 run_rsync ::: /main/files/*

Oracle: is there a tool to trace queries, like Profiler for sql server?

This is an Oracle doc explaining how to trace SQL queries, including a couple of tools (SQL Trace and tkprof)

link

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

_x000D_
_x000D_
var jsonstring='[{"ConnectionString":"aaaaaa","Server":"ssssss"}]';_x000D_
_x000D_
if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){_x000D_
_x000D_
document.write("valide json")_x000D_
_x000D_
}else{_x000D_
document.write("invalide json")_x000D_
}
_x000D_
_x000D_
_x000D_

How to read single Excel cell value

using Microsoft.Office.Interop.Excel;

string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;

//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();

wb.Close();

This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.

Rails create or update magic?

In Rails 4 you can add to a specific model:

def self.update_or_create(attributes)
  assign_or_new(attributes).save
end

def self.assign_or_new(attributes)
  obj = first || new
  obj.assign_attributes(attributes)
  obj
end

and use it like

User.where(email: "[email protected]").update_or_create(name: "Mr A Bbb")

Or if you'd prefer to add these methods to all models put in an initializer:

module ActiveRecordExtras
  module Relation
    extend ActiveSupport::Concern

    module ClassMethods
      def update_or_create(attributes)
        assign_or_new(attributes).save
      end

      def update_or_create!(attributes)
        assign_or_new(attributes).save!
      end

      def assign_or_new(attributes)
        obj = first || new
        obj.assign_attributes(attributes)
        obj
      end
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecordExtras::Relation

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Iterating through list of list in Python

So wait, this is just a list-within-a-list?

The easiest way is probably just to use nested for loops:

>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
...     for number in list:
...         print number
...
1
3
4
2
4
4
3
4
5

Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.

Also, for performance reasons, you might want to look at using list comprehensions to do this:

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions

How to get the number of threads in a Java process

java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

Where is the Docker daemon log?

Docker for Mac (Beta)

~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log

Convert string to ASCII value python

Here is a pretty concise way to perform the concatenation:

>>> s = "hello world"
>>> ''.join(str(ord(c)) for c in s)
'10410110810811132119111114108100'

And a sort of fun alternative:

>>> '%d'*len(s) % tuple(map(ord, s))
'10410110810811132119111114108100'

How to display gpg key details without importing it?

The option --list-packets parses pgp data from a file and outputs its structure - in a very technical way, though. When parsing a public key, you can easily extract the user ids and the key ids of the signatures.

Be wary that this command only parses the data format, it does no validation of signatures or similar things.

FirebaseInstanceIdService is deprecated

FirebaseinstanceIdService is deprecated. So have to use "FirebaseMessagingService"

Sea the image please:

enter image description here

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}

Why when I transfer a file through SFTP, it takes longer than FTP?

For comparison, I tried transfering a 299GB ntfs disk image from an i5 laptop running Raring Ringtail Ubuntu alpha 2 live cd to an i7 desktop running Ubuntu 12.04.1. Reported speeds:

over wifi + powerline: scp: 5MB/sec (40 Mbit/sec)

over gigabit ethernet + netgear G5608 v3:

scp: 44MB/sec

sftp: 47MB/sec

sftp -C: 13MB/sec

So, over a good gigabit link, sftp is slightly faster than scp, 2010-era fast CPUs seem fast enough to encrypt, but compression isn't a win in all cases.

Over a bad gigabit ethernet link, though, I've had sftp far outperform scp. Something about scp being very chatty, see "scp UNBELIEVABLY slow" on comp.security.ssh from 2008: https://groups.google.com/forum/?fromgroups=#!topic/comp.security.ssh/ldPV3msFFQw http://fixunix.com/ssh/368694-scp-unbelievably-slow.html

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07"), the Java SE Runtime Environment version ("build 1.6.0_07-b06"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"). I suspect the "11.0" you are seeing is the HotSpot version.

Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.

"Object doesn't support this property or method" error in IE11

We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:

  1. Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>

  2. Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />

NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.

How to use the pass statement?

The best and most accurate way to think of pass is as a way to explicitly tell the interpreter to do nothing. In the same way the following code:

def foo(x,y):
    return x+y

means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result",

def bar():
    pass

means "If I call the function bar(), do absolutely nothing."

The other answers are quite correct, but it's also useful for a few things that don't involve place-holding.

For example, in a bit of code I worked on just recently, it was necessary to divide two variables, and it was possible for the divisor to be zero.

c = a / b

will, obviously, produce a ZeroDivisionError if b is zero. In this particular situation, leaving c as zero was the desired behavior in the case that b was zero, so I used the following code:

try:
    c = a / b
except ZeroDivisionError:
    pass

Another, less standard usage is as a handy place to put a breakpoint for your debugger. For example, I wanted a bit of code to break into the debugger on the 20th iteration of a for... in statement. So:

for t in range(25):
    do_a_thing(t)
    if t == 20:
        pass

with the breakpoint on pass.

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

Example:

@Component({
    selector: 'widget-three',
    template: `<input #input1 type="text">`
})
export class WidgetThree{
    @ViewChild('input1') input1;

    constructor(private renderer:Renderer){}

    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input1.nativeElement,
            'focus',
            []
        )
    }
}

How to check SQL Server version

select charindex(  'Express',@@version)

if this value is 0 is not a express edition

I cannot start SQL Server browser

I'm trying to setup rf online game to be played offline using MS SQL server 2019 and ended up with the same problem. The SQL Browser service won't start. Almost all answers in this post have been tried but the outcome is disappointing. I've got a weird idea to try start the SQL browser service manually and then change it to automatic after it runs. Luckily it works. So, just simply right click on SQL Server Browser ==> Properties ==>Service==>Start Mode==>Manual. After apply the changes right click on the SQL Server Browser again and start the service. After the service run change the start mode to automatic. Make sure the information provided on log on as: are correct.

Get unique values from a list in python

I am surprised that nobody so far has given a direct order-preserving answer:

def unique(sequence):
    """Generate unique items from sequence in the order of first occurrence."""
    seen = set()
    for value in sequence:
        if value in seen:
            continue

        seen.add(value)

        yield value

It will generate the values so it works with more than just lists, e.g. unique(range(10)). To get a list, just call list(unique(sequence)), like this:

>>> list(unique([u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']))
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

It has the requirement that each item is hashable and not just comparable, but most stuff in Python is and it is O(n) and not O(n^2), so will work just fine with a long list.

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

Answers didn't help me to solve my problem, I couldn't find (and browse) the assemblies although I installed them using Microsoft's msi installer. For me, the excel assembly is located under C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

CocoaPods Errors on Project Build

TLDR: This is most likely a bug with Xcode and closing and reopening the project is usually the simplest fix. Assuming everything else is configured properly.


I occasionally get the same error when deleting the Pods directory and then running pod install.

Everything appears correct in the project info:

enter image description here

However, when I go to the target's User-Defined Build Settings, the PODS_ROOT entry is either entirely missing or is empty for one or more configurations. Which causes the following error on build:

enter image description here

The simplest fix is to close the project in Xcode and reopen it.

If you go to the target's Build Settings and filter on All, you will now see the PODS_ROOT entry with no errors:

enter image description here

It should now build with no errors.


Note: Even Cocoa Pods' official AFNetworking iOS Example has this problem, which leads me to believe that it is a bug with Xcode.

An alternative fix is to manually change the configuration to None, then back to its original value:

enter image description here

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

How can I invert color using CSS?

Here is a different approach using mix-blend-mode: difference, that will actually invert whatever the background is, not just a single colour:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
  color: white;_x000D_
  mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

Open a facebook link by native Facebook app on iOS

swift 3

if let url = URL(string: "fb://profile/<id>") {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:],completionHandler: { (success) in
                print("Open fb://profile/<id>: \(success)")
            })
        } else {
            let success = UIApplication.shared.openURL(url)
            print("Open fb://profile/<id>: \(success)")
        }
 }

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Bootstrap : TypeError: $(...).modal is not a function

I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using

$('#button').on('click',function(){ $('#myModal').modal(); });

myModal is the id of Bootstrap modal and you have to give a click event to a button when you call click that button a pop up modal will be displayed.

VideoView Full screen in android application

This code is for full screen landscape video

AndroidManifext.xml (Setting the orientation)

        <activity
        android:name=".Video1"
        android:screenOrientation="landscape" />

Video1.java Code :

import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;

public class Video1 extends AppCompatActivity {

private VideoView videoView;
private MediaController mediaController;

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

    videoView = findViewById(R.id.videoView);
    String fullScreen =  getIntent().getStringExtra("fullScreenInd");
    if("y".equals(fullScreen)){
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getSupportActionBar().hide();
    }

    Uri videoUri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.YOUR_VIDEO_NAME);

    videoView.setVideoURI(videoUri);

    mediaController = new FullScreenMediaController(this);
    mediaController.setAnchorView(videoView);

    videoView.setMediaController(mediaController);
    videoView.start();
    }
}

FullScreenMediaControler.java Code :

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController;

public class FullScreenMediaController extends MediaController {

private ImageButton fullScreen;
private String isFullScreen;

public FullScreenMediaController(Context context) {
    super(context);
}

@Override
public void setAnchorView(View view) {

    super.setAnchorView(view);

    //image button for full screen to be added to media controller
    fullScreen = new ImageButton (super.getContext());

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.RIGHT;
    params.rightMargin = 80;
    addView(fullScreen, params);

    //fullscreen indicator from intent
    isFullScreen =  ((Activity)getContext()).getIntent().
            getStringExtra("fullScreenInd");

    if("y".equals(isFullScreen)){
        fullScreen.setImageResource(R.drawable.ic_fullscreen_exit);
    }else{
        fullScreen.setImageResource(R.drawable.ic_fullscreen);
    }

    //add listener to image button to handle full screen and exit full screen events
    fullScreen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getContext(),Video1.class);

            if("y".equals(isFullScreen)){
                intent.putExtra("fullScreenInd", "");
            }else{
                intent.putExtra("fullScreenInd", "y");
            }
            ((Activity)getContext()).startActivity(intent);
        }
    });
  }
}

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

REST response code for invalid data

It is amusing to return 418 I'm a teapot to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.

2.3.2 418 I'm a teapot

Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.

To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.

In Javascript, how to conditionally add a member to an object?

Define a var by let and just assign new property

let msg = {
    to: "[email protected]",
    from: "[email protected]",
    subject: "Contact form",    
};

if (file_uploaded_in_form) { // the condition goes here
    msg.attachments = [ // here 'attachments' is the new property added to msg Javascript object
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ];
}

Now the msg become

{
    to: "[email protected]",
    from: "[email protected]",
    subject: "Contact form",
    attachments: [
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ]
}

In my opinion this is very simple and easy solution.

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

Note- position really matters add google() before jcenter()

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

Remove all elements contained in another array

If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.

You could also make this more generic by allowing non-object matching and / or multi-property value matching.

/**
 *
 * @param arr1 The initial array
 * @param arr2 The array to remove
 * @param propertyName the key of the object to match on
 */
function differenceByPropVal<T>(arr1: T[], arr2: T[], propertyName: string): T[] {
  return arr1.filter(
    (a: T): boolean =>
      !arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
  );
}

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

<select class="dropdownmenu" name="drop-down">
    <option class="dropdownmenu_list1" value="select-option">Choose ...</option>
    <option class="dropdownmenu_list2" value="Topic 1">Option 1</option>
    <option class="dropdownmenu_list3" value="Topic 2">Option 2</option>
</select>

This works best in Firefox. Too bad that Chrome and Safari do not support this rather easy CSS styling.

Cannot assign requested address using ServerSocket.socketBind

I came across this error when copying configurations from one server to another.

I had the old host's hostname in my ${JETTY_BASE}/start.ini jetty.host property. Setting the correct jetty.host property value solved the issue for me.

Hope this helps someone in the future who has to work on multiple servers at once.

Git Bash won't run my python files?

When you install python for windows, there is an option to include it in the path. For python 2 this is not the default. It adds the python installation folder and script folder to the Windows path. When starting the GIT Bash command prompt, it have included it in the linux PATH variable.

If you start the python installation again, you should select the option Change python and in the next step you can "Add python.exe to Path". Next time you open GIT Bash, the path is correct.

Styling twitter bootstrap buttons

Here is a good resource: http://charliepark.org/bootstrap_buttons/

You can change color and see the effect in action.

How to print the current time in a Batch-File?

You can use the command time /t for the time and date /t for the date, here is an example:

@echo off
time /t >%tmp%\time.tmp
date /t >%tmp%\date.tmp
set ttime=<%tmp%\time.tmp
set tdate=<%tmp%\date.tmp
del /f /q %tmp%\time.tmp
del /f /q %tmp%\date.tmp
echo Time: %ttime%
echo Date: %tdate%
pause >nul

You can also use the built in variables %time% and %date%, here is another example:

@echo off
echo Time: %time:~0,5%
echo Date: %date%
pause >nul

How to ignore user's time zone and force Date() use specific time zone

Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser). Then just add the needed number of milliseconds to it.

_x000D_
_x000D_
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );_x000D_
_date.setUTCMilliseconds(1270544790922);_x000D_
_x000D_
alert(_date); //date shown shifted corresponding to local time settings_x000D_
alert(_date.getUTCFullYear());    //the UTC year value_x000D_
alert(_date.getUTCMonth());       //the UTC month value_x000D_
alert(_date.getUTCDate());        //the UTC day of month value_x000D_
alert(_date.getUTCHours());       //the UTC hour value_x000D_
alert(_date.getUTCMinutes());     //the UTC minutes value
_x000D_
_x000D_
_x000D_

Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings. Otherwise date values will be shifted corresponding to local time settings.

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

How to SFTP with PHP?

I found that "phpseclib" should help you with this (SFTP and many more features). http://phpseclib.sourceforge.net/

To Put the file to the server, simply call (Code example from http://phpseclib.sourceforge.net/sftp/examples.html#put)

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);

How to test if a double is an integer

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()

Easiest way to read/write a file's content in Python

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

Make index.html default, but allow index.php to be visited if typed in

If you're using WordPress, there is now a filter hook to resolve this:

remove_filter('template_redirect', 'redirect_canonical'); 

(Put this in your theme's functions.php)

This tells WordPress to not redirect index.php back to the root page, but to sit where it is. That way, index.html can be assigned to be the default page in .htaccess and can work alongside index.php.

How to specify new GCC path for CMake

This not only works with cmake, but also with ./configure and make:

./configure CC=/usr/local/bin/gcc CXX=/usr/local/bin/g++

Which is resulting in:

checking for gcc... /usr/local/bin/gcc
checking whether the C compiler works... yes

Best practices for Storyboard login screen, handling clearing of data upon logout

Here is what I ended up doing to accomplish everything. The only thing you need to consider in addition to this is (a) the login process and (b) where you are storing your app data (in this case, I used a singleton).

Storyboard showing login view controller and main tab controller

As you can see, the root view controller is my Main Tab Controller. I did this because after the user has logged in, I want the app to launch directly to the first tab. (This avoids any "flicker" where the login view shows temporarily.)

AppDelegate.m

In this file, I check whether the user is already logged in. If not, I push the login view controller. I also handle the logout process, where I clear data and show the login view.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Show login view if not logged in already
    if(![AppData isLoggedIn]) {
        [self showLoginScreen:NO];
    }

    return YES;
}

-(void) showLoginScreen:(BOOL)animated
{

    // Get login screen from storyboard and present it
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginViewController *viewController = (LoginViewController *)[storyboard instantiateViewControllerWithIdentifier:@"loginScreen"];
    [self.window makeKeyAndVisible];
    [self.window.rootViewController presentViewController:viewController
                                             animated:animated
                                           completion:nil];
}

-(void) logout
{
    // Remove data from singleton (where all my app data is stored)
    [AppData clearData];

   // Reset view controller (this will quickly clear all the views)
   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
   MainTabControllerViewController *viewController = (MainTabControllerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"mainView"];
   [self.window setRootViewController:viewController];

   // Show login screen
   [self showLoginScreen:NO];

}

LoginViewController.m

Here, if the login is successful, I simply dismiss the view and send a notification.

-(void) loginWasSuccessful
{

     // Send notification
     [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessful" object:self];

     // Dismiss login screen
     [self dismissViewControllerAnimated:YES completion:nil];

}

Changing capitalization of filenames in Git

To bulk git mv files to lowercase on macOS:

for f in *; do git mv "$f" "`echo $f | tr "[:upper:]" "[:lower:]"`"; done

It will lowercase all files in a folder.

Javascript - Open a given URL in a new tab by clicking a button

Use window.open instead of window.location to open a new window or tab (depending on browser settings).

Your fiddle does not work because there is no button element to select. Try input[type=button] or give the button an id and use #buttonId.

Using jQuery how to get click coordinates on the target element

If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.

The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.

$("#seek-bar").click(function(event) {
  var x = event.offsetX
  alert(x);    
});

Cannot install packages using node package manager in Ubuntu

for me problem was solved by,

sudo apt-get remove node
sudo apt-get remove nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
alias node=nodejs
rm -r /usr/local/lib/python2.7/dist-packages/localstack/node_modules
npm install -g npm@latest || sudo npm install -g npm@latest

Python math module

In

from math import sqrt

Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".

Ansible: filter a list by its attributes

Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:

- debug:
    msg: "{% for address in network.addresses.private_man %}\
        {% if address.type == 'fixed' %}\
          {{ address.addr }}\
        {% endif %}\
      {% endfor %}"

Or if you prefer to put it all on one line:

- debug:
    msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"

Which returns:

ok: [localhost] => {
    "msg": "172.16.1.100"
}

C# Telnet Library

I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.

** Unique in this instance can be validly interpreted as brain-dead.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

SQL changing a value to upper or lower case

LCASE or UCASE respectively.

Example:

SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/

Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.

 import numpy as np
 s = pd.Series(['apple', np.nan, 'banana'])
 s.apply(lambda x: x!=x)
 out[252]
 0    False
 1     True
 2    False
 dtype: bool

Export to xls using angularjs

Try below with customised file name:

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

          var table = document.getElementById("searchResult");
          var filters = $('.ng-table-filters').remove();
          var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
          $('.ng-table-sort-header').after(filters) ;          
          var url = uri + base64(format(template, ctx));
          var a = document.createElement('a');
          a.href = url;
          a.download = 'Exported_Table.xls';
          a.click();        
};

How can I remove time from date with Moment.js?

Look at these Examples.

Format Dates

moment().format('MMMM Do YYYY, h:mm:ss a'); // December 7th 2020, 9:58:18 am
moment().format('dddd');                    // Monday
moment().format("MMM Do YY");               // Dec 7th 20
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020
moment().format();                          // 2020-12-07T09:58:18+05:30

Relative Time

moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 8 years ago
moment().startOf('day').fromNow();        // 10 hours ago
moment().endOf('day').fromNow();          // in 14 hours
moment().startOf('hour').fromNow();       // an hour ago

Calendar Time

moment().subtract(10, 'days').calendar(); // 11/27/2020
moment().subtract(6, 'days').calendar();  // Last Tuesday at 9:58 AM
moment().subtract(3, 'days').calendar();  // Last Friday at 9:58 AM
moment().subtract(1, 'days').calendar();  // Yesterday at 9:58 AM
moment().calendar();                      // Today at 9:58 AM
moment().add(1, 'days').calendar();       // Tomorrow at 9:58 AM
moment().add(3, 'days').calendar();       // Thursday at 9:58 AM
moment().add(10, 'days').calendar();      // 12/17/2020

Multiple Locale Support

moment.locale();         // en
moment().format('LT');   // 9:58 AM
moment().format('LTS');  // 9:58:18 AM
moment().format('L');    // 12/07/2020
moment().format('l');    // 12/7/2020
moment().format('LL');   // December 7, 2020
moment().format('ll');   // Dec 7, 2020
moment().format('LLL');  // December 7, 2020 9:58 AM
moment().format('lll');  // Dec 7, 2020 9:58 AM
moment().format('LLLL'); // Monday, December 7, 2020 9:58 AM
moment().format('llll'); // Mon, Dec 7, 2020 9:58 AM

How do you declare string constants in C?

If you want a "const string" like your question says, I would really go for the version you stated in your question:

/* first version */
const char *HELLO2 = "Howdy";

Particularly, I would avoid:

/* second version */
const char HELLO2[] = "Howdy";

Reason: The problem with second version is that compiler will make a copy of the entire string "Howdy", PLUS that string is modifiable (so not really const).

On the other hand, first version is a const string accessible by const pointer HELLO2, and there is no way anybody can modify it.

How to prevent user from typing in text field without disabling the field?

just use onkeydown="return false" to the control tag like shown below, it will not accept values from user.

    <asp:TextBox ID="txtDate" runat="server" AutoPostBack="True"
ontextchanged="txtDate_TextChanged" onkeydown="return false" >
    </asp:TextBox>

Python ValueError: too many values to unpack

self.materials is a dict and by default you are iterating over just the keys (which are strings).

Since self.materials has more than two keys*, they can't be unpacked into the tuple "k, m", hence the ValueError exception is raised.

In Python 2.x, to iterate over the keys and the values (the tuple "k, m"), we use self.materials.iteritems().

However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:

for m in self.materials.itervalues():

In Python 3.x, prefer dict.values() (which returns a dictionary view object):

for m in self.materials.values():

Bootstrap: align input with button

I tried above all and end-up with few changes which I would like to share. Here's the code which works for me (find the attached screenshot):

<div class="input-group">
    <input type="text" class="form-control" placeholder="Search text">
    <span class="input-group-btn" style="width:0;">
        <button class="btn btn-default" type="button">Go!</button>
    </span>
</div>

enter image description here

If you want to see it working, just use below code in you editor:

<html>
    <head>
        <link type='text/css' rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' />
    </head>
    <body>
        <div class="container body-content">
            <div class="form-horizontal">
              <div class="input-group">
                  <input type="text" class="form-control" placeholder="Search text">
                  <span class="input-group-btn" style="width:0;">
                      <button class="btn btn-default" type="button">Go!</button>
                  </span>
              </div>
            </div>
        </div>
    </body>
</html>

Hope this helps.

Why can't I make a vector of references?

yes you can, look for std::reference_wrapper, that mimics a reference but is assignable and also can be "reseated"

Combine [NgStyle] With Condition (if..else)

Trying to set background color based on condition:   

Consider variable x with some numeric value.    
<p [ngStyle]="{ backgroundColor: x > 4 ? 'lightblue' : 'transparent' }">
        This is a sample Text
</p>

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Send PHP variable to javascript function

You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.

<script type="text/javascript">
    // Do something in JavaScript
    var x = <?php echo $calculatedValue; ?>;
    // etc..
</script>

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the default username and password in Tomcat?

For Window 7, Netbeans 8.0.2 , Apache Tomcat 8.0.15
C:\Users\JONATHAN\AppData\Roaming\NetBeans\8.0.2\apache-tomcat-8.0.15.0_base\conf\tomcat-users.xml
The Tomcat Manager Username and password is like below pic..
tomcat-users.xml

Where are static variables stored in C and C++?

Well this question is bit too old, but since nobody points out any useful information: Check the post by 'mohit12379' explaining the store of static variables with same name in the symbol table: http://www.geekinterview.com/question_details/24745

Pretty-print an entire Pandas Series / DataFrame

If you are using Ipython Notebook (Jupyter). You can use HTML

from IPython.core.display import HTML
display(HTML(df.to_html()))

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

SQL Plus change current directory

I don't think that you can change the directory in SQL*Plus.

Instead of changing directory, you can use @@filename, which reads in another script whose location is relative to the directory the current script is running in. For example, if you have two scripts

C:\Foo\Bar\script1.sql
C:\Foo\Bar\Baz\script2.sql

then script1.sql can run script2.sql if it contains the line

@@Baz\script2.sql

See this for more info about @@.

How to check if JavaScript object is JSON

I combine the typeof operator with a check of the constructor attribute (by Peter):

var typeOf = function(object) {
    var firstShot = typeof object;
    if (firstShot !== 'object') {
        return firstShot;
    } 
    else if (object.constructor === [].constructor) {
        return 'array';
    }
    else if (object.constructor === {}.constructor) {
        return 'object';
    }
    else if (object === null) {
        return 'null';
    }
    else {
        return 'don\'t know';
    } 
}

// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];

console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
    console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});

Result:

typeOf()    input parameter
---------------------------
boolean     true
boolean     false
number      1
number      2.3
string      "string"
array       [4,5,6]
object      {"foo":"bar"}
null        null
undefined       

HTML image not showing in Gmail

My issue was similar. This is what my experience has been on testing the IMG tag on gmail (assuming most of the organization's would have a dev qa and prod server.)

I had to send emails to customers on their personal email id's and we could see that gmail would add something of its own like following to src attribute of img tag. Now when we were sending these images from our dev environment they would never render on gmail and we were always curious why?

https://ci7.googleusercontent.com/proxy/AEF54znasdUhUYhuHuHuhHkHfT7u2w5zsOnWJ7k1MwrKe8pP69hY9W9eo8_n6-tW0KdSIaG4qaBEbcXue74nbVBysdfqweAsNNmmmJyTB-JQzcgn1j=s0-d-e2-ft#https://www.prodserver.com/Folder1/Images/OurImage.PNG

so an image sent to my gmail id as following never worked for me

<img src="https://ci7.googleuser....Blah.Blah..https://devserver.com/Folder1/Images/OurImage.PNG">

and our dev server we can't render this image by hitting following URL on Chrome(or any browser).

https://www.devserver.com/folder1/folder2/myactualimage.jpg

now as long as the src has www on it worked all the time and we didnt had to add any other attributes.

<img src="https://www.**prodserver**.com/folder1/folder2/myactualimage.jpg">

How to get the onclick calling object?

The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){
  e = e || window.event;
  var src = e.target || e.srcElement;
  //src element is the eventsource
}

How do I overload the [] operator in C#

The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.

For example, in your case where an int is the key or index:

public int this[int index]
{
    get => GetValue(index);
}

You can also add a set accessor so that the indexer becomes read and write rather than just read-only.

public int this[int index]
{
    get => GetValue(index);
    set => SetValue(index, value);
}

If you want to index using a different type, you just change the signature of the indexer.

public int this[string index]
...

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

PreparedStatement IN clause alternatives?

I suppose you could (using basic string manipulation) generate the query string in the PreparedStatement to have a number of ?'s matching the number of items in your list.

Of course if you're doing that you're just a step away from generating a giant chained OR in your query, but without having the right number of ? in the query string, I don't see how else you can work around this.

What equivalents are there to TortoiseSVN, on Mac OSX?

My previous version of this answer had links, that kept becoming dead.
So, I've pointed it to the internet archive to preserve the original answer.

Subversion client releases for Windows and Macintosh

Wiki - Subversion clients comparison table

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

sudo: port: command not found

On my machine, port is in /opt/local/bin/port - try typing that into a terminal on its own.

Run Button is Disabled in Android Studio

My solution was to go to that multiselect button, then "Edit Configurations" -> Go to "+" and select the module (in this case it would be an app if you do not have a multiproject -> then apply and OK

Laravel Request getting current path with query string

Similar to Yada's answer: $request->url() will also work if you are injecting Illuminate\Http\Request

Edit: The difference between fullUrl and url is the fullUrl includes your query parameters