Programs & Examples On #Falcon

Falcon is an open source, multi-paradigm programming language.

HTML forms - input type submit problem with action=URL when URL contains index.aspx

Put the query arguments in hidden input fields:

<form action="http://spufalcons.com/index.aspx">
    <input type="hidden" name="tab" value="gymnastics" />
    <input type="hidden" name="path" value="gym" />
    <input type="submit" value="SPU Gymnastics"/>
</form>

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

Good tool for testing socket connections?

Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.

How to insert current_timestamp into Postgres via python

Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.

In other words: just write anything and it will work.

Or check this table with all the unambiguous formats.

Removing multiple classes (jQuery)

$("element").removeClass("class1 class2");

From removeClass(), the class parameter:

One or more CSS classes to remove from the elements, these are separated by spaces.

How to create an array from a CSV file using PHP and the fgetcsv function

If you want each line to be in an array, and each cell in the line in array:

$file = fopen('csvFile.csv', 'r');              // Open the file                     
while (($line = fgetcsv($file)) !== FALSE) {    // Read one line
    $array[] =$line;                            // Add the line in the main array
}
echo '<pre>';
print_r($array);   //print it out
echo '</pre>'; 
fclose($file);

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I solved this by restarting my computer. I'm guessing that this port was being occupied by a process that needed to be killed.

MySQL - how to front pad zip code with "0"?

CHAR(5)

or

MEDIUMINT (5) UNSIGNED ZEROFILL

The first takes 5 bytes per zip code.

The second takes only 3 bytes per zip code. The ZEROFILL option is necessary for zip codes with leading zeros.

What does the C++ standard state the size of int, long type to be?

Updated: C++11 brought the types from TR1 officially into the standard:

  • long long int
  • unsigned long long int

And the "sized" types from <cstdint>

  • int8_t
  • int16_t
  • int32_t
  • int64_t
  • (and the unsigned counterparts).

Plus you get:

  • int_least8_t
  • int_least16_t
  • int_least32_t
  • int_least64_t
  • Plus the unsigned counterparts.

These types represent the smallest integer types with at least the specified number of bits. Likewise there are the "fastest" integer types with at least the specified number of bits:

  • int_fast8_t
  • int_fast16_t
  • int_fast32_t
  • int_fast64_t
  • Plus the unsigned versions.

What "fast" means, if anything, is up to the implementation. It need not be the fastest for all purposes either.

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

I can highly recommend checking out the Visual Studio plugin ReSharper. It has a QuickFix feature that does the same (and a lot more).

But ReSharper doesn't require the cursor to be located on the actual code that requires a new namespace. Say, you copy/paste some code into the source file, and just a few clicks of Alt + Enter, and all the required usings are included.

Oh, and it also makes sure that the required assembly reference is added to your project. Say for example, you create a new project containing NUnit unit tests. The first class you write, you add the [TestFixture] attribute. If you already have one project in your solution that references the NUnit DLL file, then ReSharper is able to see that the TestFixtureAttribute comes from that DLL file, so it will automatically add that assembly reference to your new project.

And it also adds required namespaces for extension methods. At least the ReSharper version 5 beta does. I'm pretty sure that Visual Studio's built-in resolve function doesn't do that.

On the down side, it's a commercial product, so you have to pay for it. But if you work with software commercially, the gained productivity (the plug in does a lot of other cool stuff) outweighs the price tag.

Yes, I'm a fan ;)

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

How to convert an NSTimeInterval (seconds) into minutes

Remember that the original question is about a string output, not pseudo-code or individual string components.

I want to convert it into the following string: "5:26"

Many answers are missing the internationalization issues, and most doing the math computations by hand. All just so 20th century...

Do not do the Math yourself (Swift 4)

let timeInterval: TimeInterval = 326.4
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = .positional
if let formatted = dateComponentsFormatter.string(from: timeInterval) {
    print(formatted)
}

5:26


Leverage on libraries

If you really want individual components, and pleasantly readable code, check out SwiftDate:

import SwiftDate
...
if let minutes = Int(timeInterval).seconds.in(.minute) {
    print("\(minutes)")
}

5


Credits to @mickmaccallum and @polarwar for adequate usage of DateComponentsFormatter

How to install latest version of git on CentOS 7.x/6.x

as git says:

RHEL and derivatives typically ship older versions of git. You can download a tarball and build from source, or use a 3rd-party repository such as the IUS Community Project to obtain a more recent version of git.

there is good tutorial here. in my case (Centos7 server) after install had to logout and login again.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The problem is that you might easily get into trouble since JavaScript have a lot of implicit conversions meaning...

var x = 0;
var isTrue = x == null;
var isFalse = x === null;

Which pretty soon becomes a problem. The best sample of why implicit conversion is "evil" can be taken from this code in MFC / C++ which actually will compile due to an implicit conversion from CString to HANDLE which is a pointer typedef type...

CString x;
delete x;

Which obviously during runtime does very undefined things...

Google for implicit conversions in C++ and STL to get some of the arguments against it...

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

Google Chrome redirecting localhost to https

I am facing the same problem but only in Chrome Canary and searching a solution I've found this post.

one of the next versions of Chrome is going to force all domains ending on .dev (and .foo) to be redirected to HTTPs via a preloaded HTTP Strict Transport Security (HSTS) header.

{ "name": "dev", "include_subdomains": true, "mode": "force-https" },
{ "name": "foo", "include_subdomains": true, "mode": "force-https" },

So, change your domains.

How do I get the key at a specific index from a Dictionary in Swift?

SWIFT 3. Example for the first element

let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

How to Display Multiple Google Maps per page with API V3

You could try nex approach css

 .map {
            height: 300px;
            width: 100%;
        }

HTML

@foreach(var map in maps)
{
  <div id="[email protected]" lat="@map.Latitude" lng="@map.Longitude" class="map">
  </div>
}

JavaScript

 <script>
    var maps = [];
    var markers = [];
    function initMap() {
        var $maps = $('.map');
        $.each($maps, function (i, value) {
            var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };

            var mapDivId = $(value).attr('id');

            maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
                zoom: 17,
                center: uluru
            });

            markers[mapDivId] = new google.maps.Marker({
                position: uluru,
                map: maps[mapDivId]
            });
        })
    }
</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
</script>

How to get current CPU and RAM usage in Python?

  • For CPU details use psutil library

    https://psutil.readthedocs.io/en/latest/#cpu

  • For RAM Frequency (in MHz) use the built in Linux library dmidecode and manipulate the output a bit ;). this command needs root permission hence supply your password too. just copy the following commend replacing mypass with your password

import os

os.system("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2")

------------------- Output ---------------------------
1600 MT/s
Unknown
1600 MT/s
Unknown 0

  • more specificly
    [i for i in os.popen("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2").read().split(' ') if i.isdigit()]

-------------------------- output -------------------------
['1600', '1600']

How to remove/delete a large file from commit history in Git repository?

According to GitHub Documentation, just follow these steps:

  1. Get rid of the large file

Option 1: You don't want to keep the large file:

rm path/to/your/large/file        # delete the large file

Option 2: You want to keep the large file into an untracked directory

mkdir large_files                       # create directory large_files
touch .gitignore                        # create .gitignore file if needed
'/large_files/' >> .gitignore           # untrack directory large_files
mv path/to/your/large/file large_files/ # move the large file into the untracked directory
  1. Save your changes
git add path/to/your/large/file   # add the deletion to the index
git commit -m 'delete large file' # commit the deletion
  1. Remove the large file from all commits
git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch path/to/your/large/file" \
  --prune-empty --tag-name-filter cat -- --all
git push <remote> <branch>

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Rename a column in MySQL

In mysql your query should be like

ALTER TABLE table_name change column_1 column_2 Data_Type;

you have written the query in Oracle.

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

How to simplify a null-safe compareTo() implementation?

You can extract method:

public int cmp(String txt, String otherTxt)
{
    if ( txt == null )
        return otjerTxt == null ? 0 : 1;

    if ( otherTxt == null )
          return 1;

    return txt.compareToIgnoreCase(otherTxt);
}

public int compareTo(Metadata other) {
   int result = cmp( name, other.name); 
   if ( result != 0 )  return result;
   return cmp( value, other.value); 

}

When to use "ON UPDATE CASCADE"

A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE can be useful. Take a look at this example (PostgreSQL):

