Programs & Examples On #Morse code

jquery find class and get the value

var myVar = $("#start").find('.myClass').first().val();

In Bootstrap 3,How to change the distance between rows in vertical?

UPDATE

Bootstrap 4 has spacing utilities to handle this https://getbootstrap.com/docs/4.0/utilities/spacing/

.mt-0 {
  margin-top: 0 !important;
}

--

ORIGINAL ANSWER

If you are using SASS, this is what I normally do.

$margins: (xs: 0.5rem, sm: 1rem, md: 1.5rem, lg: 2rem, xl: 2.5rem);

@each $name, $value in $margins {
  .margin-top-#{$name} {
    margin-top: $value;
  }

  .margin-bottom-#{$name} {
    margin-bottom: $value;
  }
}

so you can later use margin-top-xs for example

How do you automatically set the focus to a textbox when a web page loads?

You can do it easily by using jquery in this way:

<script type="text/javascript">

    $(document).ready(function () {
        $("#myTextBoxId").focus();
    });

</script>

by calling this function in $(document).ready().

It means this function will execute when the DOM is ready.

For more information about the READY function, refer to : http://api.jquery.com/ready/

HTTP response code for POST when resource already exists

Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.

To expand a little on Wrikken's answer, I think you could use either 409 Conflict or 403 Forbidden depending on the situation - in short, use a 403 error when the user can do absolutely nothing to resolve the conflict and complete the request (e.g. they can't send a DELETE request to explicitly remove the resource), or use 409 if something could possibly be done.

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Nowadays, someone says "403" and a permissions or authentication issue comes to mind, but the spec says that it's basically the server telling the client that it's not going to do it, don't ask it again, and here's why the client shouldn't.

As for PUT vs. POST... POST should be used to create a new instance of a resource when the user has no means to or shouldn't create an identifier for the resource. PUT is used when the resource's identity is known.

9.6 PUT

...

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,

it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

Time part of a DateTime Field in SQL

If you want only the hour of your datetime, then you can use DATEPART() - SQL Server:

declare @dt datetime
set @dt = '2012-09-10 08:25:53'

select datepart(hour, @dt) -- returns 8

In SQL Server 2008+ you can CAST() as time:

declare @dt datetime
set @dt = '2012-09-10 08:25:53'

select CAST(@dt as time) -- returns 08:25:53

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I've resolved it by creating .rvmrc file in my project folder containg:

rvm use <yourrubie>

then entering my project path

cd ~/myprojectpath

then I run

bundle install

Using fonts with Rails asset pipeline

I was having this problem on Rails 4.2 (with ruby 2.2.3) and had to edit the font-awesome _paths.scss partial to remove references to $fa-font-path and removing a leading forward slash. The following was broken:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

And the following works:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

An alternative would be to simply remove the forward slash following the interpolated $fa-font-path and then define $fa-font-path as an empty string or subdirectory with trailing forward slash (as needed).

Remember to recompile assets and restart your server as needed. For example, on a passenger setup:

prompt> rake assets:clean; rake assets:clobber
prompt> RAILS_ENV=production RAILS_GROUPS=assets rake assets:precompile
prompt> service passenger restart

Then reload your browser.

How can the Euclidean distance be calculated with NumPy?

The other answers work for floating point numbers, but do not correctly compute the distance for integer dtypes which are subject to overflow and underflow. Note that even scipy.distance.euclidean has this issue:

>>> a1 = np.array([1], dtype='uint8')
>>> a2 = np.array([2], dtype='uint8')
>>> a1 - a2
array([255], dtype=uint8)
>>> np.linalg.norm(a1 - a2)
255.0
>>> from scipy.spatial import distance
>>> distance.euclidean(a1, a2)
255.0

This is common, since many image libraries represent an image as an ndarray with dtype="uint8". This means that if you have a greyscale image which consists of very dark grey pixels (say all the pixels have color #000001) and you're diffing it against black image (#000000), you can end up with x-y consisting of 255 in all cells, which registers as the two images being very far apart from each other. For unsigned integer types (e.g. uint8), you can safely compute the distance in numpy as:

np.linalg.norm(np.maximum(x, y) - np.minimum(x, y))

For signed integer types, you can cast to a float first:

np.linalg.norm(x.astype("float") - y.astype("float"))

For image data specifically, you can use opencv's norm method:

import cv2
cv2.norm(x, y, cv2.NORM_L2)

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

enter image description here

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

Auto-fitting columns

Further study

What is the shortest function for reading a cookie by name in JavaScript?

Shorter, more reliable and more performant than the current best-voted answer:

const getCookieValue = (name) => (
  document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)

A performance comparison of various approaches is shown here:

http://jsperf.com/get-cookie-value-regex-vs-array-functions

Some notes on approach:

The regex approach is not only the fastest in most browsers, it yields the shortest function as well. Additionally it should be pointed out that according to the official spec (RFC 2109), the space after the semicolon which separates cookies in the document.cookie is optional and an argument could be made that it should not be relied upon. Additionally, whitespace is allowed before and after the equals sign (=) and an argument could be made that this potential whitespace should be factored into any reliable document.cookie parser. The regex above accounts for both of the above whitespace conditions.

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

Detecting Enter keypress on VB.NET

Private Sub SomeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles SomeTextBox.KeyPress

    If Asc(e.KeyChar) = 13 Then
         MessageBox.Show("Enter pressed!")
         e.Handled = True
    End If

End Sub

SQL MAX of multiple columns?

Please try using UNPIVOT:

SELECT MAX(MaxDt) MaxDt
   FROM tbl 
UNPIVOT
   (MaxDt FOR E IN 
      (Date1, Date2, Date3)
)AS unpvt;

How to Sort Multi-dimensional Array by Value?

Use array_multisort(), array_map()

array_multisort(array_map(function($element) {
      return $element['order'];
  }, $array), SORT_ASC, $array);

print_r($array);

DEMO

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

Image UriSource and Data Binding

You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

And the class property is simply this

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            image.EndInit();
        }
        catch{
            return DependencyProperty.UnsetValue;
        }

        return image;
    }
}

I suppose it may be a little more work than the value converter, but it is another option.

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

List comprehension vs map

I tried the code by @alex-martelli but found some discrepancies

python -mtimeit -s "xs=range(123456)" "map(hex, xs)"
1000000 loops, best of 5: 218 nsec per loop
python -mtimeit -s "xs=range(123456)" "[hex(x) for x in xs]"
10 loops, best of 5: 19.4 msec per loop

map takes the same amount of time even for very large ranges while using list comprehension takes a lot of time as is evident from my code. So apart from being considered "unpythonic", I have not faced any performance issues relating to usage of map.

Limit Get-ChildItem recursion depth

As of powershell 5.0, you can now use the -Depth parameter in Get-ChildItem!

You combine it with -Recurse to limit the recursion.

Get-ChildItem -Recurse -Depth 2

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

How do I automatically set the $DISPLAY variable for my current session?

do you use Bash? Go to the file .bashrc in your home directory and set the variable, then export it.

DISPLAY=localhost:0.0 ; export DISPLAY

you can use /etc/bashrc if you want to do it for all the users.

You may also want to look in ~/.bash_profile and /etc/profile

EDIT:

function get_xserver ()
{
    case $TERM in
       xterm )
            XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )    
            XSERVER=${XSERVER%%:*}
            ;;
        aterm | rxvt)           
            ;;
    esac  
}

if [ -z ${DISPLAY:=""} ]; then
    get_xserver
    if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || \
      ${XSERVER} == "unix" ]]; then 
        DISPLAY=":0.0"          # Display on local host.
    else
        DISPLAY=${XSERVER}:0.0  # Display on remote host.
    fi
fi

export DISPLAY

How can I list all of the files in a directory with Perl?

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

ReactJS SyntheticEvent stopPropagation() only works with React events?

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

Working JSFiddle with the fixes from below.

React Stop Propagation on jQuery Event

Use Event.stopImmediatePropagation to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
},
  • Caveat: Listeners are called in the order in which they are bound. React must be initialized before other code (jQuery here) for this to work.

jQuery Stop Propagation on React Event

Your jQuery code uses event delegation as well, which means calling stopPropagation in the handler is not stopping anything; the event has already propagated to document, and React's listener will be triggered.

// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){
    e.stopPropagation();
});

To prevent propagation beyond the element, the listener must be bound to the element itself:

// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){
    e.stopPropagation();
});

Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.

How do I read the first line of a file using cat?

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

Programmatically get the version number of a DLL

First of all, there are two possible 'versions' that you might be interested in:

  • Windows filesystem file version, applicable to all executable files

  • Assembly build version, which is embedded in a .NET assembly by the compiler (obviously only applicable to .NET assembly dll and exe files)

In the former case, you should use Ben Anderson's answer; in the latter case, use AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version, or Tataro's answer, in case the assembly is referenced by your code.

Note that you can ignore all the answers that use .Load()/.LoadFrom() methods, since these actually load the assembly in the current AppDomain - which is analogous to cutting down a tree to see how old it is.

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Horizontal line using HTML/CSS

I have try this my new code and it might be helpful to you, it works perfectly in google chromr

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How to show PIL images on the screen?

You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:

import Tkinter as tk
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
#window.geometry("500x500") # (optional)    
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()

For Python 3, replace import Tkinter as tk with import tkinter as tk.

Twitter Bootstrap - full width navbar

You can override some css

body {
    padding-left: 0px !important;
    padding-right: 0px !important;
}

.navbar-inner {
    border-radius: 0px !important;
}

The !important is needed just in case you link the bootstrap.css after your custom css.

And add your nav html out of a .container

How to add url parameters to Django template url tag?

Im not sure if im out of the subject, but i found solution for me; You have a class based view, and you want to have a get parameter as a template tag:

class MyView(DetailView):
    model = MyModel

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['tag_name'] = self.request.GET.get('get_parameter_name', None)
        return ctx

Then you make your get request /mysite/urlname?get_parameter_name='stuff.

In your template, when you insert {{ tag_name }}, you will have access to the get parameter value ('stuff'). If you have an url in your template that also needs this parameter, you can do

 {% url 'my_url' %}?get_parameter_name={{ tag_name }}"

You will not have to modify your url configuration

show more/Less text with just HTML and JavaScript

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                </div>
            </div>

SCRIPT:

    var showChar = 100;
    var ellipsestext = "[...]";
    $('.showmore').each(function () {
        $(this).find('.shorten_txt p').addClass('more_p').hide();
        $(this).find('.shorten_txt p:first').removeClass('more_p').show();
        $(this).find('.shorten_txt ul').addClass('more_p').hide();
        //you can do this above with every other element
        var teaser = $(this).find('.shorten_txt p:first').html();
        var con_length = parseInt(teaser.length);
        var c = teaser.substr(0, showChar);
        var h = teaser.substr(showChar, con_length - showChar);
        var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        if (con_length > showChar) {
            $(this).find(".shorten_txt p:first").html(html);
            $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
        }
    });
    $(".showmore").click(function () {
        if ($(this).hasClass("less")) {
            $(this).removeClass("less");
        } else {
            $(this).addClass("less");
        }
        $(this).find('.shorten_txt p:first span.moreelipses').toggle();
        $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
        $(this).find('.shorten_txt .more_p').toggle();
        return false;
    });

malloc an array of struct pointers