CREATE TABLE club
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE band
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE concert
(
    key SERIAL PRIMARY KEY,
    club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
    band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
    concert_date DATE
);

In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE was the key to solve the problem.

Detect Safari browser

Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple vendor and then exclude Chrome and Firefox (for iOS).

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i);

if (isSafari) {
  //
} else {
  //
}

java.net.UnknownHostException: Invalid hostname for server: local

Connect your mobile with different wifi connection with different service provider. I don't know the exact issue but i could not connect to server with a specific service provider but it work when i connected to other service provider. So try it!

How do I make a matrix from a list of vectors in R?

One option is to use do.call():

 > do.call(rbind, a)
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Convert an image to grayscale

There's a static method in ToolStripRenderer class, named CreateDisabledImage. Its usage is as simple as:

Bitmap c = new Bitmap("filename");
Image d = ToolStripRenderer.CreateDisabledImage(c);

It uses a little bit different matrix than the one in the accepted answer and additionally multiplies it by a transparency of value 0.7, so the effect is slightly different than just grayscale, but if you want to just get your image grayed, it's the simplest and best solution.

What is the meaning of the term "thread-safe"?

Yes and no.

Thread safety is a little bit more than just making sure your shared data is accessed by only one thread at a time. You have to ensure sequential access to shared data, while at the same time avoiding race conditions, deadlocks, livelocks, and resource starvation.

Unpredictable results when multiple threads are running is not a required condition of thread-safe code, but it is often a by-product. For example, you could have a producer-consumer scheme set up with a shared queue, one producer thread, and few consumer threads, and the data flow might be perfectly predictable. If you start to introduce more consumers you'll see more random looking results.

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>

and js

$(document).ready( function() {
    $('#prev').click(function() {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
                $('#content1').html(result[0]);
            },
        });
    });
});

how to check if List<T> element contains an item with a Particular Property Value

If you have a list and you want to know where within the list an element exists that matches a given criteria, you can use the FindIndex instance method. Such as

int index = list.FindIndex(f => f.Bar == 17);

Where f => f.Bar == 17 is a predicate with the matching criteria.

In your case you might write

int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0) 
{
    // element exists, do what you need
}

Getting full URL of action in ASP.NET MVC

This what you need to do.

@Url.Action(action,controller, null, Request.Url.Scheme)

Catching access violation exceptions?

There is a very easy way to catch any kind of exception (division by zero, access violation, etc.) in Visual Studio using try -> catch (...) block. A minor project settings tweaking is enough. Just enable /EHa option in the project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!

See details here: http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.80).aspx

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

Closing Application with Exit button

Below used main.xml file

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/txt1" android:text="txt1" />
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/txt2"   android:text="txt2"/>
<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/btn1"
    android:text="Close App" />
  </LinearLayout>

and text.java file is below


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class testprj extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            System.exit(0);
        }
    });
    }
 }

Bootstrap 3 Navbar with Logo

Failing to make any of the other answers work in my case (I probably didn't pass the intelligence test) and after some experimentation, this is what I am using (which I believe is very close to the Bootstrap default):

   <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="navbar-header">
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
         </button>
         <div class="navbar-logo">
            <a class="navbar-brand" rel="home" href="@Url.Action("Index", "Home")" title="Home">
               <img src="~/Images/logo.png" class="img-responsive">
            </a>
         </div>
         <div class="collapse navbar-collapse" id="navbar-collapse">
            <ul class="nav navbar-nav">
               <li>@Html.ActionLink("Home", "Index", "Home")</li>
               <li>@Html.ActionLink("Coaching", "Coaching", "Home")</li>
               <li>@Html.ActionLink("Resources", "Resources", "Home")</li>
               <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
               <li>@Html.ActionLink("Blog", "Blog", "Home")</li>
               <li>@Html.ActionLink("About", "About", "Home")</li>
            </ul>
         </div>
      </div>
   </div>

And in the CSS file I have added the following:

.navbar-brand {
   padding-top: 5px;
}

.navbar-collapse {
   float: left;
}

.navbar-logo {
   float: left;
}

Note that @Html.ActionLink() is Razor syntax for an <a> tag. Where it says @Html.ActionLink(...) just replace it with an appropriate <a> tag. Equally where it says @Url.Action(...) replace it with an appropriate URL (no <a> tag in that case).

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

calling parent class method from child class object in java

First of all, it is a bad design, if you need something like that, it is good idea to refactor, e.g. by renaming the method. Java allows calling of overriden method using the "super" keyword, but only one level up in the hierarchy, I am not sure, maybe Scala and some other JVM languages support it for any level.

SQL - How do I get only the numbers after the decimal?

If you want to select only decimal numbers use this WHERE clause:

    (CAST(RIGHT(Myfield, LEN( Myfield)-CHARINDEX('.',Myfield)+1 ) AS FLOAT)) <> 0

If you want a clear list you can sort by decimal/integer:

    CASE WHEN 0 = CAST(RIGHT(Myfield, LEN( Myfield)-CHARINDEX('.',Myfield)+1 ) AS FLOAT) THEN 'Integer' ELSE 'Decimal' END AS Type

How to explain callbacks in plain english? How are they different from calling one function from another function?

Let's pretend you were to give me a potentially long-running task: get the names of the first five unique people you come across. This might take days if I'm in a sparsely populated area. You're not really interested in sitting on your hands while I'm running around so you say, "When you've got the list, call me on my cell and read it back to me. Here's the number.".

You've given me a callback reference--a function that I'm supposed to execute in order to hand off further processing.

In JavaScript it might look something like this:

var lottoNumbers = [];
var callback = function(theNames) {
  for (var i=0; i<theNames.length; i++) {
    lottoNumbers.push(theNames[i].length);
  }
};

db.executeQuery("SELECT name " +
                "FROM tblEveryOneInTheWholeWorld " +
                "ORDER BY proximity DESC " +
                "LIMIT 5", callback);

while (lottoNumbers.length < 5) {
  playGolf();
}
playLotto(lottoNumbers);

This could probably be improved in lots of ways. E.g., you could provide a second callback: if it ends up taking longer than an hour, call the red phone and tell the person that answers that you've timed out.

How can I use a batch file to write to a text file?

    @echo off

    (echo this is in the first line) > xy.txt
    (echo this is in the second line) >> xy.txt

    exit

The two >> means that the second line will be appended to the file (i.e. second line will start after the last line of xy.txt).

this is how the xy.txt looks like:

this is in the first line
this is in the second line

Bash mkdir and subfolders

You can:

mkdir -p folder/subfolder

The -p flag causes any parent directories to be created if necessary.

How do I create a comma-separated list from an array in PHP?

This is how I've been doing it:

$arr = array(1,2,3,4,5,6,7,8,9);

$string = rtrim(implode(',', $arr), ',');

echo $string;

Output:

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

Live Demo: http://ideone.com/EWK1XR

EDIT: Per @joseantgv's comment, you should be able to remove rtrim() from the above example. I.e:

$string = implode(',', $arr);

How to add a touch event to a UIView?

Objective-C:

UIControl *headerView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

Swift:

let headerView = UIControl(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: nextY))
headerView.addTarget(self, action: #selector(myEvent(_:)), for: .touchDown)

The question asks:

How do I add a touch event to a UIView?

It isn't asking for a tap event.

Specifically OP wants to implement UIControlEventTouchDown

Switching the UIView to UIControl is the right answer here because Gesture Recognisers don't know anything about .touchDown, .touchUpInside, .touchUpOutside etc.

Additionally, UIControl inherits from UIView so you're not losing any functionality.

If all you want is a tap, then you can use the Gesture Recogniser. But if you want finer control, like this question asks for, you'll need UIControl.

https://developer.apple.com/documentation/uikit/uicontrol?language=objc https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc

MySql difference between two timestamps in days?

SELECT DATEDIFF(max_date, min_date) as days from my table. This works even if the col max_date and min_date are in string data types.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Save the console.log in Chrome to a file

I have found a great and easy way for this.

  1. In the console - right click on the console logged object

  2. Click on 'Store as global variable'

  3. See the name of the new variable - e.g. it is variableName1

  4. Type in the console: JSON.stringify(variableName1)

  5. Copy the variable string content: e.g. {"a":1,"b":2,"c":3}

enter image description here

  1. Go to some JSON online editor: e.g. https://jsoneditoronline.org/

enter image description here

How to return value from function which has Observable subscription inside?

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())

In above case console.log runs before the promise is resolved so no value is displayed, change it to following

function getValueFromObservable() {
    return this.store
}

getValueFromObservable()
 .subscribe((data: any) => {
    // do something here with data
    console.log(data);
});

other solution is when you need data inside getValueFromObservable to return the observable using of operator and subscribe to the function.

 function getValueFromObservable() {
        return this.store.subscribe((data: any) => {
            // do something with data here
            console.log(data);
            //return again observable.
            return of(data);
       })
    }

    getValueFromObservable()
     .subscribe((data: any) => {
        // do something here with data
        console.log(data);
    });

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

Difference between scaling horizontally and vertically for databases

SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.

But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.

Swift_TransportException Connection could not be established with host smtp.gmail.com

My solution was to change:

  'driver' => 'smtp',

to

 'driver' => 'mail',

In app/config/mail

Hope that helps

Pinging servers in Python

I resolve this with:

def ping(self, host):
    res = False

    ping_param = "-n 1" if system_name().lower() == "windows" else "-c 1"

    resultado = os.popen("ping " + ping_param + " " + host).read()

    if "TTL=" in resultado:
        res = True
    return res

"TTL" is the way to know if the ping is correctly. Saludos

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

How to loop in excel without VBA or macros?

@Nat gave a good answer. But since there is no way to shorten a code, why not use contatenate to 'generate' the code you need. It works for me when I'm lazy (at typing the whole code in the cell).

So what we need is just identify the pattern > use excel to built the pattern 'structure' > add " = " and paste it in the intended cell.

For example, you want to achieve (i mean, enter in the cell) :

=IF('testsheet'!$C$1 <= 99,'testsheet'!$A$1,"") &IF('testsheet'!$C$2 <= 99,'testsheet'!$A$2,"") &IF('testsheet'!$C$3 <= 99,'testsheet'!$A$3,"") &IF('testsheet'!$C$4 <= 99,'testsheet'!$A$4,"") &IF('testsheet'!$C$5 <= 99,'testsheet'!$A$5,"") &IF('testsheet'!$C$6 <= 99,'testsheet'!$A$6,"") &IF('testsheet'!$C$7 <= 99,'testsheet'!$A$7,"") &IF('testsheet'!$C$8 <= 99,'testsheet'!$A$8,"") &IF('testsheet'!$C$9 <= 99,'testsheet'!$A$9,"") &IF('testsheet'!$C$10 <= 99,'testsheet'!$A$10,"") &IF('testsheet'!$C$11 <= 99,'testsheet'!$A$11,"") &IF('testsheet'!$C$12 <= 99,'testsheet'!$A$12,"") &IF('testsheet'!$C$13 <= 99,'testsheet'!$A$13,"") &IF('testsheet'!$C$14 <= 99,'testsheet'!$A$14,"") &IF('testsheet'!$C$15 <= 99,'testsheet'!$A$15,"") &IF('testsheet'!$C$16 <= 99,'testsheet'!$A$16,"") &IF('testsheet'!$C$17 <= 99,'testsheet'!$A$17,"") &IF('testsheet'!$C$18 <= 99,'testsheet'!$A$18,"") &IF('testsheet'!$C$19 <= 99,'testsheet'!$A$19,"") &IF('testsheet'!$C$20 <= 99,'testsheet'!$A$20,"") &IF('testsheet'!$C$21 <= 99,'testsheet'!$A$21,"") &IF('testsheet'!$C$22 <= 99,'testsheet'!$A$22,"") &IF('testsheet'!$C$23 <= 99,'testsheet'!$A$23,"") &IF('testsheet'!$C$24 <= 99,'testsheet'!$A$24,"") &IF('testsheet'!$C$25 <= 99,'testsheet'!$A$25,"") &IF('testsheet'!$C$26 <= 99,'testsheet'!$A$26,"") &IF('testsheet'!$C$27 <= 99,'testsheet'!$A$27,"") &IF('testsheet'!$C$28 <= 99,'testsheet'!$A$28,"") &IF('testsheet'!$C$29 <= 99,'testsheet'!$A$29,"") &IF('testsheet'!$C$30 <= 99,'testsheet'!$A$30,"") &IF('testsheet'!$C$31 <= 99,'testsheet'!$A$31,"") &IF('testsheet'!$C$32 <= 99,'testsheet'!$A$32,"") &IF('testsheet'!$C$33 <= 99,'testsheet'!$A$33,"") &IF('testsheet'!$C$34 <= 99,'testsheet'!$A$34,"") &IF('testsheet'!$C$35 <= 99,'testsheet'!$A$35,"") &IF('testsheet'!$C$36 <= 99,'testsheet'!$A$36,"") &IF('testsheet'!$C$37 <= 99,'testsheet'!$A$37,"") &IF('testsheet'!$C$38 <= 99,'testsheet'!$A$38,"") &IF('testsheet'!$C$39 <= 99,'testsheet'!$A$39,"") &IF('testsheet'!$C$40 <= 99,'testsheet'!$A$40,"") 

I didn't type it, I just use "&" symbol to combine arranged cell in excel (another file, not the file we are working on).

Notice that :

part1 > IF('testsheet'!$C$

part2 > 1 to 40

part3 > <= 99,'testsheet'!$A$

part4 > 1 to 40

part5 > ,"") &

  • Enter part1 to A1, part3 to C1, part to E1.
  • Enter " = A1 " in A2, " = C1 " in C2, " = E1 " in E2.
  • Enter " = B1+1 " in B2, " = D1+1 " in D2.
  • Enter " =A2&B2&C2&D2&E2 " in G2
  • Enter " =I1&G2 " in I2

Now select A2:I2 , and drag it down. Notice that the number did the increament per row added, and the generated text is combined, cell by cell and line by line.

  • Copy I41 content,
  • paste it somewhere, add " = " in front, remove the extra & and the back.

Result = code as you intended.

I've use excel/OpenOfficeCalc to help me generate code for my projects. Works for me, hope it helps for others. (:

What does the colon (:) operator do?

You usually see it in the ternary assignment operator;

Syntax

variable =  `condition ? result 1 : result 2;`

example:

boolean isNegative = number > 0 ? false : true;

which is "equivalent" in nature to the if else

if(number > 0){
    isNegative = false;
}
else{
    isNegative = true;
}

Other than examples given by different posters,

you can also use : to signify a label for a block which you can use in conjunction with continue and break..

for example:

public void someFunction(){
     //an infinite loop
     goBackHere: { //label
          for(int i = 0; i < 10 ;i++){
               if(i == 9 ) continue goBackHere;
          }
     }
}

Editing in the Chrome debugger

I came across this today, when I was playing around with someone else's website.

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

So as a quick work around, and if it works with your situation:

  1. Add a break-point at an earlier point in the script
  2. Reload page
  3. Edit your changes into the code
  4. CTRL + s (save changes)
  5. Unpause the debugger

How to convert .pfx file to keystore with private key?

Using JDK 1.6 or later

It has been pointed out by Justin in the comments below that keytool alone is capable of doing this using the following command (although only in JDK 1.6 and later):

keytool -importkeystore -srckeystore mypfxfile.pfx -srcstoretype pkcs12 
-destkeystore clientcert.jks -deststoretype JKS

Using JDK 1.5 or below

OpenSSL can do it all. This answer on JGuru is the best method that I've found so far.

Firstly make sure that you have OpenSSL installed. Many operating systems already have it installed as I found with Mac OS X.

The following two commands convert the pfx file to a format that can be opened as a Java PKCS12 key store:

openssl pkcs12 -in mypfxfile.pfx -out mypemfile.pem
openssl pkcs12 -export -in mypemfile.pem -out mykeystore.p12 -name "MyCert"

NOTE that the name provided in the second command is the alias of your key in the new key store.

You can verify the contents of the key store using the Java keytool utility with the following command:

keytool -v -list -keystore mykeystore.p12 -storetype pkcs12

Finally if you need to you can convert this to a JKS key store by importing the key store created above into a new key store:

keytool -importkeystore -srckeystore mykeystore.p12 -destkeystore clientcert.jks -srcstoretype pkcs12 -deststoretype JKS

How to list running screen sessions?

In most cases a screen -RRx $username/ will suffice :)