IMHO, this looks better:

Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`

for ( int i =0; i < SOME_VALUE; ++i )
{
    array[i] = (Chess) malloc(sizeof(Chess));
}

Displaying the Error Messages in Laravel after being Redirected from controller

If you want to load the view from the same controller you are on:

if ($validator->fails()) {
    return self::index($request)->withErrors($validator->errors());
}

And if you want to quickly display all errors but have a bit more control:

 @if ($errors->any())
     @foreach ($errors->all() as $error)
         <div>{{$error}}</div>
     @endforeach
 @endif

How to initialize/instantiate a custom UIView class with a XIB file in Swift

And this is the answer of Frederik on Swift 3.0

/*
 Usage:
 - make your CustomeView class and inherit from this one
 - in your Xib file make the file owner is your CustomeView class
 - *Important* the root view in your Xib file must be of type UIView
 - link all outlets to the file owner
 */
@IBDesignable
class NibLoadingView: UIView {

    @IBOutlet weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        nibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        nibSetup()
    }

    private func nibSetup() {
        backgroundColor = .clear

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.translatesAutoresizingMaskIntoConstraints = true

        addSubview(view)
    }

    private func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return nibView
    }
}

Table-level backup

A free app named SqlTableZip will get the job done. Basically, you write any query (which, of course can also be [select * from table]) and the app creates a compressed file with all the data, which can be restored later.

Link: http://www.doccolabs.com/products_sqltablezip.html

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I can also confirm this error.

Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.

That is done in three steps:

1 Install maven on local machine (the test-machine was Ubuntu 10.10)

mvn --version

Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"

2 Run maven externally link how to run maven from console

> cd path-to-pom.xml
> mvn test
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Simple
    [INFO]    task-segment: [test]
    [INFO] ------------------------------------------------------------------------
    [...]
    [INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running net.tverrbjelke.experiment.MainAppTest
    Hello World
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    [...]

3 inside m2eclipse: switch from embedded maven to local maven

  • find out where local maven home installation dir is (mvn --version, or google for your MAVEN_HOME, for me this helped me that is /usr/share/maven2 )
  • in eclipse Menu->Window->Preferences->Maven->Installation-> enter that string. Then you should have switched to your new external maven.
  • then run your Project as e.g. "maven test".

The error-message should be gone.

DBNull if statement

Consider:

if(rsData.Read()) {
  int index = rsData.GetOrdinal("columnName"); // I expect, just "ursrdaystime"
  if(rsData.IsDBNull(index)) {
     // is a null
  } else {
     // access the value via any of the rsData.Get*(index) methods
  }
} else {
  // no row returned
}

Also: you need more using ;p

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

PHP - Failed to open stream : No such file or directory

To add to the (really good) existing answer

Shared Hosting Software

open_basedir is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf) you cannot change that file directly because the hosting software will just overwrite it when it restarts.

With Plesk, they provide a place to override the provided httpd.conf called vhost.conf. Only the server admin can write this file. The configuration for Apache looks something like this

<Directory /var/www/vhosts/domain.com>
    <IfModule mod_php5.c>
        php_admin_flag engine on
        php_admin_flag safe_mode off
        php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
    </IfModule>
</Directory>

Have your server admin consult the manual for the hosting and web server software they use.

File Permissions

It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache, www-data or httpd (depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).

A lot of times people will solve a permissions problem by doing the following (Linux example)

chmod 777 /path/to/file

This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.

What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that

  1. That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below

     chown apache:apache /path/to/file
    
  2. The user, and only that user, has access. In Linux, a good practice would be chmod 600 (only owner can read and write) or chmod 644 (owner can write but everyone can read)

You can read a more extended discussion of Linux/Unix permissions and users here

How to convert NSData to byte array in iPhone?

Here's what I believe is the Swift equivalent:

if let data = NSData(contentsOfFile: filePath) {
   let length = data.length
   let byteData = malloc(length)
   memcmp(byteData, data.bytes, length)
}

How to send a pdf file directly to the printer using JavaScript?

There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
{
  var pdfFrame = window.frames["pdf"];
  pdfFrame.focus();
  pdfFrame.print();
}

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Try a different protocol. git:// may have problems from your firewall, for example; try a git clone with https: instead.

Java: Calling a super method which calls an overridden method

"this" keyword refers to current class reference. That means, when it is used inside the method, the 'current' class is still SubClass and so, the answer is explained.

Top 1 with a left join

Damir is correct,

Your subquery needs to ensure that dps_user.id equals um.profile_id, otherwise it will grab the top row which might, but probably not equal your id of 'u162231993'

Your query should look like this:

SELECT u.id, mbg.marker_value 
FROM dps_user u
LEFT JOIN 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE u.id = um.profile_id
     ORDER BY m.creation_date
    ) MBG ON MBG.profile_id=u.id 
WHERE u.id = 'u162231993'

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

Cosine Similarity between 2 Number Lists

You should try SciPy. It has a bunch of useful scientific routines for example, "routines for computing integrals numerically, solving differential equations, optimization, and sparse matrices." It uses the superfast optimized NumPy for its number crunching. See here for installing.

Note that spatial.distance.cosine computes the distance, and not the similarity. So, you must subtract the value from 1 to get the similarity.

from scipy import spatial

dataSetI = [3, 45, 7, 2]
dataSetII = [2, 54, 13, 15]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)

How to dump a dict to a json file?

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...

What is the "continue" keyword and how does it work in Java?

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

Saving an image in OpenCV

Sometimes the first call to cvQueryFrame() returns an empty image. Try:

IplImage *pSaveImg = cvQueryFrame(pCapturedImage);
pSaveImg = cvQueryFrame(pCapturedImage);

If that does not work, try to select capture device automatically:

CvCapture *pCapturedImage = cvCreateCameraCapture(-1);

Or you may try to select other capture devices where n=1,2,3...

CvCapture *pCapturedImage = cvCreateCameraCapture(n);

PS: Also I believe there is a misunderstanding about captured image looking at your variable name. The variable pCapturedImage is not an Image it is a Capture. You can always 'read' an image from capture.

How can I open a Shell inside a Vim Window?

Shougo's VimShell, which can auto-complete file names if used with neocomplcache

Show space, tab, CRLF characters in editor of Visual Studio

Display white space characters

Menu: You can toggle the visibility of the white space characters from the menu: Edit > Advanced > View White Space.

Button: If you want to add the button to a toolbar, it is called Toggle Visual Space in the command category "Edit".
The actual command name is: Edit.ViewWhiteSpace.

Keyboard Shortcut: In Visual Studio 2015, 2017 and 2019 the default keyboard shortcut still is CTRL+R, CTRL+W
Type one after the other.
All default shortcuts

End-of-line characters

Extension: There is a minimal extension adding the displaying of end-of-line characters (LF and CR) to the visual white space mode, as you would expect. Additionally it supplies buttons and short-cuts to modify all line-endings in a document, or a selection.
VisualStudio gallery: End of the Line

Note: Since Visual Studio 2017 there is no option in the File-menu called Advanced Save Options. Changing the encoding and line-endings for a file can be done using Save File As ... and clicking the down-arrow on the right side of the save-button. This shows the option Save with Encoding. You'll be asked permission to overwrite the current file.

node.js, socket.io with SSL

On the same note, if your server supports both http and https you can connect using:

var socket = io.connect('//localhost');

to auto detect the browser scheme and connect using http/https accordingly. when in https, the transport will be secured by default, as connecting using

var socket = io.connect('https://localhost');

will use secure web sockets - wss:// (the {secure: true} is redundant).

for more information on how to serve both http and https easily using the same node server check out this answer.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

The accepted answer to set git config core.filemode false, works, but with consequences. Setting core.filemode to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode back to true.

A less consequential alternative, if all the modified files should have mode 100755, is to do something like

chmod 100755 $(git ls-files --modified)

which just does exactly the change in mode, no more, no less, without additional implications.

(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode will hide it from me, which I don't want)

Twitter bootstrap 3 two columns full height

This was not mentioned here with offsetting.

You can use absolute to position for the left sidebar.

CSS

.sidebar-fixed{
  width: 16.66666667%;
  height: 100%;
}

HTML

<div class="row">
  <div class="sidebar-fixed">
    Side Bar
  </div>
  <div class="col-md-10 col-md-offset-2">
    CONTENT
  </div>
</div>

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

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

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

javac error: Class names are only accepted if annotation processing is explicitly requested

first download jdk from https://www.oracle.com/technetwork/java/javase/downloads/index.html. Then in search write Edit the System environment variables In open window i push bottom called Environment Variables Then in System variables enter image description here Push bottom new In field new variables write "Path" In field new value Write directory in folder bin in jdk like "C:\Program Files\Java\jdk1.8.0_191\bin" but in my OS work only this "C:\Program Files\Java\jdk1.8.0_191\bin\javac.exe" enter image description here press ok 3 times

Start Cmd. I push bottom windows + R. Then write cmd. In cmd write "cd (your directory with code )" looks like C:\Users\user\IdeaProjects\app\src. Then write "javac (name of your main class for your program).java" looks like blabla.java and javac create byte code like (name of your main class).class in your directory. last write in cmd "java (name of your main class)" and my program start work

CSS: Position loading indicator in the center of the screen

_x000D_
_x000D_
.loader{_x000D_
  position: fixed;_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 9999;_x000D_
  background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') _x000D_
              50% 50% no-repeat rgb(249,249,249);_x000D_
}
_x000D_
<div class="loader"></div>
_x000D_
_x000D_
_x000D_

Number of regex matches

If you know you will want all the matches, you could use the re.findall function. It will return a list of all the matches. Then you can just do len(result) for the number of matches.

Change button text from Xcode?

There is no need to add if{}else{} control flow. Initialise the button texts for different states at the View or ViewController constructor:

[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal];
[btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];

Then switch the button state to Selected:

[btnCheckButton setSelected:YES];

Then switch the button state to Normal:

[btnCheckButton setSelected:NO];

Converting a pointer into an integer

I'd say this is the modern C++ way.

#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);

EDIT:

The correct type to the the Integer

so the right way to store a pointer as an integer is to use the uintptr_t or intptr_t types. (See also in cppreference integer types for C99).

these types are defined in <stdint.h> for C99 and in the namespace std for C++11 in <cstdint> (see integer types for C++).

C++11 (and onwards) Version

#include <cstdint>
std::uintptr_t i;

C++03 Version

extern "C" {
#include <stdint.h>
}

uintptr_t i;

C99 Version

#include <stdint.h>
uintptr_t i;

The correct casting operator

In C there is only one cast and using the C cast in C++ is frowned upon (so don't use it in C++). In C++ there is different casts. reinterpret_cast is the correct cast for this conversion (See also here).

C++11 Version

auto i = reinterpret_cast<std::uintptr_t>(p);

C++03 Version

uintptr_t i = reinterpret_cast<uintptr_t>(p);

C Version

uintptr_t i = (uintptr_t)p; // C Version

Related Questions

Browser Caching of CSS files

That depends on what headers you are sending along with your CSS files. Check your server configuration as you are probably not sending them manually. Do a google search for "http caching" to learn about different caching options you can set. You can force the browser to download a fresh copy of the file everytime it loads it for instance, or you can cache the file for one week...

There is an error in XML document (1, 41)

Ensure your Message class looks like below:

[Serializable, XmlRoot("Message")]
public class Message
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

This works for me fine:

string xml = File.ReadAllText("c:\\Message.xml");
var result = DeserializeFromXml<Message>(xml);

MSDN, XmlRoot.ElementName:

The name of the XML root element that is generated and recognized in an XML-document instance. The default is the name of the serialized class.

So it might be your class name is not Message and this is why deserializer was not able find it using default behaviour.

member names cannot be the same as their enclosing type C#

The problem is with the method:

private void Flow()
{
    X = x;
    Y = y;
}

Your class is named Flow so this method can't also be named Flow. You will have to change the name of the Flow method to something else to make this code compile.

Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the void keyword to let the compiler know that your declaring a constructor.

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

Extending the User model with custom fields in Django

Currently as of Django 2.2, the recommended way when starting a new project is to create a custom user model that inherits from AbstractUser, then point AUTH_USER_MODEL to the model.

Source: https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project

Bash ignoring error for a particular command

Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs) : and just "do nothing". You'll save a few letters. :)

#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."

How to stop (and restart) the Rails Server?

In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line

How to linebreak an svg text within javascript?

use HTML instead of javascript

_x000D_
_x000D_
<html>_x000D_
  <head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
  <body>_x000D_
    <h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
    <svg_x000D_
      xmlns="http://www.w3.org/2000/svg"_x000D_
      viewBox="0 0 300 300"_x000D_
      x="0" y="0" height="300" width="300"_x000D_
    >_x000D_
_x000D_
      <circle_x000D_
        r="142" cx="150" cy="150"_x000D_
        fill="none" stroke="#000000" stroke-width="2"_x000D_
      />_x000D_
_x000D_
      <foreignObject_x000D_
        x="50" y="50" width="200" height="200"_x000D_
      >_x000D_
        <div_x000D_
          xmlns="http://www.w3.org/1999/xhtml"_x000D_
          style="_x000D_
            width: 196px; height: 196px;_x000D_
            border: solid 2px #000000;_x000D_
            font-size: 32px;_x000D_
            overflow: auto; /* scroll */_x000D_
          "_x000D_
        >_x000D_
          <p>this is html in svg 1</p>_x000D_
          <p>this is html in svg 2</p>_x000D_
          <p>this is html in svg 3</p>_x000D_
          <p>this is html in svg 4</p>_x000D_
        </div>_x000D_
      </foreignObject>_x000D_
_x000D_
    </svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Difference between scaling horizontally and vertically for databases

Scaling horizontally ===> Thousands of minions will do the work together for you.

Scaling vertically ===> One big hulk will do all the work for you.

enter image description here

How to parse XML in Bash?

Yuzem's method can be improved by inversing the order of the < and > signs in the rdom function and the variable assignments, so that:

rdom () { local IFS=\> ; read -d \< E C ;}

becomes:

rdom () { local IFS=\< ; read -d \> C E ;}

If the parsing is not done like this, the last tag in the XML file is never reached. This can be problematic if you intend to output another XML file at the end of the while loop.

Writing files in Node.js

Here we use w+ for read/write both actions and if the file path is not found the it would be created automatically.

fs.open(path, 'w+', function(err, data) {
    if (err) {
        console.log("ERROR !! " + err);
    } else {
        fs.write(data, 'content', 0, 'content length', null, function(err) {
            if (err)
                console.log("ERROR !! " + err);
            fs.close(data, function() {
                console.log('written success');
            })
        });
    }
});

Content means what you have to write to the file and its length, 'content.length'.

How can I color a UIImage in Swift?

Swift 4.

Use this extension to create a solid colored image

extension UIImage {   

    public func coloredImage(color: UIColor) -> UIImage? {
        return coloredImage(color: color, size: CGSize(width: 1, height: 1))
    }

    public func coloredImage(color: UIColor, size: CGSize) -> UIImage? {

        UIGraphicsBeginImageContextWithOptions(size, false, 0)

        color.setFill()
        UIRectFill(CGRect(origin: CGPoint(), size: size))

        guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()

        return image
    }
}

Add resources, config files to your jar using gradle

I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).

None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle file :

sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]

It tells Gradle to look for resources in the src folder, and ask it to include only PNG files.

EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/ for example, and to set it as srcDirs instead of src/.

How do I view the SQLite database on an Android device?

The best way to view and manage your Android app database is to use the library DatabaseManager_For_Android.

It's a single Java activity file; just add it to your source folder. You can view the tables in your app database, update, delete, insert rows to you table. Everything from inside your app.

When the development is done remove the Java file from your src folder. That's it.

You can view the 5 minute demo, Database Manager for Android SQLite Database .

Could not load file or assembly '' or one of its dependencies

Try checking if the "Copy to Local" property for the reference is set to true and the specific version is set to true. This is relevant for applications in Visual Studio.

How to SELECT the last 10 rows of an SQL table which has no ID field?

Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.

SELECT * FROM big_table ORDER BY A DESC LIMIT 10

Avoid dropdown menu close on click inside

You need to add "hold-on-click" to "dropdown-menu" class

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Find the smallest positive integer that does not occur in a given sequence

In PHP I can achieve it from a few lines of code.

function solution($A) {
  for($i=1; in_array($i,$A); $i++);
  return $i;    
}

Padding In bootstrap

There are padding built into various classes.

For example:

A asp.net web forms app:

<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />

this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.

However with bootstrap

<div class="checkbox-inline">
    <asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>

This created the space, if you don't want the text bold, that class=checkbox

Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.

updating table rows in postgres using subquery

There are many ways to update the rows.

When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

  1. Approach-1 [Using direct table reference]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2>
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

  1. Approach-2 [Using SubQueries]
UPDATE
  <table1>
SET
  customer=subquery.customer,
  address=subquery.address,
  partn=subquery.partn
FROM
  (
    SELECT
      address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
  ) AS subquery
WHERE
  dummy.address_id=subquery.address_id;

Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

  1. Approach-3 [Using multiple Joined tables]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2> as t2
  JOIN <table3> as t3
  ON
    t2.id = t3.id
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

  1. Approach-4 [Using WITH statement]

    • 4.1 [Using simple query]
WITH subquery AS (
    SELECT
      address_id,
      customer,
      address,
      partn
    FROM
      <table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
  • 4.2 [Using query with complex JOIN]
WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM
      <table1> as t1
    JOIN
      <table2> as t2
    ON
      t1.id = t2.id;
    -- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;

Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

I hope, this would be helpful.

Returning IEnumerable<T> vs. IQueryable<T>

In addition to first 2 really good answers (by driis & by Jacob) :

IEnumerable interface is in the System.Collections namespace.

The IEnumerable object represents a set of data in memory and can move on this data only forward. The query represented by the IEnumerable object is executed immediately and completely, so the application receives data quickly.

When the query is executed, IEnumerable loads all the data, and if we need to filter it, the filtering itself is done on the client side.

IQueryable interface is located in the System.Linq namespace.

The IQueryable object provides remote access to the database and allows you to navigate through the data either in a direct order from beginning to end, or in the reverse order. In the process of creating a query, the returned object is IQueryable, the query is optimized. As a result, less memory is consumed during its execution, less network bandwidth, but at the same time it can be processed slightly more slowly than a query that returns an IEnumerable object.

What to choose?

If you need the entire set of returned data, then it's better to use IEnumerable, which provides the maximum speed.

If you DO NOT need the entire set of returned data, but only some filtered data, then it's better to use IQueryable.

Hide strange unwanted Xcode logs

My solution is to use the debugger command and/or Log Message in breakpoints.

enter image description here

And change the output of console from All Output to Debugger Output like

enter image description here

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Remove trailing zeros

Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):

private static decimal Trim(this decimal value)
{
    var s = value.ToString(CultureInfo.InvariantCulture);
    return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
        ? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
        : value;
}

private static decimal? Trim(this decimal? value)
{
    return value.HasValue ? (decimal?) value.Value.Trim() : null;
}

private static void Main(string[] args)
{
    Console.WriteLine("=>{0}", 1.0000m.Trim());
    Console.WriteLine("=>{0}", 1.000000023000m.Trim());
    Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
    Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}

Output:

=>1
=>1.000000023
=>1.000000023
=>

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

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

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

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

UPDATE

Using g grouping, how about something like this? fiddle

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

How do I center align horizontal <UL> menu?

Generally speaking the way to center a black level element (like a <ul>) is using the margin:auto; property.

To align text and inline level elements within a block level element use text-align:center;. So all together something like...

ul {
    margin:auto;
}
ul li {
    text-align:center;
    list-style-position:inside; /* so that the bullet points are also centered */
}
ul li div {
    display:inline; /* so that the bullet points aren't above the content */
}

... should work.

The fringe case is Internet Explorer6... or even other IEs when not using a <!DOCTYPE>. IE6 incorrectly aligns block level elemnts using text-align. So if you're looking to support IE6 (or not using a <!DOCTYPE>) your full solution is...

div.topmenu-design {
    text-align:center;
}
div.topmenu-design ul {
    margin:auto;
}
div.topmenu-design ul li {
    text-align:center;
    list-style-position:inside; /* so that the bullet points are also centered */
}
div.topmenu-design ul li div {
    display:inline; /* so that the bullet points aren't above the content */
}

As a footnote, I think id="topmenu firstlevel" is invalid as an id attribute can't contain spaces... ? Indeed the w3c recommendation defines the id attribute as a 'name' type...

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

How to find index of all occurrences of element in array?

You can use Polyfill

if (!Array.prototype.filterIndex) {
Array.prototype.filterIndex = function (func, thisArg) {

    'use strict';
    if (!((typeof func === 'Function' || typeof func === 'function') && this))
        throw new TypeError();

    let len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;

    let kValue;
    if (thisArg === undefined) {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i]; // in case t is changed in callback
                if (func(t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }
    else {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i];
                if (func.call(thisArg, t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }

    res.length = c; // shrink down array to proper size
    return res;
};

}

Use it like this:

[2,23,1,2,3,4,52,2].filterIndex(element => element === 2)

result: [0, 3, 7]

import error: 'No module named' *does* exist

They are several ways to run python script:

  • run by double click on file.py (it opens the python command line)
  • run your file.py from the cmd prompt (cmd) (drag/drop your file on it for instance)
  • run your file.py in your IDE (eg. pyscripter or Pycharm)

Each of these ways can run a different version of python (¤)


Check which python version is run by cmd: Type in cmd:

python --version 

Check which python version is run when clicking on .py:

option 1:

create a test.py containing this:

import sys print (sys.version)
input("exit")

Option 2:

type in cmd:

assoc .py
ftype Python.File

Check the path and if the module (ex: win32clipboard) is recognized in the cmd:

create a test.py containing this:

python
import sys
sys.executable
sys.path
import win32clipboard
win32clipboard.__file__

Check the path and if module is recognized in the .py

create a test.py containing this:

import sys
print(sys.executable)
print(sys.path)
import win32clipboard
print(win32clipboard.__file__)

If the version in cmd is ok but not in .py it's because the default program associated with .py isn't the right one. Change python version for .py

To change the python version associated with cmd:

Control Panel\All Control Panel Items\System\Advanced system setting\Environnement variable In SYSTEM variable set the path variable to you python version (the path are separated by ;: cmd use the FIRST path eg: C:\path\to\Python27;C:\path\to\Python35 ? cmd will use python27)

To change the python version associated with .py extension:

Run cmd as admin:

Write: ftype Python.File="C:\Python35\python.exe" "%1" %* It will set the last python version (eg. python3.6). If your last version is 3.6 but you want 3.5 just add some xxx in your folder (xxxpython36) so it will take the last recognized version which is python3.5 (after the cmd remove the xxx).

Other:

"No modul error" could also come from a syntax error btw python et 3 (eg. missing parenthesis for print function...)

¤ Thus each of them has it's own pip version

can't multiply sequence by non-int of type 'float'

You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i to rate and using that instead. See the updated code below:

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
    for rate in growthRates:  
        #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
        fund = fund * (1 + 0.01 * rate) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

How to parse unix timestamp to time.Time

According to the go documentation, Unix returns a local time.

Unix returns the local Time corresponding to the given Unix time

This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

To do so, I adapted the snippet to make it return a time in UTC:

i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
    panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())

This prints on my machine (in CEST)

2014-07-16 20:55:46 +0000 UTC

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If it's a PHP issue, you could simply alter the configuration file php.ini wherever it's located and update the settings for PORT/SOCKET-PATH etc to make it connect to the server.

In my case, I opened the file php.ini and did

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock

And it worked straight away. I have to admit, I took hint from the accepted answer by @Joni

error MSB6006: "cmd.exe" exited with code 1

Another solution could be, that you deleted a file from your Project by just removing it in your file system, instead of removing it within your project.

Pick any kind of file via an Intent in Android

Not for camera but for other files..

In my device I have ES File Explorer installed and This simply thing works in my case..

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);

How to select last two characters of a string

Shortest:

str.slice(-2)

Example:

_x000D_
_x000D_
const str = "test";
const last2 = str.slice(-2);

console.log(last2);
_x000D_
_x000D_
_x000D_

SELECT inside a COUNT

You don't really need a sub-select:

SELECT a, COUNT(*) AS b,
   SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
   from t group by a order by b desc

How can I setup & run PhantomJS on Ubuntu?

On Ubuntu for Windows, I found neither apt-get nor npm versions worked for me. What worked was the script from this comment.

For ease of use, I pasted the whole thing into a script file called install_phantomjs.sh, made it executable (chmod u+x install_phantomjs.sh), and then ran it (./install_phantomjs.sh)

C# int to enum conversion

It's fine just to cast your int to Foo:

int i = 1;
Foo f = (Foo)i;

If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.

If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:

int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
    Foo f = (Foo)i;
}
else
{
   // Throw exception, etc.
}

However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.

Also note that you don't have to specify that your enum inherits from int; this is the default behavior.

How to implement the Java comparable interface?

Use a Comparator...

    public class AnimalAgeComparator implements Comparator<Animal> {

@Override
public int compare(Animal a1, Animal a2) {
  ...
}
}

Should I put #! (shebang) in Python scripts, and what form should it take?

The purpose of shebang is for the script to recognize the interpreter type when you want to execute the script from the shell. Mostly, and not always, you execute scripts by supplying the interpreter externally. Example usage: python-x.x script.py

This will work even if you don't have a shebang declarator.

Why first one is more "portable" is because, /usr/bin/env contains your PATH declaration which accounts for all the destinations where your system executables reside.

NOTE: Tornado doesn't strictly use shebangs, and Django strictly doesn't. It varies with how you are executing your application's main function.

ALSO: It doesn't vary with Python.

Disable/Enable Submit Button until all forms have been filled

I just posted this on Disable Submit button until Input fields filled in. Works for me.

Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.

http://www.w3schools.com/jsref/event_form_onsubmit.asp

<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
   ...
</form>

function validateCreditCardForm(){
    var result = false;
    if (($('#billing-cc-exp').val().length > 0) &&
        ($('#billing-cvv').val().length  > 0) &&
        ($('#billing-cc-number').val().length > 0)) {
            result = true;
    }
    return result;
}

How to generate .json file with PHP?

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

copy

How can I use JQuery to post JSON data?

I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data

$.fn.postJSON = function(url, data) {
    return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json'
        });

Add new attribute (element) to JSON object using JavaScript

You can also add new json objects into your json, using the extend function,

var newJson = $.extend({}, {my:"json"}, {other:"json"});
// result -> {my: "json", other: "json"}

A very good option for the extend function is the recursive merge. Just add the true value as the first parameter (read the documentation for more options). Example,

var newJson = $.extend(true, {}, {
    my:"json",
    nestedJson: {a1:1, a2:2}
}, {
    other:"json",
    nestedJson: {b1:1, b2:2}
});
// result -> {my: "json", other: "json", nestedJson: {a1:1, a2:2, b1:1, b2:2}}

Change column type in pandas

How about creating two dataframes, each with different data types for their columns, and then appending them together?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))

Results

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object

After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.

Execution time of C program

You functionally want this:

#include <sys/time.h>

struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);

printf ("Total time = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));

Note that this measures in microseconds, not just seconds.

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

Shell - How to find directory of some command?

The Korn shell, ksh, offers the whence built-in, which identifies other shell built-ins, macros, etc. The which command is more portable, however.

Delete all but the most recent X files in bash

I made this into a bash shell script. Usage: keep NUM DIR where NUM is the number of files to keep and DIR is the directory to scrub.

#!/bin/bash
# Keep last N files by date.
# Usage: keep NUMBER DIRECTORY
echo ""
if [ $# -lt 2 ]; then
    echo "Usage: $0 NUMFILES DIR"
    echo "Keep last N newest files."
    exit 1
fi
if [ ! -e $2 ]; then
    echo "ERROR: directory '$1' does not exist"
    exit 1
fi
if [ ! -d $2 ]; then
    echo "ERROR: '$1' is not a directory"
    exit 1
fi
pushd $2 > /dev/null
ls -tp | grep -v '/' | tail -n +"$1" | xargs -I {} rm -- {}
popd > /dev/null
echo "Done. Kept $1 most recent files in $2."
ls $2|wc -l

Iterating over Numpy matrix rows to apply a function each?

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

What is the difference between __str__ and __repr__?

In all honesty, eval(repr(obj)) is never used. If you find yourself using it, you should stop, because eval is dangerous, and strings are a very inefficient way to serialize your objects (use pickle instead).

Therefore, I would recommend setting __repr__ = __str__. The reason is that str(list) calls repr on the elements (I consider this to be one of the biggest design flaws of Python that was not addressed by Python 3). An actual repr will probably not be very helpful as the output of print [your, objects].

To qualify this, in my experience, the most useful use case of the repr function is to put a string inside another string (using string formatting). This way, you don't have to worry about escaping quotes or anything. But note that there is no eval happening here.

How to add constraints programmatically using Swift

The problem, as the error message suggests, is that you have constraints of type NSAutoresizingMaskLayoutConstraints that conflict with your explicit constraints, because new_view.translatesAutoresizingMaskIntoConstraints is set to true.

This is the default setting for views you create in code. You can turn it off like this:

var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
new_view.translatesAutoresizingMaskIntoConstraints = false

Also, your width and height constraints are weird. If you want the view to have a constant width, this is the proper way:

new_view.addConstraint(NSLayoutConstraint(
    item:new_view, attribute:NSLayoutAttribute.Width,
    relatedBy:NSLayoutRelation.Equal,
    toItem:nil, attribute:NSLayoutAttribute.NotAnAttribute,
    multiplier:0, constant:100))

(Replace 100 by the width you want it to have.)

If your deployment target is iOS 9.0 or later, you can use this shorter code:

new_view.widthAnchor.constraintEqualToConstant(100).active = true

Anyway, for a layout like this (fixed size and centered in parent view), it would be simpler to use the autoresizing mask and let the system translate the mask into constraints:

var new_view:UIView! = UIView(frame: CGRectMake(0, 0, 100, 100))
new_view.backgroundColor = UIColor.redColor();
view.addSubview(new_view);

// This is the default setting but be explicit anyway...
new_view.translatesAutoresizingMaskIntoConstraints = true

new_view.autoresizingMask = [ .FlexibleTopMargin, .FlexibleBottomMargin,
    .FlexibleLeftMargin, .FlexibleRightMargin ]

new_view.center = CGPointMake(view.bounds.midX, view.bounds.midY)

Note that using autoresizing is perfectly legitimate even when you're also using autolayout. (UIKit still uses autoresizing in lots of places internally.) The problem is that it's difficult to apply additional constraints to a view that is using autoresizing.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

Iterating over a 2 dimensional python list

Ref: zip built-in function

zip() in conjunction with the * operator can be used to unzip a list

unzip_lst = zip(*mylist)
for i in unzip_lst:
    for j in i:
        print j

Returning a value even if no result

if you want both always a return value but never a null value you can combine count with coalesce :

select count(field1), coalesce(field1,'any_other_default_value') from table;

that because count, will force mysql to always return a value (0 if there is no values to count) and coalesce will force mysql to always put a value that is not null

How to fill background image of an UIView

The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.

Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:

Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.

This is IMHO the simplest and most flexible design for future changes.

Datatables warning(table id = 'example'): cannot reinitialise data table

You are initializing datatables twice, why?

// Take this off
/*
$(document).ready(function() {
    $( '#example' ).dataTable();
} );
*/
$(document).ready( function() {
  $( '#example' ).dataTable( {
   "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
     // Bold the grade for all 'A' grade browsers
     if ( aData[4] == "A" )
     {
       $('td:eq(4)', nRow).html( '<b>A</b>' );
     }
   }
 } );
 } );

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

pip not working in Python Installation in Windows 10

Make sure the path to scripts folder for the python version is added to the path environment/system variable in order to use pip command directly without the whole path to pip.exe which is inside the scripts folder.

The scripts folder would be inside the python folder for the version that you are using, which by default would be inside c drive or in c:/program files or c:/program files (x86).

Then use commands as mentioned below. You may have to run cmd as administrator to perform these tasks. You can do it by right clicking on cmd icon and selecting run as administrator.

python -m pip install packagename
python -m pip uninstall packagename
python -m pip install --upgrade packagename

In case you have more than one version of python. You may replace python with py -versionnumber for example py -2 for python 2 or you may replace it with the path to the corresponding python.exe file. For example "c:\python27\python".

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

Using lodash to compare jagged arrays (items existence without order)

By 'the same' I mean that there are is no item in array1 that is not contained in array2.

You could use flatten() and difference() for this, which works well if you don't care if there are items in array2 that aren't in array1. It sounds like you're asking is array1 a subset of array2?

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];

function isSubset(source, target) {
    return !_.difference(_.flatten(source), _.flatten(target)).length;
}

isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true

destination path already exists and is not an empty directory

If you got Destination path XXX already exists means the name of the project repository which you are trying to clone is already there in that current directory. So please cross-check and delete any existing one and try to clone it again

Two-dimensional array in Swift

From the docs:

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:

var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.

How to turn off INFO logging in Spark?

>>> log4j = sc._jvm.org.apache.log4j
>>> log4j.LogManager.getRootLogger().setLevel(log4j.Level.ERROR)

How to get substring from string in c#?

var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

Output:

Retrieves a substring from this instance. The substring starts at a specified character position.

how to stop Javascript forEach?

Array.forEach cannot be broken and using try...catch or hacky methods such as Array.every or Array.some will only make your code harder to understand. There are only two solutions of this problem:

1) use a old for loop: this will be the most compatible solution but can be very hard to read when used often in large blocks of code:

var testArray = ['a', 'b', 'c'];
for (var key = 0; key < testArray.length; key++) {
    var value = testArray[key];
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

2) use the new ECMA6 (2015 specification) in cases where compatibility is not a problem. Note that even in 2016, only a few browsers and IDEs offer good support for this new specification. While this works for iterable objects (e.g. Arrays), if you want to use this on non-iterable objects, you will need to use the Object.entries method. This method is scarcely available as of June 18th 2016 and even Chrome requires a special flag to enable it: chrome://flags/#enable-javascript-harmony. For Arrays, you won't need all this but compatibility remains a problem:

var testArray = ['a', 'b', 'c'];
for (let [key, value] of testArray.entries()) {
    console.log(key); // This is the key;
    console.log(value); // This is the value;
}

3) A lot of people would agree that neither the first or second option are good candidates. Until option 2 becomes the new standard, most popular libraries such as AngularJS and jQuery offer their own loop methods which can be superior to anything available in JavaScript. Also for those who are not already using these big libraries and that are looking for lightweight options, solutions like this can be used and will almost be on par with ECMA6 while keeping compatibility with older browsers.

How to overcome the CORS issue in ReactJS

Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.

A simpler way is to use express-http-proxy

  1. run npm run build to create the bundle.

    var proxy = require('express-http-proxy');
    
    var app = require('express')();
    
    //define the path of build
    
    var staticFilesPath = path.resolve(__dirname, '..', 'build');
    
    app.use(express.static(staticFilesPath));
    
    app.use('/api/api-server', proxy('www.api-server.com'));
    

Use "/api/api-server" from react code to call the API.

So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Via SQL as per MSDN

SET IDENTITY_INSERT sometableWithIdentity ON

INSERT INTO sometableWithIdentity 
    (IdentityColumn, col2, col3, ...)
VALUES 
    (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF

The complete error message tells you exactly what is wrong...

Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.

@Cacheable key on multiple method arguments

You can use Spring SimpleKey class

@Cacheable(value = "bookCache", key = "new org.springframework.cache.interceptor.SimpleKey(#isbn, #checkWarehouse)")

How to make a checkbox checked with jQuery?

$('#checkbox').prop('checked', true);

When you want it unchecked:

$('#checkbox').prop('checked', false);

How to select true/false based on column value?

Maybe too late, but I'd cast 0/1 as bit to make the datatype eventually becomes True/False when consumed by .NET framework:

SELECT   EntityId, 
         EntityName, 
         CASE 
            WHEN EntityProfileIs IS NULL 
            THEN CAST(0 as bit) 
            ELSE CAST(1 as bit) END AS HasProfile
FROM      Entities
LEFT JOIN EntityProfiles ON EntityProfiles.EntityId = Entities.EntityId`

How to upload and parse a CSV file in php

You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().

Setting width/height as percentage minus pixels

You can use calc:

height: calc(100% - 18px);

Note that some old browsers don't support the CSS3 calc() function, so implementing the vendor-specific versions of the function may be required:

/* Firefox */
height: -moz-calc(100% - 18px);
/* WebKit */
height: -webkit-calc(100% - 18px);
/* Opera */
height: -o-calc(100% - 18px);
/* Standard */
height: calc(100% - 18px);

How to restart VScode after editing extension's config?

Execute the workbench.action.reloadWindow command.

There are some ways to do so:

  1. Open the command palette (Ctrl + Shift + P) and execute the command:

    >Reload Window    
    
  2. Define a keybinding for the command (for example CTRL+F5) in keybindings.json:

    [
      {
        "key": "ctrl+f5",
        "command": "workbench.action.reloadWindow",
        "when": "editorTextFocus"
      }
    ]
    

Can an Android App connect directly to an online mysql database

What you want to do is a bad idea. It would require you to embed your username and password in the app. This is a very bad idea as it might be possible to reverse engineer your APK and get the username and password to this publicly facing mysql server which may contain sensitive user data.

I would suggest making a web service to act as a proxy to the mysql server. I assume users need to be logged in, so you could use their username/password to authenticate to the web service.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