If you still want to list all screens then put the following script in your path and call it screen or whatever you like:

#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
    exec /usr/bin/screen "$@"
else
    shopt -s nullglob
    screens=(/var/run/screen/S-*/*)
    if (( ${#screens[@]} == 0 )); then
        echo "no screen session found in /var/run/screen"
    else
        echo "${screens[@]#*S-}"
    fi
fi

It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.

psql - save results of command to a file

\copy which is a postgres command can work for any user. Don't know if it works for \dt or not, but general syntax is reproduced from the following link Postgres SQL copy syntax

\copy (select * from tempTable limit 100) to 'filenameinquotes' with header delimiter as ','

The above will save the output of the select query in the filename provided as a csv file

EDIT:

For my psql server the following command works this is an older version v8.5

copy (select * from table1) to 'full_path_filename' csv header;

Multiple controllers with AngularJS in single page app

<div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
</div>

<div class="menu" ng-controller="menuController">
    <p>Other stuff here</p>
</div>
///////////////// OR ////////////


  <div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
    <div class="menu" ng-controller="menuController">
        <p>Other stuff here</p>
    </div>
</div>

menuController have access for menu div. And widgetController have access to both.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

onchange event for input type="number"

$("input[type='number']").bind("focus", function() {
    var value = $(this).val();
    $(this).bind("blur", function() {
        if(value != $(this).val()) {
            alert("Value changed");
        }
        $(this).unbind("blur");
    });
});

OR

$("input[type='number']").bind("input", function() {
    alert("Value changed");
});

SQL Server Group By Month

Another approach, that doesn't involve adding columns to the result, is to simply zero-out the day component of the date, so 2016-07-13 and 2016-07-16 would both be 2016-07-01 - thus making them equal by month.

If you have a date (not a datetime) value, then you can zero it directly:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ), [Date] )

If you have datetime values, you'll need to use CONVERT to remove the time-of-day portion:

SELECT
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) ),
    COUNT(*)
FROM
    [Table]
GROUP BY
    DATEADD( day, 1 - DATEPART( day, [Date] ),  CONVERT( date, [Date] ) )

background: fixed no repeat not working on mobile

I've been having the same problem, but now it works. All I had to do was add background-size: cover !important; and it works on my Android device!

The entire code looks like this:

body.page-id-8 #art-main {
  background: #000000 url("link to image") !important;
  background-repeat: no-repeat !important;
  background-position: 50% 50% !important;
  background-attachment: fixed !important;
  background-color: transparent !important;
  background-size: cover !important;
}

Thanks a lot @taylan derinbay and @Vincent!

Return list of items in list greater than some value

In case you are considering using the numpy module, it makes this task very simple, as requested:

import numpy as np

j = np.array([4, 5, 6, 7, 1, 3, 7, 5])

j2 = np.sort(j[j >= 5])

The code inside of the brackets, j >= 5, produces a list of True or False values, which then serve as indices to select the desired values in j. Finally, we sort with the sort function built into numpy.

Tested result (a numpy array):

array([5, 5, 6, 7, 7])

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

jQuery click event not working after adding class

You should use the following:

$('#gentab').on('click', 'a.tabclick', function(event) {
    event.preventDefault();
    var liId = $(this).closest("li").attr("id");
    alert(liId);  
});

This will attach your event to any anchors within the #gentab element, reducing the scope of having to check the whole document element tree and increasing efficiency.

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

node and Error: EMFILE, too many open files

With bagpipe, you just need change

FS.readFile(filename, onRealRead);

=>

var bagpipe = new Bagpipe(10);

bagpipe.push(FS.readFile, filename, onRealRead))

The bagpipe help you limit the parallel. more details: https://github.com/JacksonTian/bagpipe

In Python, how do I split a string and keep the separators?

Another no-regex solution that works well on Python 3

# Split strings and keep separator
test_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']

def split_and_keep(s, sep):
   if not s: return [''] # consistent with string.split()

   # Find replacement character that is not used in string
   # i.e. just use the highest available character plus one
   # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
   p=chr(ord(max(s))+1) 

   return s.replace(sep, sep+p).split(p)

for s in test_strings:
   print(split_and_keep(s, '<'))


# If the unicode limit is reached it will fail explicitly
unicode_max_char = chr(1114111)
ridiculous_string = '<Hello>'+unicode_max_char+'<World>'
print(split_and_keep(ridiculous_string, '<'))

Java equivalent to C# extension methods

Bit late to the party on this question, but in case anyone finds it useful I just created a subclass:

public class ArrayList2<T> extends ArrayList<T> 
{
    private static final long serialVersionUID = 1L;

    public T getLast()
    {
        if (this.isEmpty())
        {
            return null;
        }
        else
        {       
            return this.get(this.size() - 1);
        }
    }
}

Display filename before matching line

How about this, which I managed to achieve thanks, in part, to this post.

You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE), inside several directories with a pattern (e.g. /logsapp1, /logsapp2). Each file has a pattern you want to grep (e.g. "init time"), and you want to have the "init time" of each file, but knowing which file it belongs to.

find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt

Then the outputfilename.txt would be something like

./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms

In general

find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt

Explanation:

find command will search the filenames based in the pattern

then, pipe xargs -I{} will redirect the find output to the {}

which will be the input for grep ""pattern" {}

Then the trick to make grep display the filenames \dev\null

and finally, write the output in file with tee outputfile.txt

This worked for me in grep version 9.0.5 build 1989.

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

Set System.Drawing.Color values

You must use Color.FromArgb method to create new color structure

var newColor = Color.FromArgb(0xCC,0xBB,0xAA);

Opening Android Settings programmatically

I used the code from the most upvoted answer:

startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);

It opens the device settings in the same window, thus got the users of my android application (finnmglas/Launcher) for android stuck in there.

The answer for 2020 and beyond (in Kotlin):

startActivity(Intent(Settings.ACTION_SETTINGS))

It works in my app, should also be working in yours without any unwanted consequences.

How to make inline plots in Jupyter Notebook larger?

Yes, play with figuresize and dpi like so (before you call your subplot):

fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')

As @tacaswell and @Hagne pointed out, you can also change the defaults if it's not a one-off:

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">

or

<form accept-charset="UTF-8">

to force the encoding.

Some references :

http://www.htmlhelp.com/reference/html40/forms/form.html

http://www.w3schools.com/tags/tag_form.asp

EditText underline below text property

Simply change android:backgroundTint in xml code to your color

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

If your rollback segment/undo segment can accomodate the size of the transaction then option 2 is better. Option 1 is useful if you do not have the rollback capacity needed and have to break the large insert into smaller commits so you don't get rollback/undo segment too small errors.

Hide/Show Action Bar Option Menu Item for different fragments

MenuItem Import = menu.findItem(R.id.Import);
  Import.setVisible(false)

htaccess remove index.php from url

This will work, use the following code in .htaccess file RewriteEngine On

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

"The public type <<classname>> must be defined in its own file" error in Eclipse

You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class

How to use lodash to find and return an object from Array?

You can do this easily in vanilla JS:

Using find

_x000D_
_x000D_
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.find(obj => {_x000D_
  return obj.description === view;_x000D_
}).id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
_x000D_
_x000D_

Using filter (original answer)

_x000D_
_x000D_
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.filter(function (el) {_x000D_
  return el.description === view;_x000D_
})[0].id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
_x000D_
_x000D_

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

Format timedelta to string

def td_format(td_object):
    seconds = int(td_object.total_seconds())
    periods = [
        ('year',        60*60*24*365),
        ('month',       60*60*24*30),
        ('day',         60*60*24),
        ('hour',        60*60),
        ('minute',      60),
        ('second',      1)
    ]

    strings=[]
    for period_name, period_seconds in periods:
        if seconds > period_seconds:
            period_value , seconds = divmod(seconds, period_seconds)
            has_s = 's' if period_value > 1 else ''
            strings.append("%s %s%s" % (period_value, period_name, has_s))

    return ", ".join(strings)

Adding Python Path on Windows 7

Working with Windows environment variables is always a horrible experience. Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.

If you use chocolatey, you can install it using choco install rapidee. Otherwise, take a look at http://www.rapidee.com/en/download

Re-reading this, it sounds like a paid shill, but I swear I'm not! It's just been one of the most useful utilities in my toolkit for a while and I'm surprised no one seems to know about it.

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Angular 2 - Setting selected value on dropdown list

I would like to add, [ngValue]="..." support strings, but you need to add simple quotes if it represents a number, like [ngValue]="'...'". It was to complement the Günter Zöchbauer answer.

How to clear a data grid view

The solution is:

dataGridView1.Rows.RemoveAt(0);

Clears the grid and preserves the columns.

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Android Shared preferences for creating one time activity (example)

Setting values in Preference:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.apply();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.

More info:

Using Shared Preferences

Shared Preferences

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

How do I get a computer's name and IP address using VB.NET?

Imports System.Net

Module MainLine
    Sub Main()
        Dim hostName As String = Dns.GetHostName
        Console.WriteLine("Host Name : " & hostName & vbNewLine)
        For Each address In Dns.GetHostEntry(hostName).AddressList()
            Select Case Convert.ToInt32(address.AddressFamily)
                Case 2
                    Console.WriteLine("IP Version 4 Address: " & address.ToString)
                Case 23
                    Console.WriteLine("IP Version 6 Address: " & address.ToString)
            End Select
        Next
        Console.ReadKey()
    End Sub
End Module

Does hosts file exist on the iPhone? How to change it?

I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).

  • Installed OpenSSH onto iPhone via Cydia
  • Using a SFTP client like FileZilla on my computer, I connected to my iPhone
    • Address: [use your phone's IP address or hostname, eg. simophone.local]
    • Username: root
    • Password: alpine
  • Located the /etc/hosts file
  • Made a backup on my computer (in case I want to revert my changes later)
  • Edited the hosts file in a decent text editor (such as Notepad++). See here for an explanation of the hosts file.
  • Uploaded the changes, overwriting the hosts file on the iPhone

The phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.

Simon.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

Why does Firebug say toFixed() is not a function?

Low is a string.

.toFixed() only works with a number.

A simple way to overcome such problem is to use type coercion:

Low = (Low*1).toFixed(..);

The multiplication by 1 forces to code to convert the string to number and doesn't change the value.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Sort & uniq in Linux shell

Using sort -u does less I/O than sort | uniq, but the end result is the same. In particular, if the file is big enough that sort has to create intermediate files, there's a decent chance that sort -u will use slightly fewer or slightly smaller intermediate files as it could eliminate duplicates as it is sorting each set. If the data is highly duplicative, this could be beneficial; if there are few duplicates in fact, it won't make much difference (definitely a second order performance effect, compared to the first order effect of the pipe).

Note that there times when the piping is appropriate. For example:

sort FILE | uniq -c | sort -n

This sorts the file into order of the number of occurrences of each line in the file, with the most repeated lines appearing last. (It wouldn't surprise me to find that this combination, which is idiomatic for Unix or POSIX, can be squished into one complex 'sort' command with GNU sort.)

There are times when not using the pipe is important. For example:

sort -u -o FILE FILE

This sorts the file 'in situ'; that is, the output file is specified by -o FILE, and this operation is guaranteed safe (the file is read before being overwritten for output).

Java JDBC - How to connect to Oracle using Service Name instead of SID

This discussion helped me resolve the issue I was struggling with for days. I looked around all over the internet until I found the answered by Jim Tough on May 18 '11 at 15:17. With that answer I was able to connect. Now I want to give back and help others with a complete example. Here goes:

import java.sql.*; 

public class MyDBConnect {

    public static void main(String[] args) throws SQLException {

        try { 
            String dbURL = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=whatEverYourHostNameIs)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=yourServiceName)))";
            String strUserID = "yourUserId";
            String strPassword = "yourPassword";
            Connection myConnection=DriverManager.getConnection(dbURL,strUserID,strPassword);

            Statement sqlStatement = myConnection.createStatement();
            String readRecordSQL = "select * from sa_work_order where WORK_ORDER_NO = '1503090' ";  
            ResultSet myResultSet = sqlStatement.executeQuery(readRecordSQL);
            while (myResultSet.next()) {
                System.out.println("Record values: " + myResultSet.getString("WORK_ORDER_NO"));
            }
            myResultSet.close();
            myConnection.close();

        } catch (Exception e) {
            System.out.println(e);
        }       
    }
}

Unloading classes in java?

Classes have an implicit strong reference to their ClassLoader instance, and vice versa. They are garbage collected as with Java objects. Without hitting the tools interface or similar, you can't remove individual classes.

As ever you can get memory leaks. Any strong reference to one of your classes or class loader will leak the whole thing. This occurs with the Sun implementations of ThreadLocal, java.sql.DriverManager and java.beans, for instance.

static function in C

pmg's answer is very convincing. If you would like to know how static declarations work at object level then this below info could be interesting to you. I reused the same program written by pmg and compiler it into a .so(shared object) file

Following contents are after dumping the .so file into something human readable

0000000000000675 f1: address of f1 function

000000000000068c f2: address of f2(staticc) function

note the difference in the function address , it means something . For a function that's declared with different address , it can very well signify that f2 lives very far away or in a different segment of the object file.

Linkers use something called PLT(Procedure linkage table) and GOT(Global offsets table) to understand symbols that they have access to link to .

For now think that GOT and PLT magically bind all the addresses and a dynamic section holds information of all these functions that are visible by linker.

After dumping the dynamic section of the .so file we get a bunch of entries but only interested in f1 and f2 function.

The dynamic section holds entry only for f1 function at address 0000000000000675 and not for f2 !

Num: Value Size Type Bind Vis Ndx Name

 9: 0000000000000675    23 FUNC    GLOBAL DEFAULT   11 f1

And thats it !. From this its clear that the linker will be unsuccessful in finding the f2 function since its not in the dynamic section of the .so file.

SQL where datetime column equals today's date?

To get all the records where record created date is today's date Use the code after WHERE clause

WHERE  CAST(Submission_date AS DATE) = CAST( curdate() AS DATE)

How do you create different variable names while in a loop?

Sure you can; it's called a dictionary:

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!

Can I get div's background-image url?

As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})

SVN change username

You could ask your colleague to create a patch, which will collapse all the changes that have been made into a single file that you can apply to your own check out. This will update all of your files appropriately and then you can revert the changes on his side and check yours in.

Replace all occurrences of a String using StringBuilder?

Here is an in place replaceAll that will modify the passed in StringBuilder. I thought that I would post this as I was looking to do replaceAll with out creating a new String.

public static void replaceAll(StringBuilder sb, Pattern pattern, String replacement) {
    Matcher m = pattern.matcher(sb);
    while(m.find()) {
        sb.replace(m.start(), m.end(), replacement);
    }
}

I was shocked how simple the code to do this was (for some reason I thought changing the StringBuilder while using the matcher would throw of the group start/end but it does not).

This is probably faster than the other regex answers because the pattern is already compiled and your not creating a new String but I didn't do any benchmarking.

how can I connect to a remote mongo server from Mac OS terminal

Another way to do this is:

mongo mongodb://mongoDbIPorDomain:port

Create code first, many to many, with additional fields in association table

I want to propose a solution where both flavors of a many-to-many configuration can be achieved.

The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet.

This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.

The model:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<Member> Members { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class MemberCommentView
{
    public int MemberID { get; set; }
    public int CommentID { get; set; }
    public int Something { get; set; }
    public string SomethingElse { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }
}

The configuration:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

public class MemberConfiguration : EntityTypeConfiguration<Member>
{
    public MemberConfiguration()
    {
        HasKey(x => x.MemberID);

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.FirstName).HasColumnType("varchar(512)");
        Property(x => x.LastName).HasColumnType("varchar(512)")

        // configure many-to-many through internal EF EntitySet
        HasMany(s => s.Comments)
            .WithMany(c => c.Members)
            .Map(cs =>
            {
                cs.ToTable("MemberComment");
                cs.MapLeftKey("MemberID");
                cs.MapRightKey("CommentID");
            });
    }
}

public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
    public CommentConfiguration()
    {
        HasKey(x => x.CommentID);

        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Message).HasColumnType("varchar(max)");
    }
}

public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
    public MemberCommentViewConfiguration()
    {
        ToTable("MemberCommentView");
        HasKey(x => new { x.MemberID, x.CommentID });

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Something).HasColumnType("int");
        Property(x => x.SomethingElse).HasColumnType("varchar(max)");

        // configure one-to-many targeting the Join Table view
        // making all of its properties available
        HasRequired(a => a.Member).WithMany(b => b.MemberComments);
        HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
    }
}

The context:

using System.Data.Entity;

public class MyContext : DbContext
{
    public DbSet<Member> Members { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<MemberCommentView> MemberComments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new MemberConfiguration());
        modelBuilder.Configurations.Add(new CommentConfiguration());
        modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());

        OnModelCreatingPartial(modelBuilder);
     }
}

From Saluma's (@Saluma) answer

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

This still works...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

...but could now also be...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.Comments)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

This still works...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

...but could now also be...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        m.Comments
    })
        .ToList();

If you want to remove a comment from a member

var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith

member.Comments.Remove(comment);

If you want to Include() a member's comments

var member = context.Members
    .Where(m => m.FirstName == "John", m.LastName == "Smith")
    .Include(m => m.Comments);

This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

How to format code in Xcode?

  1. Select the block of code that you want indented.

  2. Right-click (or, on Mac, Ctrl-click).

  3. Structure → Re-indent

How do I get DOUBLE_MAX?

You are looking for the float.h header.

How to sort an array of ints using a custom comparator?

java 8:

Arrays.stream(new int[]{10,4,5,6,1,2,3,7,9,8}).boxed().sorted((e1,e2)-> e2-e1).collect(Collectors.toList());

Get last key-value pair in PHP array

If you have an array

$last_element = array_pop(array);

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

Prevent multiple instances of a given app in .NET?

Use VB.NET! No: really ;)

using Microsoft.VisualBasic.ApplicationServices;

The WindowsFormsApplicationBase from VB.Net provides you with a "SingleInstace" Property, which determines other Instances and let only one Instance run.

What is the Maximum Size that an Array can hold?

Per MSDN it is

By default, the maximum size of an Array is 2 gigabytes (GB).

In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

However, the array will still be limited to a total of 4 billion elements.

Refer Here http://msdn.microsoft.com/en-us/library/System.Array(v=vs.110).aspx

Note: Here I am focusing on the actual length of array by assuming that we will have enough hardware RAM.

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

Binding Listbox to List<object> in WinForms

Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:

listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();

Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)

How to add font-awesome to Angular 2 + CLI project

After some experimentation I managed to get the following working:

  1. Install with npm:

    npm install font-awesome --save
    
  2. add to angular-cli-build.js file:

    vendorNpmFiles : [
        font-awesome/**/*.+(css|css.map|otf|eot|svg|ttf|woff|woff2)',
    ]
    
  3. add to index.html

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">
    