Javascript-Setting background image of a DIV via a function and function parameter

From what I know, the correct syntax is:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}

So basically, getElementById(tabName).backgroundImage and split the string like:

"cssInHere('and" + javascriptOutHere + "/cssAgain')";

JavaScript string with new line - but not using \n

The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings.

When you have a string which looks like this:

//Note lack of terminating double quote
var foo = "Bob 

Your code will have a syntax error at that point and cease to run.

If you wish to have a string which spans multiple lines, you may insert a backslash character '\' just before you terminate the line, like so:

//Perfectly valid code
var foo = "Bob \
is \
cool.";

However that string will not contain \n characters in the positions where the string was broken into separate lines. The only way to insert a newline into a string is to insert a character with a value of 10, the easiest way of which is the \n escape character.

var foo = "Bob\nis\ncool.";

Replace values in list using Python

Riffing on a side question asked by the OP in a comment, i.e.:

what if I had a generator that yields the values from range(11) instead of a list. Would it be possible to replace values in the generator?

Sure, it's trivially easy...:

def replaceiniter(it, predicate, replacement=None):
  for item in it:
    if predicate(item): yield replacement
    else: yield item

Just pass any iterable (including the result of calling a generator) as the first arg, the predicate to decide if a value must be replaced as the second arg, and let 'er rip.

For example:

>>> list(replaceiniter(xrange(11), lambda x: x%2))
[0, None, 2, None, 4, None, 6, None, 8, None, 10]

"Line contains NULL byte" in CSV reader (Python)

You could just inline a generator to filter out the null values if you want to pretend they don't exist. Of course this is assuming the null bytes are not really part of the encoding and really are some kind of erroneous artifact or bug.

See the (line.replace('\0','') for line in f) below, also you'll want to probably open that file up using mode rb.

import csv

lines = []
with open('output.txt','r') as f:
    for line in f.readlines():
        lines.append(line[:-1])

with open('corrected.csv','w') as correct:
    writer = csv.writer(correct, dialect = 'excel')
    with open('input.csv', 'rb') as mycsv:
        reader = csv.reader( (line.replace('\0','') for line in mycsv) )
        for row in reader:
            if row[0] not in lines:
                writer.writerow(row)

Writing your own square root function

A simple solution that can deal with float square root and arbitrary precision using binary search

coded in ruby

include Math

def sqroot_precision num, precision
  upper   = num
  lower   = 0
  middle  = (upper + lower)/2.0

  while true do
    diff = middle**2 - num

    return middle if diff.abs <= precision

    if diff > 0
      upper = middle
    else diff < 0
      lower = middle
    end

    middle = (upper + lower)/2.0
  end 