The key was to include the font file types in the angular-cli-build.js file

.+(css|css.map|otf|eot|svg|ttf|woff|woff2)

Box-Shadow on the left side of the element only

box-shadow: -15px 0px 17px -7px rgba(0,0,0,0.75);

The first px value is the "Horizontal Length" set to -15px to position the shadow towards the left, the next px value is set to 0 so the shadow top and bottom is centred to minimise the top and bottom shadow.

The third value(17px) is known as the blur radius. The higher the number, the more blurred the shadow will be. And then last px value -7px is The spread radius, a positive value increases the size of the shadow, a negative value decreases the size of the shadow, at -7px it keeps the shadow from appearing above and below the item.

reference: CSS Box Shadow Property

PHP how to get value from array if key is in a variable

It should work the way you intended.

$array = array('value-0', 'value-1', 'value-2', 'value-3', 'value-4', 'value-5' /* … */);
$key = 4;
$value = $array[$key];
echo $value; // value-4

But maybe there is no element with the key 4. If you want to get the fiveth item no matter what key it has, you can use array_slice:

$value = array_slice($array, 4, 1);

How to change color of Toolbar back button in Android?

Use this:

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/white</item> 
</style>

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

Test if string is a number in Ruby on Rails

no you're just using it wrong. your is_number? has an argument. you called it without the argument

you should be doing is_number?(mystring)

How to pass multiple parameters in a querystring

Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz

before you redirect:

string queryString = Request.QueryString.ToString();

Response.Redirect("page.aspx?"+queryString);

How to define a two-dimensional array?

In case if you need a matrix with predefined numbers you can use the following code:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

File name without extension name VBA

You could always use Replace() since you're performing this on the workbook's Name, which will almost certainly end with .xlsm by virtue of using VBA.

Using ActiveWorkbook per your example:

Replace(Application.ActiveWorkbook.Name, ".xlsm", "")

Using ThisWorkbook:

Replace(Application.ThisWorkbook.Name, ".xlsm", "")

Undo a Git merge that hasn't been pushed yet

With git reflog check which commit is one prior the merge (git reflog will be a better option than git log). Then you can reset it using:

git reset --hard commit_sha

There's also another way:

git reset --hard HEAD~1

It will get you back 1 commit.

Be aware that any modified and uncommitted/unstashed files will be reset to their unmodified state. To keep them either stash changes away or see --merge option below.


As @Velmont suggested below in his answer, in this direct case using:

git reset --hard ORIG_HEAD

might yield better results, as it should preserve your changes. ORIG_HEAD will point to a commit directly before merge has occurred, so you don't have to hunt for it yourself.


A further tip is to use the --merge switch instead of --hard since it doesn't reset files unnecessarily:

git reset --merge ORIG_HEAD

--merge

Resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added).

Execution order of events when pressing PrimeFaces p:commandButton

It failed because you used ajax="false". This fires a full synchronous request which in turn causes a full page reload, causing the oncomplete to be never fired (note that all other ajax-related attributes like process, onstart, onsuccess, onerror and update are also never fired).

That it worked when you removed actionListener is also impossible. It should have failed the same way. Perhaps you also removed ajax="false" along it without actually understanding what you were doing. Removing ajax="false" should indeed achieve the desired requirement.


Also is it possible to execute actionlistener and oncomplete simultaneously?

No. The script can only be fired before or after the action listener. You can use onclick to fire the script at the moment of the click. You can use onstart to fire the script at the moment the ajax request is about to be sent. But they will never exactly simultaneously be fired. The sequence is as follows:

  • User clicks button in client
  • onclick JavaScript code is executed
  • JavaScript prepares ajax request based on process and current HTML DOM tree
  • onstart JavaScript code is executed
  • JavaScript sends ajax request from client to server
  • JSF retrieves ajax request
  • JSF processes the request lifecycle on JSF component tree based on process
  • actionListener JSF backing bean method is executed
  • action JSF backing bean method is executed
  • JSF prepares ajax response based on update and current JSF component tree
  • JSF sends ajax response from server to client
  • JavaScript retrieves ajax response
    • if HTTP response status is 200, onsuccess JavaScript code is executed
    • else if HTTP response status is 500, onerror JavaScript code is executed
  • JavaScript performs update based on ajax response and current HTML DOM tree
  • oncomplete JavaScript code is executed

Note that the update is performed after actionListener, so if you were using onclick or onstart to show the dialog, then it may still show old content instead of updated content, which is poor for user experience. You'd then better use oncomplete instead to show the dialog. Also note that you'd better use action instead of actionListener when you intend to execute a business action.

See also:

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

Shrinking navigation bar when scrolling down (bootstrap3)

You can combine "scroll" and "scrollstop" events in order to achieve desired result:

$(window).on("scroll",function(){
   $('nav').addClass('shrink');
}); 
$(window).on("scrollstop",function(){
   $('nav').removeClass('shrink');
}); 

Date only from TextBoxFor()

<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>

Use <Image> with a local file

If loading images dynamically one can create a .js file like following and do require in it.

export const data = [
  {
    id: "1",
    text: "blablabla1",
    imageLink: require('../assets/first-image.png')
  },
  {
    id: "2",
    text: "blablabla2",
    imageLink: require('../assets/second-image.png')
  }
]

In your component .js file

import {data} from './js-u-created-above';
...

function UsageExample({item}) {
   <View>
     <Image style={...} source={item.imageLink} /> 
   </View>
}

function ComponentName() {
   const elements = data.map(item => <UsageExample key={item.id} item={item}/> );
   return (...);
}

How to format a duration in java? (e.g format H:MM:SS)

If you're using a version of Java prior to 8... you can use Joda Time and PeriodFormatter. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using Duration for the most part - you can then call toPeriod (specifying whatever PeriodType you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a Period which you can format.