end

puts sqroot_precision 232.3, 0.0000000001

Android WebView, how to handle redirects in app instead of opening a browser

According to the official documentation, a click on any link in WebView launches an application that handles URLs, which by default is a browser. You need to override the default behavior like this

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });

How to convert float to varchar in SQL Server

Try this one, should work:

cast((convert(bigint,b.tax_id)) as varchar(20))

Compiler error: "initializer element is not a compile-time constant"

When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize to create your image. initialize is a class method which will be called before any other method is called on your class.

Example:

NSImage *imageSegment = nil;
+ (void)initialize {
    if(!imageSegment)
        imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

Simulating ENTER keypress in bash script

You can just use yes.

# yes "" | someCommand

What is the use of adding a null key or value to a HashMap in Java?

The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

div inside table

you can put div tags inside a td tag, but not directly inside a table or tr tag. examples:

this works:

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td> _x000D_
      <div>This will work.</div> _x000D_
    </td>_x000D_
  </tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

this does not work:

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <div> this does not work. </div> _x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

nor does this work:

_x000D_
_x000D_
<table>_x000D_
  <div> this does not work. </div>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to load local file in sc.textFile, instead of HDFS

I have a file called NewsArticle.txt on my Desktop.

In Spark, I typed:

val textFile= sc.textFile(“file:///C:/Users/582767/Desktop/NewsArticle.txt”)

I needed to change all the \ to / character for the filepath.

To test if it worked, I typed:

textFile.foreach(println)

I'm running Windows 7 and I don't have Hadoop installed.

hash keys / values as array

Here is a good example of array_keys from PHP.js library:

function array_keys (input, search_value, argStrict) {
    // Return just the keys from the input array, optionally only for the specified search_value

    var search = typeof search_value !== 'undefined',
        tmp_arr = [],
        strict = !!argStrict,
        include = true,
        key = '';

    for (key in input) {
        if (input.hasOwnProperty(key)) {
            include = true;
            if (search) {
                if (strict && input[key] !== search_value) {
                    include = false;
                }
                else if (input[key] != search_value) {
                    include = false;
                }
            }

            if (include) {
                tmp_arr[tmp_arr.length] = key;
            }
        }
    }

    return tmp_arr;
}

The same goes for array_values (from the same PHP.js library):

function array_values (input) {
    // Return just the values from the input array  

    var tmp_arr = [],
        key = '';

    for (key in input) {
        tmp_arr[tmp_arr.length] = input[key];
    }

    return tmp_arr;
}

EDIT: Removed unnecessary clauses from the code.

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

How do I know the script file name in a Bash script?

Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:

me=$(readlink --canonicalize --no-newline $0)

If your script has been sourced from another bash script, you can use:

me=$(readlink --canonicalize --no-newline $BASH_SOURCE)

I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.

If REST applications are supposed to be stateless, how do you manage sessions?

There is no spoon.

Don't think of statelessness like "sending all your stuff to the server again and again". No way. There will be state, always - database itself is a kind of state after all, you're a registered user, so any set of client-side info won't be valid without the server side. Technically, you're never truly stateless.

The Login Debate

    What does it even mean to not keep a session - and log in every time?

    Some mean "send the password each time", that's just plain stupid. Some say "nah of course not, send a token instead" - lo and behold, PHP session is doing almost exactly that. It sends a session id which is a kind of token and it helps you reach your personal stuff without resending u/pw every time. It's also quite reliable and well tested. And yes, convenient, which can turn into a drawback, see next paragraph.

Reduce footprint

    What you should do, instead, and what makes real sense, is thin your webserver footprint to the minimum. Languages like PHP make it very easy to just stuff everything in the session storage - but sessions have a price tag. If you have several webservers, they need to share session info, because they share the load too - any of them may have to serve the next request.

    A shared storage is a must. Server needs to know at least if someone's logged in or not. (And if you bother the database every time you need to decide this, you're practically doomed.) Shared storages need to be a lot faster than the database. This brings the temptation: okay, I have a very fast storage, why not do everything there? - and that's where things go nasty in the other way.

So you're saying, keep session storage to the minimum?

    Again, it's your decision. You can store stuff there for performance reasons (database is almost always slower than Redis), you can store information redundantly, implement your own caching, whatever - just keep in mind that web servers will have a bigger load if you store a lot of rubbish on them. Also, if they break under heavy loads (and they will), you lose valuable information; with the REST way of thinking, all that happens in this case is the client sends the same (!) request again and it gets served this time.

How to do it right then?

    No one-fits-all solution here. I'd say choose a level of statelessness and go with that. Sessions may be loved by some and hated by others but they're not going anywhere. With every request, send as much information as makes sense, a bit more perhaps; but don't interpret statelessness as not having a session, nor as logging in every time. Somehow the server must know it's you; PHP session ids are one good way, manually generated tokens are another.

    Think and decide - don't let design trends think for you.

How to enable local network users to access my WAMP sites?

go to... 
C:\wamp\alias

Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...

open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines

Require local

by

Require all granted

Subversion ignoring "--password" and "--username" options

I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:

Host server.hostname
  User username

I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

What is the difference between declarations, providers, and import in NgModule?

Components are declared, Modules are imported, and Services are provided. An example I'm working with:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';    

@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [ StateService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

where to place CASE WHEN column IS NULL in this query

Try this:

CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4

The as col4 should go at the end of the CASE the statement. Also note that you're missing the END too.

Another probably more simple option would be:

IIf([table3.col3] Is Null,[table2.col3],[table3.col3])

Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.

Edit after radical question change:

To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID

BTW, your CASE statement was missing a , before the field. That's why it didn't work.

Read values into a shell variable from a pipe

How about this:

echo "hello world" | echo test=$(cat)

Permissions error when connecting to EC2 via SSH on Mac OSx

None of the above helped me, but futzing with the user seemed like it had promise. For my config using 'ubuntu' was right.....

ssh -i [full path to keypair file] ubuntu@[EC2 instance hostname or IP address]

How to call a function in shell Scripting?

Summary:

  • Define functions before using them.
  • Once defined, treat them as commands.

Consider this script, called funcdemo:

#!/bin/bash

[ $# = 0 ] && exhort "write nastygram"

exhort(){
    echo "Please, please do not forget to $*"
}

[ $# != 0 ] && exhort "write begging letter"

In use:

$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$

Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.

How to set timeout on python's socket recv method?

You could set timeout before receiving the response and after having received the response set it back to None:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)

How to restrict UITextField to take only numbers in Swift?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

        {
            let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

            if textField == self.phoneTextField  && string.characters.count > 0{
                let numberOnly = NSCharacterSet.decimalDigits
                let strValid = numberOnly.contains(UnicodeScalar.init(string)!)
                return strValid && textString.characters.count <= 10
            }
            return true
        }

in above code is working in swift 3
NSCharacterSet.decimalDigits
You are also use letters only
NSCharacterSet.Letters
and uppercase,Lowercaseand,alphanumerics,whitespaces is used same code or See the Link

How to make an inline element appear on new line, or block element not occupy the whole line?

For the block element not occupy the whole line, set it's width to something small and the white-space:nowrap

label
{
    width:10px;
    display:block;
    white-space:nowrap;
}

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

How to uninstall downloaded Xcode simulator?

Run this command in terminal to remove simulators that can't be accessed from the current version of Xcode in use.

xcrun simctl delete unavailable

Also if you're looking to reclaim simulator related space Michael Tsai found that deleting sim logs saved him 30 GB.

~/Library/Logs/CoreSimulator

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

javascript create empty array of a given size

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');

C++ - struct vs. class

The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.

Get protocol + host name from URL

to get domain/hostname and Origin*

url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
hostname = url.split('/')[2] # stackoverflow.com
origin = '/'.join(url.split('/')[:3]) # https://stackoverflow.com

*Origin is used in XMLHttpRequest headers

Python: Find in list

If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

first_or_default = next((x for x in lst if ...), None)

How do I change a TCP socket to be non-blocking?

If you want to change socket to non blocking , precisely accept() to NON-Blocking state then

    int flags=fcntl(master_socket, F_GETFL);
        fcntl(master_socket, F_SETFL,flags| O_NONBLOCK); /* Change the socket into non-blocking state  F_SETFL is a command saying set flag and flag is 0_NONBLOCK     */                                          

while(1){
    if((newSocket = accept(master_socket, (struct sockaddr *) &address, &addr_size))<0){
                if(errno==EWOULDBLOCK){
                       puts("\n No clients currently available............ \n");
                       continue;
               }
    }else{
          puts("\nClient approched............ \n");
    }

}

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

in this scenario:

DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));

aren't you missing the column you want to compare to? example:

DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) 
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));    