If you're using Java 8 or later: I'd normally suggest using java.time.Duration to represent the duration. You can then call getSeconds() or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a single negative sign in the output string. So something like:

public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}

Formatting this way is reasonably simple, if annoyingly manual. For parsing it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

Programmatically Hide/Show Android Soft Keyboard

Adding this to your code android:focusableInTouchMode="true" will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.

ie: In your app_list_view.xml file

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    android:focusableInTouchMode="true">
    <EditText 
        android:id="@+id/filter_edittext"       
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Search" 
        android:inputType="text" 
        android:maxLines="1"/>
    <ListView 
        android:id="@id/android:list" 
        android:layout_height="fill_parent"
        android:layout_weight="1.0" 
        android:layout_width="fill_parent" 
        android:focusable="true" 
        android:descendantFocusability="beforeDescendants"/>
</LinearLayout> 

------------------ EDIT: To Make keyboard appear on startup -----------------------

This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:paddingLeft="20dip"  
    android:paddingRight="20dip">
    <EditText 
        android:id="@+id/userName" 
        android:singleLine="true" 
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content" 
        android:hint="Username"  
        android:imeOptions="actionDone" 
        android:inputType="text"
        android:maxLines="1"
       />
    <EditText 
        android:id="@+id/password" 
        android:password="true" 
        android:singleLine="true"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="Password" />
    <ScrollView
        android:id="@+id/ScrollView01"  
        android:layout_height="fill_parent"   
        android:layout_width="fill_parent"> 
    </ScrollView>
</LinearLayout>

If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.

Hope this is what you are looking for.

Cheers!

How to update column with null value

Remember to look if your column can be null. You can do that using

mysql> desc my_table;

If your column cannot be null, when you set the value to null it will be the cast value to it.

Here a example

mysql> create table example ( age int not null, name varchar(100) not null );
mysql> insert into example values ( null, "without num" ), ( 2 , null );
mysql> select * from example;
+-----+-------------+
| age | name        |
+-----+-------------+
|   0 | without num |
|   2 |             |
+-----+-------------+
2 rows in set (0.00 sec)

mysql> select * from example where age is null or name is null;
Empty set (0.00 sec)

How do you find out which version of GTK+ is installed on Ubuntu?

To make the answer more general than Ubuntu (I have Redhat):

gtk is usually installed under /usr, but possibly in other locations. This should be visible in environment variables. Check with

env | grep gtk

Then try to find where your gtk files are stored. For example, use locate and grep.

locate gtk | grep /usr/lib

In this way, I found /usr/lib64/gtk-2.0, which contains the subdirectory 2.10.0, which contains many .so library files. My conclusion is that I have gtk+ version 2.10. This is rather consistent with the rpm command on Redhat: rpm -qa | grep gtk2, so I think my conclusion is right.

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

Select all 'tr' except the first one

Since tr:not(:first-child) is not supported by IE 6, 7, 8. You can use the help of jQuery. You may find it here

HTML image bottom alignment inside DIV container

<div> with some proportions

div {
  position: relative;
  width: 100%;
  height: 100%;
}

<img>'s with their own proportions

img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: auto; /* to keep proportions */
  height: auto; /* to keep proportions */
  max-width: 100%; /* not to stand out from div */
  max-height: 100%; /* not to stand out from div */
  margin: auto auto 0; /* position to bottom and center */
}

How can INSERT INTO a table 300 times within a loop in SQL?

You may try it like this:

DECLARE @i int = 0
WHILE @i < 300 
BEGIN
    SET @i = @i + 1
    /* your code*/
END

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

Just change

import android.widget.Toolbar;

To

import android.support.v7.widget.Toolbar;

Programmatically select a row in JTable

You use the available API of JTable and do not try to mess with the colors.

Some selection methods are available directly on the JTable (like the setRowSelectionInterval). If you want to have access to all selection-related logic, the selection model is the place to start looking

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

What is the "right" JSON date format?

The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);

How to submit form on change of dropdown list?

Just ask assistance of JavaScript.

<select onchange="this.form.submit()">
    ...
</select>

See also:

How to determine when Fragment becomes visible in ViewPager

Another solution posted here overriding setPrimaryItem in the pageradapter by kris larson almost worked for me. But this method is called multiple times for each setup. Also I got NPE from views, etc. in the fragment as this is not ready the first few times this method is called. With the following changes this worked for me:

private int mCurrentPosition = -1;

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    super.setPrimaryItem(container, position, object);

    if (position == mCurrentPosition) {
        return;
    }

    if (object instanceof MyWhizBangFragment) {
        MyWhizBangFragment fragment = (MyWhizBangFragment) object;

        if (fragment.isResumed()) {
            mCurrentPosition = position;
            fragment.doTheThingYouNeedToDoOnBecomingVisible();
        }
    }
}

Converting File to MultiPartFile

Solution without Mocking class, Java9+ and Spring only.

FileItem fileItem = new DiskFileItemFactory().createItem("file",
    Files.probeContentType(file.toPath()), false, file.getName());

try (InputStream in = new FileInputStream(file); OutputStream out = fileItem.getOutputStream()) {
    in.transferTo(out);
} catch (Exception e) {
    throw new IllegalArgumentException("Invalid file: " + e, e);
}

CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Okay here's a simple fix for getting 'done' button to show and work in an app in both iOS 9, iOS 8 and below when I got similar error. It could be observed after running an app and viewing it via 'View's Hierarchy' (i.e. clicking on the 'View Hierarchy' icon from Debug Area bar while app is running on device and inspecting your views in Storyboard), that the keyboard is presented on different windows in iOS 9 compared to iOS 8 and below versions and have to be accounted for. addButtonToKeyboard

- (id)addButtonToKeyboard
{
if (!doneButton)
{
   // create custom button
    UIButton * doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(-2, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(saveNewLead:) forControlEvents:UIControlEventTouchUpInside];
}

NSArray *windows = [[UIApplication sharedApplication] windows];
//Check to see if running below iOS 9,then return the second window which bears the keyboard   
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
return windows[windows.count - 2];
}
else {
UIWindow* keyboardWithDoneButtonWindow = [ windows lastObject];
return keyboardWithDoneButtonWindow;
    }
}

And this is how you could removeKeyboardButton from keyboard if you want.

- (void)removeKeyboardButton {

id windowTemp = [self addButtonToKeyboard];

if (windowTemp) {

    for (UIView *doneButton in [windowTemp subviews]) {
        if ([doneButton isKindOfClass:[UIButton class]]) {
            [doneButton setHidden:TRUE];
        }
    }
  }
}

How to convert ZonedDateTime to Date?

You can convert ZonedDateTime to an instant, which you can use directly with Date.

Date.from(java.time.ZonedDateTime.now().toInstant());

How to use Session attributes in Spring-mvc

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.

shell init issue when click tab, what's wrong with getcwd?

Just change the directory to another one and come back. Probably that one has been deleted or moved.

Get a pixel from HTML Canvas?

Yes sure, provided you have its context. (See how to get canvas context here.)

var imgData = context.getImageData(0,0,canvas.width,canvas.height);
// { data: [r,g,b,a,r,g,b,a,r,g,..], ... }

function getPixel(imgData, index) {
  var i = index*4, d = imgData.data;
  return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
}

// AND/OR

function getPixelXY(imgData, x, y) {
  return getPixel(imgData, y*imgData.width+x);
}



PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray

var
  idt = imgData, // See previous code snippet
  a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
  b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]

a[0] = 255 // Does nothing
getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]

b[0] = 255 // Mutates the original imgData.data
getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]

// Or use it in the function
function getPixel(imgData, index) {
  var i = index*4, d = imgData.data;
  return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
}

You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.

Formatting Numbers by padding with leading zeros in SQL Server

Another way, just for completeness.

DECLARE @empNumber INT = 7123
SELECT STUFF('000000', 6-LEN(@empNumber)+1, LEN(@empNumber), @empNumber)

Or, as per your query

SELECT STUFF('000000', 6-LEN(EmployeeID)+1, LEN(EmployeeID), EmployeeID) 
         AS EmployeeCode
FROM dbo.RequestItems
WHERE ID=0

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

Datatable vs Dataset

in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

How to initialize a vector in C++

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

Adding an arbitrary line to a matplotlib plot in ipython notebook

It's not too late for the newcomers.

plt.axvline(x, color='r')

It takes the range of y as well, using ymin and ymax.

require_once :failed to open stream: no such file or directory

set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");

Also this can help.See set_include_path()

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

Restful API service

I know @Martyn does not want full code, but I think this annotation its good for this question:

10 Open Source Android Apps which every Android developer must look into

Foursquared for Android is open-source, and have an interesting code pattern interacting with the foursquare REST API.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

What is a semaphore?

Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.

It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.

Here is a very pedagogic example in C# :-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TheNightclub
{
    public class Program
    {
        public static Semaphore Bouncer { get; set; }

        public static void Main(string[] args)
        {
            // Create the semaphore with 3 slots, where 3 are available.
            Bouncer = new Semaphore(3, 3);

            // Open the nightclub.
            OpenNightclub();
        }

        public static void OpenNightclub()
        {
            for (int i = 1; i <= 50; i++)
            {
                // Let each guest enter on an own thread.
                Thread thread = new Thread(new ParameterizedThreadStart(Guest));
                thread.Start(i);
            }
        }

        public static void Guest(object args)
        {
            // Wait to enter the nightclub (a semaphore to be released).
            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
            Bouncer.WaitOne();          

            // Do some dancing.
            Console.WriteLine("Guest {0} is doing some dancing.", args);
            Thread.Sleep(500);

            // Let one guest out (release one semaphore).
            Console.WriteLine("Guest {0} is leaving the nightclub.", args);
            Bouncer.Release(1);
        }
    }
}

Easiest way to loop through a filtered list with VBA?

Call MyMacro()

ActiveCell.Offset(1, 0).Activate

Do Until Selection.EntireRow.Hidden = False
If Selection.EntireRow.Hidden = True Then
ActiveCell.Offset(1, 0).Activate
End If
Loop

C# Macro definitions in Preprocessor

There is no direct equivalent to C-style macros in C#, but inlined static methods - with or without #if/#elseif/#else pragmas - is the closest you can get:

        /// <summary>
        /// Prints a message when in debug mode
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Log(object message) {
#if DEBUG
            Console.WriteLine(message);
#endif
        }

        /// <summary>
        /// Prints a formatted message when in debug mode
        /// </summary>
        /// <param name="format">A composite format string</param>
        /// <param name="args">An array of objects to write using format</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void Log(string format, params object[] args) {
#if DEBUG
            Console.WriteLine(format, args);
#endif
        }

        /// <summary>
        /// Computes the square of a number
        /// </summary>
        /// <param name="x">The value</param>
        /// <returns>x * x</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static double Square(double x) {
            return x * x;
        }

        /// <summary>
        /// Wipes a region of memory
        /// </summary>
        /// <param name="buffer">The buffer</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void ClearBuffer(ref byte[] buffer) {
            ClearBuffer(ref buffer, 0, buffer.Length);
        }

        /// <summary>
        /// Wipes a region of memory
        /// </summary>
        /// <param name="buffer">The buffer</param>
        /// <param name="offset">Start index</param>
        /// <param name="length">Number of bytes to clear</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) {
            fixed(byte* ptrBuffer = &buffer[offset]) {
                for(int i = 0; i < length; ++i) {
                    *(ptrBuffer + i) = 0;
                }
            }
        }

This works perfectly as a macro, but comes with a little drawback: Methods marked as inlined will be copied to the reflection part of your assembly like any other "normal" method.

Correct mime type for .mp4

According to RFC 4337 § 2, video/mp4 is indeed the correct Content-Type for MPEG-4 video.

Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.

Reloading a ViewController

If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:

[self viewDidLoad];

again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.

[self viewDidLoad]; [self viewWillAppear:YES];

I think there should be a more specific solution like refresh button in browser.

Undefined behavior and sequence points

I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:

f (a,b)

previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.

Format a message using MessageFormat.format() in Java

Just be sure you have used double apostrophe ('')

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

Edit:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. ...

Any unmatched quote is treated as closed at the end of the given pattern. For example, pattern string "'{0}" is treated as pattern "'{0}'".

Source http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html

How to pass a list from Python, by Jinja2 to JavaScript

To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the safe Jinja filter, to prevent your data from being htmlescaped.

You can achieve this by doing something like that:

The view

import json

@app.route('/')
def my_view():
    data = [1, 'foo']
    return render_template('index.html', data=json.dumps(data))

The template

<script type="text/javascript">
    function test_func(data) {
        console.log(data);
    }
    test_func({{ data|safe }})
</script>

Edit - exact answer

So, to achieve exactly what you want (loop over a list of items, and pass them to a javascript function), you'd need to serialize every item in your list separately. Your code would then look like this:

The view

import json

@app.route('/')
def my_view():
    data = [1, "foo"]
    return render_template('index.html', data=map(json.dumps, data))

The template

{% for item in data %}
    <span onclick=someFunction({{ item|safe }});>{{ item }}</span>
{% endfor %}

Edit 2

In my example, I use Flask, I don't know what framework you're using, but you got the idea, you just have to make it fit the framework you use.

Edit 3 (Security warning)

NEVER EVER DO THIS WITH USER-SUPPLIED DATA, ONLY DO THIS WITH TRUSTED DATA!

Otherwise, you would expose your application to XSS vulnerabilities!

How to add icon inside EditText view in Android ?

You can set drawableLeft in the XML as suggested by marcos, but you might also want to set it programmatically - for example in response to an event. To do this use the method setCompoundDrawablesWithIntrincisBounds(int, int, int, int):

EditText editText = findViewById(R.id.myEditText);

// Set drawables for left, top, right, and bottom - send 0 for nothing
editTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

Numpy converting array from float to strings

If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimalS: http://docs.python.org/library/decimal.html.

In python 2.7 and higher you can directly convert a float to a decimal object.

json call with C#

just continuing what @Mulki made with his code

public string WebRequestinJson(string url, string postData)
{
    string ret = string.Empty;

    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }

    HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
    Stream resStream = resp.GetResponseStream();
    StreamReader reader = new StreamReader(resStream);
    ret = reader.ReadToEnd();

    return ret;
}

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I had the same issue. Turned out I used some external jars (apache poi 4.1.2) which were compiled with 1.8. Solved it by changing Java Build Path JRE to 1.8.

svn : how to create a branch from certain revision of trunk

$ svn copy http://svn.example.com/repos/calc/trunk@192 \
   http://svn.example.com/repos/calc/branches/my-calc-branch \
   -m "Creating a private branch of /calc/trunk."

Where 192 is the revision you specify

You can find this information from the SVN Book, specifically here on the page about svn copy

In reactJS, how to copy text to clipboard?

<input
value={get(data, "api_key")}
styleName="input-wrap"
title={get(data, "api_key")}
ref={apikeyObjRef}
/>
  <div
onClick={() => {
  apikeyObjRef.current.select();
  if (document.execCommand("copy")) {
    document.execCommand("copy");
  }
}}
styleName="copy"
>
  ??
</div>

How does HTTP_USER_AGENT work?

The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

Returning JSON from PHP to JavaScript?

Here are a couple of things missing in the previous answers:

  1. Set header in your PHP:

    header('Content-type: application/json');
    echo json_encode($array);
    
  2. json_encode() can return a JavaScript array instead of JavaScript object, see:
    Returning JSON from a PHP Script
    This could be important to know in some cases as arrays and objects are not the same.

Query to display all tablespaces in a database and datafiles

In oracle, generally speaking, there are number of facts that I will mention in following section:

  • Each database can have many Schema/User (Logical division).
  • Each database can have many tablespaces (Logical division).
  • A schema is the set of objects (tables, indexes, views, etc) that belong to a user.
  • In Oracle, a user can be considered the same as a schema.
  • A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. You may have a tablespace for application data and an additional one for application indexes.

Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.

However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.

So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:

SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'

ElasticSearch: Unassigned Shards, how to fix?

Might help, but I had this issue when trying to run ES in embedded mode. Fix was to make sure the Node had local(true) set.

Ignore files that have already been committed to a Git repository

There is another suggestion maybe for the slow guys like me =) Put the .gitignore file into your repository root not in .git folder. Cheers!

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

Remove first 4 characters of a string with PHP

If you’re using a multi-byte character encoding and do not just want to remove the first four bytes like substr does, use the multi-byte counterpart mb_substr. This does of course will also work with single-byte strings.