I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.

How do I encrypt and decrypt a string in python?

Although its very old, but I thought of sharing another idea to do this:

from Crypto.Cipher import AES    
from Crypto.Hash import SHA256

password = ("anything")    
hash_obj = SHA256.new(password.encode('utf-8'))    
hkey = hash_obj.digest()

def encrypt(info):
    msg = info
    BLOCK_SIZE = 16
    PAD = "{"
    padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
    cipher = AES.new(hkey, AES.MODE_ECB)
    result = cipher.encrypt(padding(msg).encode('utf-8'))
    return result  

msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)
print(cipher_text)

def decrypt(info):
    msg = info
    PAD = "{"
    decipher = AES.new(hkey, AES.MODE_ECB)
    pt = decipher.decrypt(msg).decode('utf-8')
    pad_index = pt.find(PAD)
    result = pt[: pad_index]
    return result

plaintext = decrypt(cipher_text)
print(plaintext)

Outputs:

> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'

> Hello stackoverflow!

Access a global variable in a PHP function

Another way to do it:

<?php

$data = 'My data';

$menugen = function() use ($data) {

    echo "[".$data."]";
};

$menugen();

UPDATE 2020-01-13: requested by Peter Mortensen

As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.

In the example, the closure is able to access $data because it was declared in the use clause.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Call the toISOString() method:

var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());

// Output:
//  2010-07-30T15:05:00.000Z

How can I find WPF controls by name or type?

I have a sequence function like this (which is completely general):

    public static IEnumerable<T> SelectAllRecursively<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> func)
    {
        return (items ?? Enumerable.Empty<T>()).SelectMany(o => new[] { o }.Concat(SelectAllRecursively(func(o), func)));
    }

Getting immediate children:

    public static IEnumerable<DependencyObject> FindChildren(this DependencyObject obj)
    {
        return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(obj))
            .Select(i => VisualTreeHelper.GetChild(obj, i));
    }

Finding all children down the hiararchical tree:

    public static IEnumerable<DependencyObject> FindAllChildren(this DependencyObject obj)
    {
        return obj.FindChildren().SelectAllRecursively(o => o.FindChildren());
    }

You can call this on the Window to get all controls.

After you have the collection, you can use LINQ (i.e. OfType, Where).

Nested objects in javascript, best practices

var defaultSettings = {
    ajaxsettings: {},
    uisettings: {}
};

Take a look at this site: http://www.json.org/

Also, you can try calling JSON.stringify() on one of your objects from the browser to see the json format. You'd have to do this in the console or a test page.

How to avoid 'cannot read property of undefined' errors?

I answered this before and happened to be doing a similar check today. A simplification to check if a nested dotted property exists. You could modify this to return the value, or some default to accomplish your goal.

function containsProperty(instance, propertyName) {
    // make an array of properties to walk through because propertyName can be nested
    // ex "test.test2.test.test"
    let walkArr = propertyName.indexOf('.') > 0 ? propertyName.split('.') : [propertyName];

    // walk the tree - if any property does not exist then return false
    for (let treeDepth = 0, maxDepth = walkArr.length; treeDepth < maxDepth; treeDepth++) {

        // property does not exist
        if (!Object.prototype.hasOwnProperty.call(instance, walkArr[treeDepth])) {
            return false;
        }

        // does it exist - reassign the leaf
        instance = instance[walkArr[treeDepth]];

    }

    // default
    return true;

}

In your question you could do something like:

let test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
containsProperty(test[0], 'a.b.c');

Conditional statement in a one line lambda function in python?

The right way to do this is simple:

def rate(T):
    if (T > 200):
        return 200*exp(-T)
    else:
        return 400*exp(-T)

There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.

The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).


From a comment:

Well the function needed to fit in one line, which i didn't think you could do with a named function?

I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:

>>> def foo(x): return x + 1

Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.

Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.

But on the off chance that this really is what you need here: Just use exec instead of eval.

You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:

exec(my_function_string, my_globals, my_locals)

In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.

In earlier 2.x (before 2.6, I think?) you have to do it like this instead:

exec my_function_string in my_globals, my_locals

Parse an URL in JavaScript

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Worked for me. But the first var should be var url = window.location.href

How can you search Google Programmatically Java API

Just an alternative. Searching google and parsing the results can also be done in a generic way using any HTML Parser such as Jsoup in Java. Following is the link to the mentioned example.

Update: Link no longer works. Please look for any other example. https://www.codeforeach.com/java/example-how-to-search-google-using-java

Swift programmatically navigate to another view controller/scene

The above code works well but if you want to navigate from an NSObject class, where you can not use self.present:

let storyBoard = UIStoryboard(name:"Main", bundle: nil)
if let conVC = storyBoard.instantiateViewController(withIdentifier: "SoundViewController") as? SoundViewController,
    let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
    
    navController.pushViewController(conVC, animated: true)
}

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Error in installation a R package

The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.

When you run sudo R in order to run install.packages() as superuser, the directories in which you install the library end up belonging to root user, a.k.a., the superuser.

So, next time you need to update your libraries, you will not remember that you ran sudo, therefore leaving root as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root but themself.

That can be averted by running

sudo chown -R yourusername:yourusername *

in the directory lib that contains your local libraries, replacing yourusername by the adequated value in your installation. Then you try installing once again.

Vue.js data-bind style backgroundImage not working

I tried @david answer, and it didn't fix my issue. after a lot of hassle, I made a method and return the image with style string.

HTML Code

<div v-for="slide in loadSliderImages" :key="slide.id">
    <div v-else :style="bannerBgImage(slide.banner)"></div>
</div>

Method

bannerBgImage(image){
    return 'background-image: url("' + image + '")';
},

Add common prefix to all cells in Excel

Another way to do this:

  1. Put your prefix in one column say column A in excel
  2. Put the values to which you want to add prefix in another column say column B in excel
  3. In Column C, use this formula;

"C1=A1&B1"

  1. Copy all the values in column C and paste it again in the same selection but as values only.