Programs & Examples On #Redmine

Redmine is a flexible project management web application. Written using the Ruby on Rails framework, it is cross-platform and cross-database.

Python POST binary data

Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - Processing by AttachmentsController#upload as XML. I guess maybe there's a bug in docs and to post binary data you should try using http://redmine/uploads url instead of http://redmine/uploads.xml.

Btw, I highly recommend very good and very popular Requests library for http in Python. It's much better than what's in the standard lib (urllib2). It supports authentication as well but I skipped it for brevity here.

import requests
with open('./x.png', 'rb') as f:
    data = f.read()
res = requests.post(url='http://httpbin.org/post',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

# let's check if what we sent is what we intended to send...
import json
import base64

assert base64.b64decode(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data

UPDATE

To find out why this works with Requests but not with urllib2 we have to examine the difference in what's being sent. To see this I'm sending traffic to http proxy (Fiddler) running on port 8888:

Using Requests

import requests

data = 'test data'
res = requests.post(url='http://localhost:8888',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

we see

POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 9
Content-Type: application/octet-stream
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vista

test data

and using urllib2

import urllib2

data = 'test data'    
req = urllib2.Request('http://localhost:8888', data)
req.add_header('Content-Length', '%d' % len(data))
req.add_header('Content-Type', 'application/octet-stream')
res = urllib2.urlopen(req)

we get

POST http://localhost:8888/ HTTP/1.1
Accept-Encoding: identity
Content-Length: 9
Host: localhost:8888
Content-Type: application/octet-stream
Connection: close
User-Agent: Python-urllib/2.7

test data

I don't see any differences which would warrant different behavior you observe. Having said that it's not uncommon for http servers to inspect User-Agent header and vary behavior based on its value. Try to change headers sent by Requests one by one making them the same as those being sent by urllib2 and see when it stops working.

Android Open External Storage directory(sdcard) for storing file

hope it's worked for you:

File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");

This will give u sdcard path:

File path = Environment.getExternalStorageDirectory();

Try this:

String pathName = "/mnt/";

or try this:

String pathName = "/storage/";

Twitter API - Display all tweets with a certain hashtag?

The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.

Assign null to a SqlParameter

With one line of code, try this:

var piParameter = new SqlParameter("@AgeIndex", AgeItem.AgeIndex ?? (object)DBNull.Value);

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

You missed the closing parenthesis at the end:

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

How to update TypeScript to latest version with npm?

My solution to this error was to update the typescript version with this command:

npm install -g typescript@latest as I was using Windows. However on Mac this can also be doable by sudo npm install -g typescript@latest

Is it possible to read from a InputStream with a timeout?

I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Rename the output.config produced by svcutil.exe to app.config. it worked for me.

Why does configure say no C compiler found when GCC is installed?

Maybe gcc is not in your path? Try finding gcc using which gcc and add it to your path if it's not already there.

Cloning an Object in Node.js

npm install node-v8-clone

Fastest cloner, it open native clone method from node.js

var clone = require('node-v8-clone').clone;
var newObj = clone(obj, true); //true - deep recursive clone

How to write a simple Java program that finds the greatest common divisor between two numbers?

You can also do it in a three line method:

public static int gcd(int x, int y){
  return (y == 0) ? x : gcd(y, x % y);
}

Here, if y = 0, x is returned. Otherwise, the gcd method is called again, with different parameter values.

Python Regex - How to Get Positions and Values of Matches

Taken from

Regular Expression HOWTO

span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.

>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

Combine that with:

In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.

>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)

you should be able to do something on the order of

for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

Support for the experimental syntax 'classProperties' isn't currently enabled

I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc

{
  "presets": [
    [
      "@babel/preset-react",
      { "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
    ]
  ],
  "plugins": [["@babel/plugin-proposal-class-properties"]]
}

css transform, jagged edges in chrome

For me it was the perspective CSS property that did the trick:

-webkit-perspective: 1000;

Completely illogical in my case as I use no 3d transitions, but works nonetheless.

Why can't I shrink a transaction log file, even after backup?

Have you tried from within SQL Server management studio with the GUI. Right click on the database, tasks, shrink, files. Select filetype=Log.

I worked for me a week ago.

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

How can I extract audio from video with ffmpeg?

ffmpeg -i sample.avi will give you the audio/video format info for your file. Make sure you have the proper libraries configured to parse the input streams. Also, make sure that the file isn't corrupt.

Encrypt Password in Configuration Files?

The big point, and the elephant in the room and all that, is that if your application can get hold of the password, then a hacker with access to the box can get hold of it too!

The only way somewhat around this, is that the application asks for the "master password" on the console using Standard Input, and then uses this to decrypt the passwords stored on file. Of course, this completely makes is impossible to have the application start up unattended along with the OS when it boots.

However, even with this level of annoyance, if a hacker manages to get root access (or even just access as the user running your application), he could dump the memory and find the password there.

The thing to ensure, is to not let the entire company have access to the production server (and thereby to the passwords), and make sure that it is impossible to crack this box!

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.

So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.

My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.

Take nth column in a text file

If your file contains n lines, then your script has to read the file n times; so if you double the length of the file, you quadruple the amount of work your script does — and almost all of that work is simply thrown away, since all you want to do is loop over the lines in order.

Instead, the best way to loop over the lines of a file is to use a while loop, with the condition-command being the read builtin:

while IFS= read -r line ; do
    # $line is a single line of the file, as a single string
    : ... commands that use $line ...
done < input_file.txt

In your case, since you want to split the line into an array, and the read builtin actually has special support for populating an array variable, which is what you want, you can write:

while read -r -a line ; do
    echo ""${line[1]}" "${line[3]}"" >> out.txt
done < /path/of/my/text

or better yet:

while read -r -a line ; do
    echo "${line[1]} ${line[3]}"
done < /path/of/my/text > out.txt

However, for what you're doing you can just use the cut utility:

cut -d' ' -f2,4 < /path/of/my/text > out.txt

(or awk, as Tom van der Woerdt suggests, or perl, or even sed).

svn cleanup: sqlite: database disk image is malformed

The SVN cleanup didn't work. The SVN folder on my local system got corrupted. So I just deleted the folder, recreated a new one, and updated from SVN. That solved the problem!

What is the 'open' keyword in Swift?

Read open as

open for inheritance in other modules

I repeat open for inheritance in other modules. So an open class is open for subclassing in other modules that include the defining module. Open vars and functions are open for overriding in other modules. Its the least restrictive access level. It is as good as public access except that something that is public is closed for inheritance in other modules.

From Apple Docs:

Open access applies only to classes and class members, and it differs from public access as follows:

  1. Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.

  2. Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.

  3. Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.

  4. Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

How to get all options of a select using jQuery?

Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item

$('#nCS1 > option').each((index, obj) => {
   console.log($(obj).val());
})

_x000D_
_x000D_
printOptionValues = () => {_x000D_
_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).val());_x000D_
  })_x000D_
_x000D_
}_x000D_
_x000D_
printOptionTexts = () => {_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).text());_x000D_
  })_x000D_
}_x000D_
_x000D_
printSelectedItemText = () => {_x000D_
  console.log($('#nCS1 option:selected').text());_x000D_
}_x000D_
_x000D_
printSelectedItemValue = () => {_x000D_
  console.log($('#nCS1 option:selected').val());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select size="1" id="nCS1" name="nCS1" class="form-control" >_x000D_
     <option value="22">Australia</option>_x000D_
          <option value="23">Brunei</option>_x000D_
          <option value="33">Cambodia</option>_x000D_
          <option value="32">Canada</option>_x000D_
          <option value="27">Dubai</option>_x000D_
          <option value="28">Indonesia</option>_x000D_
          <option value="25">Malaysia</option>    _x000D_
</select>_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionValues()' value='print option values' />_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionTexts()' value='print option texts' />_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
_x000D_
_x000D_
_x000D_

Converting a char to uppercase

f = Character.toUpperCase(f);
l = Character.toUpperCase(l);

Can you write nested functions in JavaScript?

Yes, it is possible to write and call a function nested in another function.

Try this:

function A(){
   B(); //call should be B();
   function B(){

   }
}

Android/Java - Date Difference in days

One another way:

public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) {
        fromDay = calendarStartOfDay(fromDay);
        toDay = calendarStartOfDay(toDay);
        long from = fromDay.getTimeInMillis();
        long to = toDay.getTimeInMillis();
        return (int) TimeUnit.MILLISECONDS.toDays(to - from);
    }

How to get current time and date in Android

    long totalSeconds = currentTimeMillis / 1000;
    int currentSecond = (int)totalSeconds % 60;

    long totalMinutes = totalSeconds / 60;
    int currentMinute = (int)totalMinutes % 60;

    long totalHours = totalMinutes / 60;
    int currentHour = (int)totalHours % 12;

    TextView tvTime = findViewById(R.id.tvTime);
    tvTime.setText((currentHour + OR - TIME YOU ARE FROM GMT) + ":" + currentMinute + ":" + currentSecond);

How can I view array structure in JavaScript with alert()?

I'd recommend using toString().

Ex. alert(array.toString()), or console.log(array.toString())

How to find a min/max with Ruby

You can do

[5, 10].min

or

[4, 7].max

They come from the Enumerable module, so anything that includes Enumerable will have those methods available.

v2.4 introduces own Array#min and Array#max, which are way faster than Enumerable's methods because they skip calling #each.

@nicholasklick mentions another option, Enumerable#minmax, but this time returning an array of [min, max].

[4, 5, 7, 10].minmax
=> [4, 10]

Git, fatal: The remote end hung up unexpectedly

I got this error when I had misspelt my remote branch name

What is the purpose of a question mark after a type (for example: int? myVariable)?

It means that the value type in question is a nullable type

Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample
{
  static void Main()
  {
      int? num = null;

      // Is the HasValue property true?
      if (num.HasValue)
      {
          System.Console.WriteLine("num = " + num.Value);
      }
      else
      {
          System.Console.WriteLine("num = Null");
      }

      // y is set to zero
      int y = num.GetValueOrDefault();

      // num.Value throws an InvalidOperationException if num.HasValue is false
      try
      {
          y = num.Value;
      }
      catch (System.InvalidOperationException e)
      {
          System.Console.WriteLine(e.Message);
      }
  }
}

Flutter: Run method on Widget build complete

In flutter version 1.14.6, Dart version 28.

Below is what worked for me, You simply just need to bundle everything you want to happen after the build method into a separate method or function.

@override
void initState() {
super.initState();
print('hello girl');

WidgetsBinding.instance
    .addPostFrameCallback((_) => afterLayoutWidgetBuild());

}

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How can I access my localhost from my Android device?

Simple. First and foremost make your your android device and computer is connected on thee same network.e.g router Open command prompt by windows+R and search for cmd then open. On the command type ipconfig and get the ipv4 address.

NB: Firewall blocks access of your computer along network so you need to turn off firewall for the network if either public or private.

How to turn off firewall Open control panel > System and security > windows firewall > on the left pane select turn on and off windows firewall. > Then select turn off windows firewall(not recommended)

You are done

then open your mobile device and run your ip address 192.168.1.xxx


What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Using Mockito to test abstract classes

The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.

use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

Example:

public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.

How to switch between python 2.7 to python 3 from command line?

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

Can RDP clients launch remote applications and not desktops

This is called RemoteApp. To use it you need to install Terminal Services, which is now called Remote Desktop Services.

https://social.technet.microsoft.com/wiki/contents/articles/10817.publishing-remoteapps-in-windows-server-2012.aspx

Visual Studio 2017 - Git failed with a fatal error

I'm going to add a solution here that the previous answers have not already mentioned, but this is what fixed it for me.

  1. Navigate to C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\ and delete the Git folder.

  2. Make sure that there is no version of Git installed on your system, remove it by going to Control Panel ? Program and Features (TortoiseGit does not need to be removed from my experience, just native git installations).

  3. Open up the Visual Studio 2017 installer and untick "Git For Windows" in installation options.

  4. Head over to the Git website and install the latest version of Git for Windows.

  5. Go back into the Visual Studio installer and tick "Git for Windows" again. It will not download a new version even though it may look like it is. After that is done, your Git should be fine with VSTS and TF Explorer.

How can I selectively merge or pick changes from another branch in Git?

It is not exactly what you were looking for, but it was useful to me:

git checkout -p <branch> -- <paths> ...

It is a mix of some answers.

Select query with date condition

hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::

select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;

FOR EXAMPLE:

select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name     | BIRTH      |
+----------+------------+
| bowser   | 1979-09-11 |
| chirpy   | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+

FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN

mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;

FOR EXAMPLE mysql>

select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name     |
+----------+
| bowser   |
| chirpy   |
| whistler |
+----------+
3 rows in set (0.00 sec)

"could not find stored procedure"

One more possibility to check. Listing here because it just happened to me and wasn't mentioned;-)

I had accidentally added a space character on the end of the name. Many hours of trying things before I finally noticed it. It's always something simple after you figure it out.

Ordering issue with date values when creating pivot tables

If you want to use a column with 24/11/15 (for 24th November 2015) in your Pivot that will sort correctly, you can make sure it is properly formatted by doing the following - highlight the column, go to Data – Text to Columns – click Next twice, then select “Date” and use the default of DMY (or select as applicable to your data) and click ok

When you pivot now you should see it sorting properly as we have properly formatted that column to be a date field so Excel can work with it

Convert file path to a file URI?

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

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

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

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

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

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

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

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

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

'str' object does not support item assignment in Python

Python strings are immutable so what you are trying to do in C will be simply impossible in python. You will have to create a new string.

I would like to read some characters from a string and put it into other string.

Then use a string slice:

>>> s1 = 'Hello world!!'
>>> s2 = s1[6:12]
>>> print s2
world!

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

WPF Binding StringFormat Short Date String

Try this:

<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />

which is culture sensitive and requires .NET 3.5 SP1 or above.

NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.

There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post

However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.

If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.

Source

One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

The other way is to set the converter culture in the binding:

<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />

Though this doesn't allow you to localise the output.

unique combinations of values in selected columns in pandas data frame and count

Slightly related, I was looking for the unique combinations and I came up with this method:

def unique_columns(df,columns):

    result = pd.Series(index = df.index)

    groups = meta_data_csv.groupby(by = columns)
    for name,group in groups:
       is_unique = len(group) == 1
       result.loc[group.index] = is_unique

    assert not result.isnull().any()

    return result

And if you only want to assert that all combinations are unique:

df1.set_index(['A','B']).index.is_unique

Set textbox to readonly and background color to grey in jquery

Can add disable like below and can get data on submit. something like this .. DEMO

Html

<input type="hidden" name="email" value="email" />
<input type="text" id="dis" class="disable" value="email"   name="email" >

JS

 $("#dis").attr('disabled','disabled');

CSS

    .disable { opacity : .35; background-color:lightgray; border:1px solid gray;}

What is mapDispatchToProps?

mapStateToProps receives the state and props and allows you to extract props from the state to pass to the component.

mapDispatchToProps receives dispatch and props and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.

I find this only saves you from having to do dispatch(actionCreator()) within your component thus making it a bit easier to read.

https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments

Convert datetime to Unix timestamp and convert it back in python

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

Get changes from master into branch in Git

Easy way

# 1. Create a new remote branch A base on last master
# 2. Checkout A
# 3. Merge aq to A

how to fetch array keys with jQuery?

Using jQuery, easiest way to get array of keys from object is following:

$.map(obj, function(element,index) {return index})

In your case, it will return this array: ["alfa", "beta"]

Integer value in TextView

just found an advance and most currently used method to set string in textView

textView.setText(String.valueOf(YourIntegerNumber));

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How to show what a commit did?

I found out that "git show --stat" is the best out of all here, gives you a brief summary of the commit, what files did you add and modify without giving you whole bunch of stuff, especially if you changed a lot files.

How to update one file in a zip archive

From zip(1):

When given the name of an existing zip archive, zip will replace identically named entries in the zip archive or add entries for new names.

So just use the zip command as you normally would to create a new .zip file containing only that one file, except the .zip filename you specify will be the existing archive.

How to select an option from drop down using Selenium WebDriver C#?

You must create a select element object from the drop down list.

 using OpenQA.Selenium.Support.UI;

 // select the drop down list
 var education = driver.FindElement(By.Name("education"));
 //create select element object 
 var selectElement = new SelectElement(education);

 //select by value
 selectElement.SelectByValue("Jr.High"); 
 // select by text
 selectElement.SelectByText("HighSchool");

More info here

How to import classes defined in __init__.py

Yes, it is possible. You might also want to define __all__ in __init__.py files. It's a list of modules that will be imported when you do

from lib import *

Angular 2 TypeScript how to find element in Array

You could combine .find with arrow functions and destructuring. Take this example from MDN.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

SVN: Folder already under version control but not comitting?

I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:

Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)

You will see the following Eclipse error message:

org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control

After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)

You will see the following message dialog: "File list is empty"

Press cancel and refresh the project in Eclipse. Your project should be under version control again.

Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.

How many times does each value appear in a column?

You can use CountIf. Put the following code in B1 and drag down the whole column

=COUNTIF(A:A,A1)

It will look like this:

enter image description here

How to select the first row of each group?

The pattern is group by keys => do something to each group e.g. reduce => return to dataframe

I thought the Dataframe abstraction is a bit cumbersome in this case so I used RDD functionality

 val rdd: RDD[Row] = originalDf
  .rdd
  .groupBy(row => row.getAs[String]("grouping_row"))
  .map(iterableTuple => {
    iterableTuple._2.reduce(reduceFunction)
  })

val productDf = sqlContext.createDataFrame(rdd, originalDf.schema)

Remove characters from a string

Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.

How to return a custom object from a Spring Data JPA GROUP BY query

Solution for JPQL queries

This is supported for JPQL queries within the JPA specification.

Step 1: Declare a simple bean class

package com.path.to;

public class SurveyAnswerStatistics {
  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(String answer, Long cnt) {
    this.answer = answer;
    this.count  = cnt;
  }
}

Step 2: Return bean instances from the repository method

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query("SELECT " +
           "    new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Important notes

  1. Make sure to provide the fully-qualified path to the bean class, including the package name. For example, if the bean class is called MyBean and it is in package com.path.to, the fully-qualified path to the bean will be com.path.to.MyBean. Simply providing MyBean will not work (unless the bean class is in the default package).
  2. Make sure to call the bean class constructor using the new keyword. SELECT new com.path.to.MyBean(...) will work, whereas SELECT com.path.to.MyBean(...) will not.
  3. Make sure to pass attributes in exactly the same order as that expected in the bean constructor. Attempting to pass attributes in a different order will lead to an exception.
  4. Make sure the query is a valid JPA query, that is, it is not a native query. @Query("SELECT ..."), or @Query(value = "SELECT ..."), or @Query(value = "SELECT ...", nativeQuery = false) will work, whereas @Query(value = "SELECT ...", nativeQuery = true) will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new and com.path.to.MyBean are not valid SQL keywords, the RDBMS then throws an exception.

Solution for native queries

As noted above, the new ... syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ... syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new keyword since it is not part of the SQL standard.

In situations like these, bean classes need to be replaced with Spring Data Projection interfaces.

Step 1: Declare a projection interface

package com.path.to;

public interface SurveyAnswerStatistics {
  String getAnswer();

  int getCnt();
}

Step 2: Return projected properties from the query

public interface SurveyRepository extends CrudRepository<Survey, Long> {
    @Query(nativeQuery = true, value =
           "SELECT " +
           "    v.answer AS answer, COUNT(v) AS cnt " +
           "FROM " +
           "    Survey v " +
           "GROUP BY " +
           "    v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
}

Use the SQL AS keyword to map result fields to projection properties for unambiguous mapping.

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.


An Analogy...

Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. Give me a ring back when you've got the information!

At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.


Imagine if the conversation had gone like this instead;

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. I'll wait.

And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.


This is asynchronous vs. synchronous behavior

This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).

Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.

var outerScopeVar;    
var img = document.createElement('img');

// Here we register the callback function.
img.onload = function() {
    // Code within this function will be executed once the image has loaded.
    outerScopeVar = this.width;
};

// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';
alert(outerScopeVar);

In the code above, we're asking JavaScript to load lolcat.png, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar).

This is why we see the alert showing undefined; since the alert() is processed immediately, rather than after the image has been loaded.

In order to fix our code, all we have to do is move the alert(outerScopeVar) code into the callback function. As a consequence of this, we no longer need the outerScopeVar variable declared as a global variable.

var img = document.createElement('img');

img.onload = function() {
    var localScopeVar = this.width;
    alert(localScopeVar);
};

img.src = 'lolcat.png';

You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.

Therefore, in all of our examples, the function() { /* Do something */ } is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!

* Technically you can use eval() as well, but eval() is evil for this purpose


How do I keep my caller waiting?

You might currently have some code similar to this;

function getWidthOfImage(src) {
    var outerScopeVar;

    var img = document.createElement('img');
    img.onload = function() {
        outerScopeVar = this.width;
    };
    img.src = src;
    return outerScopeVar;
}

var width = getWidthOfImage('lolcat.png');
alert(width);

However, we now know that the return outerScopeVar happens immediately; before the onload callback function has updated the variable. This leads to getWidthOfImage() returning undefined, and undefined being alerted.

To fix this, we need to allow the function calling getWidthOfImage() to register a callback, then move the alert'ing of the width to be within that callback;

function getWidthOfImage(src, cb) {     
    var img = document.createElement('img');
    img.onload = function() {
        cb(this.width);
    };
    img.src = src;
}

getWidthOfImage('lolcat.png', function (width) {
    alert(width);
});

... as before, note that we've been able to remove the global variables (in this case width).

How can I check the size of a file in a Windows batch script?

Just an idea:

You may get the filesize by running command "dir":

>dir thing

Then again it returns so many things.

Maybe you can get it from there if you look for it.

But I am not sure.

How to resolve git stash conflict without commit?

According to git stash questions, after fixing the conflict, git add <file> is the right course of action.

It was after reading this comment that I understood that the changes are automatically added to the index (by design). That's why git add <file> completes the conflict resolution process.

Python xticks in subplots

There are two ways:

  1. Use the axes methods of the subplot object (e.g. ax.set_xticks and ax.set_xticklabels) or
  2. Use plt.sca to set the current axes for the pyplot state machine (i.e. the plt interface).

As an example (this also illustrates using setp to change the properties of all of the subplots):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=3, ncols=4)

# Set the ticks and ticklabels for all axes
plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'],
        yticks=[1, 2, 3])

# Use the pyplot interface to change just one subplot...
plt.sca(axes[1, 1])
plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red')

fig.tight_layout()
plt.show()

enter image description here

Git merge is not possible because I have unmerged files

I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...

What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"

You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...

You can leave this state with git merge --abort and now try to execute other commands.

In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...

How to insert data into SQL Server

You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.

 using(SqlConnection openCon=new SqlConnection("your_connection_String"))
    {
      string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

      using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
       {
         querySaveStaff.Connection=openCon;
         querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
         .....
         openCon.Open();

         querySaveStaff.ExecuteNonQuery();
       }
     }

Unable to install boto3

I have faced the same issue and also not using virtual environment. easy_install is working for me.

easy_install boto3

Accessing dict keys like an attribute?

Just to add some variety to the answer, sci-kit learn has this implemented as a Bunch:

class Bunch(dict):                                                              
    """ Scikit Learn's container object                                         

    Dictionary-like object that exposes its keys as attributes.                 
    >>> b = Bunch(a=1, b=2)                                                     
    >>> b['b']                                                                  
    2                                                                           
    >>> b.b                                                                     
    2                                                                           
    >>> b.c = 6                                                                 
    >>> b['c']                                                                  
    6                                                                           
    """                                                                         

    def __init__(self, **kwargs):                                               
        super(Bunch, self).__init__(kwargs)                                     

    def __setattr__(self, key, value):                                          
        self[key] = value                                                       

    def __dir__(self):                                                          
        return self.keys()                                                      

    def __getattr__(self, key):                                                 
        try:                                                                    
            return self[key]                                                    
        except KeyError:                                                        
            raise AttributeError(key)                                           

    def __setstate__(self, state):                                              
        pass                       

All you need is to get the setattr and getattr methods - the getattr checks for dict keys and the moves on to checking for actual attributes. The setstaet is a fix for fix for pickling/unpickling "bunches" - if inerested check https://github.com/scikit-learn/scikit-learn/issues/6196

iCheck check if checkbox is checked

You could wrap all your checkboxes in a parent class and check the length of .checked..

if( $('.your-parent-class').find('.checked').length ){
  $(".hide").toggle();
}

How to download/checkout a project from Google Code in Windows?

Another simple solution without the TortoiseSVN overhead is RapidSVN. It is a lightweight open-source SVN client that is easy to install and easy to use.

The Download SVN tool did also work quite well, but it had problems with SVN repositories that don't provide a web interface. RapidSVN works fine with those.

How to coerce a list object to type 'double'

There are problems with some data. Consider:

as.double(as.character("2.e")) # This results in 2

Another solution:

get_numbers <- function(X) {
    X[toupper(X) != tolower(X)] <- NA
    return(as.double(as.character(X)))
}

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

Flask-SQLAlchemy how to delete all rows in a single table

Try delete:

models.User.query.delete()

From the docs: Returns the number of rows deleted, excluding any cascades.

How do I display a decimal value to 2 decimal places?

The top-rated answer describes a method for formatting the string representation of the decimal value, and it works.

However, if you actually want to change the precision saved to the actual value, you need to write something like the following:

public static class PrecisionHelper
{
    public static decimal TwoDecimalPlaces(this decimal value)
    {
        // These first lines eliminate all digits past two places.
        var timesHundred = (int) (value * 100);
        var removeZeroes = timesHundred / 100m;

        // In this implementation, I don't want to alter the underlying
        // value.  As such, if it needs greater precision to stay unaltered,
        // I return it.
        if (removeZeroes != value)
            return value;

        // Addition and subtraction can reliably change precision.  
        // For two decimal values A and B, (A + B) will have at least as 
        // many digits past the decimal point as A or B.
        return removeZeroes + 0.01m - 0.01m;
    }
}

An example unit test:

[Test]
public void PrecisionExampleUnitTest()
{
    decimal a = 500m;
    decimal b = 99.99m;
    decimal c = 123.4m;
    decimal d = 10101.1000000m;
    decimal e = 908.7650m

    Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("500.00"));

    Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("99.99"));

    Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("123.40"));

    Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("10101.10"));

    // In this particular implementation, values that can't be expressed in
    // two decimal places are unaltered, so this remains as-is.
    Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
        Is.EqualTo("908.7650"));
}

Check string length in PHP

[0]=> string(141) means that $message is an array, not string, and $message[0] is a string with 141 characters in length.

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

Adding blur effect to background in swift

This one always keeps the right frame:

public extension UIView {

    @discardableResult
    public func addBlur(style: UIBlurEffect.Style = .extraLight) -> UIVisualEffectView {
        let blurEffect = UIBlurEffect(style: style)
        let blurBackground = UIVisualEffectView(effect: blurEffect)
        addSubview(blurBackground)
        blurBackground.translatesAutoresizingMaskIntoConstraints = false
        blurBackground.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        blurBackground.topAnchor.constraint(equalTo: topAnchor).isActive = true
        blurBackground.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        blurBackground.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        return blurBackground
    }
}

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

How to calculate percentage when old value is ZERO

use below code, as this is 100% growth rate in case of 0 to any number :

IFERROR((NEW-OLD)/OLD,100%)

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:

http://www.youtube.com/watch?v=y1c7WFMMkZ4

When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.

What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.

PHPExcel how to set cell value dynamically

I don't have much experience working with php but from a logic standpoint this is what I would do.

  1. Loop through your result set from MySQL
  2. In Excel you should already know what A,B,C should be because those are the columns and you know how many columns you are returning.
  3. The row number can just be incremented with each time through the loop.

Below is some pseudocode illustrating this technique:

    for (int i = 0; i < MySQLResults.count; i++){
         $objPHPExcel->getActiveSheet()->setCellValue('A' . (string)(i + 1), MySQLResults[i].name); 
        // Add 1 to i because Excel Rows start at 1, not 0, so row will always be one off
         $objPHPExcel->getActiveSheet()->setCellValue('B' . (string)(i + 1), MySQLResults[i].number);
         $objPHPExcel->getActiveSheet()->setCellValue('C' . (string)(i + 1), MySQLResults[i].email);
    }

Search code inside a Github project

Update January 2013: a brand new search has arrived!, based on elasticsearch.org:

A search for stat within the ruby repo will be expressed as stat repo:ruby/ruby, and will now just workTM.
(the repo name is not case sensitive: test repo:wordpress/wordpress returns the same as test repo:Wordpress/Wordpress)

enter image description here

Will give:

enter image description here

And you have many other examples of search, based on followers, or on forks, or...


Update July 2012 (old days of Lucene search and poor code indexing, combined with broken GUI, kept here for archive):

The search (based on SolrQuerySyntax) is now more permissive and the dreaded "Invalid search query. Try quoting it." is gone when using the default search selector "Everything":)

(I suppose we can all than Tim Pease, which had in one of his objectives "hacking on improved search experiences for all GitHub properties", and I did mention this Stack Overflow question at the time ;) )

Here is an illustration of a grep within the ruby code: it will looks for repos and users, but also for what I wanted to search in the first place: the code!

GitHub more permissive search results


Initial answer and illustration of the former issue (Sept. 2012 => March 2012)

You can use the advanced search GitHub form:

  • Choose Code, Repositories or Users from the drop-down and
  • use the corresponding prefixes listed for that search type.

For instance, Use the repo:username/repo-name directive to limit the search to a code repository.
The initial "Advanced Search" page includes the section:

Code Search:

The Code search will look through all of the code publicly hosted on GitHub. You can also filter by :

  • the language language:
  • the repository name (including the username) repo:
  • the file path path:

So if you select the "Code" search selector, then your query grepping for a text within a repo will work:

Good Search selector


What is incredibly unhelpful from GitHub is that:

  • if you forget to put the right search selector (here "Code"), you will get an error message:
    "Invalid search query. Try quoting it."

Wrong selector for the code filer

  • the error message doesn't help you at all.
    No amount of "quoting it" will get you out of this error.

  • once you get that error message, you don't get the sections reminding you of the right association between the search selectors ("Repositories", "Users" or "Language") and the (right) search filters (here "repo:").
    Any further attempt you do won't display those associations (selectors-filters) back. Only the error message you see above...
    The only way to get back those arrays is by clicking the "Advance Search" icon:

Advance Search Icon on GitHub

  • the "Everything" search selector, which is the default, is actually the wrong one for all of the search filters! Except "language:"...
    (You could imagine/assume that "Everything" would help you to pick whatever search selector actually works with the search filter "repo:", but nope. That would be too easy)

  • you cannot specify the search selector you want through the "Advance Search" field alone!
    (but you can for "language:", even though "Search Language" is another combo box just below the "Search for" 'type' one...)

Wrong search selector


So, the user's experience usually is as follows:

  • you click "Advanced Search", glance over those sections of filters, and notice one you want to use: "repo:"
  • you make a first advanced search "repo:jruby/jruby stat", but with the default Search selector "Everything"
    => FAIL! (and the arrays displaying the association "Selectors-Filters" is gone)
  • you notice that "Search for" selector thingy, select the first choice "Repositories" ("Dah! I want to search within repositories...")
    => FAIL!
  • dejected, you select the next choice of selectors (here, "Users"), without even looking at said selector, just to give it one more try...
    => FAIL!
  • "Screw this, GitHub search is broken! I'm outta here!"
    ...
    (GitHub advanced search is actually not broken. Only their GUI is...)

So, to recap, if you want to "grep for something inside a Github project's code", as the OP Ben Humphreys, don't forget to select the "Code" search selector...

Python to print out status bar and percentage

import progressbar
import time

# Function to create  
def animated_marker():
    widgets = ['Loading: ', progressbar.Bar('=', '[', ']', '-'), progressbar.Percentage()]
    bar = progressbar.ProgressBar(max_value=200,widgets=widgets).start() 
      
    for i in range(200): 
        time.sleep(0.1)
        bar.update(i+1)
    bar.finish()

# Driver's code 
animated_marker()

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

Is it possible to change the package name of an Android app on Google Play?

No, you cannot change package name unless you're okay with publishing it as a new app in Play Store:

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application. Android manual confirms it as well here:

Caution: Once you publish your application, you cannot change the package name. The package name defines your application's identity, so if you change it, then it is considered to be a different application and users of the previous version cannot update to the new version. If you're okay with publishing new version of your app as a completely new entity, you can do it of course - just remove old app from Play Store (if you want) and publish new one, with different package name.

Overlay a background-image with an rgba background-color

_x000D_
_x000D_
/* Working method */_x000D_
.tinted-image {_x000D_
  background: _x000D_
    /* top, transparent red, faked with gradient */ _x000D_
    linear-gradient(_x000D_
      rgba(255, 0, 0, 0.45), _x000D_
      rgba(255, 0, 0, 0.45)_x000D_
    ),_x000D_
    /* bottom, image */_x000D_
    url(https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg);_x000D_
    height: 1280px;_x000D_
    width: 960px;_x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
.tinted-image p {_x000D_
    color: #fff;_x000D_
    padding: 100px;_x000D_
  }
_x000D_
<div class="tinted-image">_x000D_
  _x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam distinctio, temporibus tempora a eveniet quas  qui veritatis sunt perferendis harum!</p>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

source: https://css-tricks.com/tinted-images-multiple-backgrounds/

Convert byte to string in Java

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.

How do I escape ampersands in XML so they are rendered as entities in HTML?

In my case I had to change it to %26.

I needed to escape & in a URL. So &amp; did not work out for me. The urlencode function changes & to %26. This way neither XML nor the browser URL mechanism complained about the URL.

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

contenteditable change events

This thread was very helpful while I was investigating the subject.

I've modified some of the code available here into a jQuery plugin so it is in a re-usable form, primarily to satisfy my needs but others may appreciate a simpler interface to jumpstart using contenteditable tags.

https://gist.github.com/3410122

Update:

Due to its increasing popularity the plugin has been adopted by Makesites.org

Development will continue from here:

https://github.com/makesites/jquery-contenteditable

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

How to get temporary folder for current user

try

Environment.GetEnvironmentVariable("temp");

How to get the request parameters in Symfony 2?

$request = Request::createFromGlobals();
$getParameter = $request->get('getParameter');

How to move the layout up when the soft keyboard is shown android

Make use of Relative layout it will adjust the view so that you can see that view while typing the text

How to workaround 'FB is not defined'?

It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

Pattern matching using a wildcard

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

Edit: Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)

How to run a program automatically as admin on Windows 7 at startup?

Setting compatibility of your application to administrator (Run theprogram as an administrator).

Plug it into task scheduler, then turn off UAC.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

I was using Xming and got similar error. Following steps were taken to fix the issue:

  1. In Xming launch check the box no access control.
  2. In putty ran the following command: DISPLAY=XXX.XXX.XXX.XX:0.0; export DISPLAY

Replace XXX.XXX.XXX.XX with your IP address.

Importing from a relative path in Python

Doing a relative import is absolulutely OK! Here's what little 'ol me does:

#first change the cwd to the script path
scriptPath = os.path.realpath(os.path.dirname(sys.argv[0]))
os.chdir(scriptPath)

#append the relative location you want to import from
sys.path.append("../common")

#import your module stored in '../common'
import common.py

GridLayout and Row/Column Span Woe

It feels pretty hacky, but I managed to get the correct look by adding an extra column and row beyond what is needed. Then I filled the extra column with a Space in each row defining a height and filled the extra row with a Space in each col defining a width. For extra flexibility, I imagine these Space sizes could be set in code to provide something similar to weights. I tried to add a screenshot, but I do not have the reputation necessary.

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="9"
android:orientation="horizontal"
android:rowCount="8" >

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="1" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="2" />

<Button
    android:layout_gravity="fill_vertical"
    android:layout_rowSpan="4"
    android:text="3" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill"
    android:layout_rowSpan="2"
    android:text="4" />

<Button
    android:layout_columnSpan="3"
    android:layout_gravity="fill_horizontal"
    android:text="5" />

<Button
    android:layout_columnSpan="2"
    android:layout_gravity="fill_horizontal"
    android:text="6" />

<Space
    android:layout_width="36dp"
    android:layout_column="0"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="1"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="2"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="3"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="4"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="5"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="6"
    android:layout_row="7" />

<Space
    android:layout_width="36dp"
    android:layout_column="7"
    android:layout_row="7" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="0" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="1" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="2" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="3" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="4" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="5" />

<Space
    android:layout_height="36dp"
    android:layout_column="8"
    android:layout_row="6" />

</GridLayout>

screenshot

Laravel where on relationship object

I created a custom query scope in BaseModel (my all models extends this class):

/**
 * Add a relationship exists condition (BelongsTo).
 *
 * @param  Builder        $query
 * @param  string|Model   $relation   Relation string name or you can try pass directly model and method will try guess relationship
 * @param  mixed          $modelOrKey
 * @return Builder|static
 */
public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
{
    if ($relation instanceof Model && $modelOrKey === null) {
        $modelOrKey = $relation;
        $relation   = Str::camel(class_basename($relation));
    }

    return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
        return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
    });
}

You can use it in many contexts for example:

Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1 

Furthermore, you can try to omit relationship name and pass just model:

$participant = Participant::find(1);
Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance

Uncaught TypeError: undefined is not a function while using jQuery UI

This is about the HTML parse mechanism.

The HTML parser will parse the HTML content from top to bottom. In your script logic,

jQuery('#datetimepicker')

will return an empty instance because the element has not loaded yet.

You can use

$(function(){ your code here });

or

$(document).ready(function(){ your code here });

to parse HTML element firstly, and then do your own script logics.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

This gives me the most reliable results:

Sub RangeToPicture()
  Dim FileName As String: FileName = "C:\file.bmp"
  Dim rPrt As Range: Set rPrt = ThisWorkbook.Sheets("Sheet1").Range("A1:C6")

  Dim chtObj As ChartObject
  rPrt.CopyPicture xlScreen, xlBitmap
  Set chtObj = ActiveSheet.ChartObjects.Add(1, 1, rPrt.Width, rPrt.Height)
  chtObj.Activate
  ActiveChart.Paste
  ActiveChart.Export FileName
  chtObj.Delete
End Sub

Remove an array element and shift the remaining ones

Programming Hub randomly provided a code snippet which in fact does reduce the length of an array

for (i = position_to_remove; i < length_of_array; ++i) {
        inputarray[i] = inputarray[i + 1];
}

Not sure if it's behaviour that was added only later. It does the trick though.

Merge DLL into EXE?

I answered a similar question for VB.NET. It shouldn't however be too hard to convert. You embedd the DLL's into your Ressource folder and on the first usage, the AppDomain.CurrentDomain.AssemblyResolve event gets fired.

If you want to reference it during development, just add a normal DLL reference to your project.

Embedd a DLL into a project

Changing the action of a form with JavaScript/jQuery

jQuery (1.4.2) gets confused if you have any form elements named "action". You can get around this by using the DOM attribute methods or simply avoid having form elements named "action".

<form action="foo">
  <button name="action" value="bar">Go</button>
</form>

<script type="text/javascript">
  $('form').attr('action', 'baz'); //this fails silently
  $('form').get(0).setAttribute('action', 'baz'); //this works
</script>

Restore a postgres backup file using the command line?

Below is my version of pg_dump which I use to restore the database:

pg_restore -h localhost -p 5432 -U postgres -d my_new_database my_old_database.backup

or use psql:

psql -h localhost -U postgres -p 5432 my_new_database < my_old_database.backup

where -h host, -p port, -u login username, -d name of database

"relocation R_X86_64_32S against " linking Error

Assuming you are generating a shared library, most probably what happens is that the variant of liblog4cplus.a you are using wasn't compiled with -fPIC. In linux, you can confirm this by extracting the object files from the static library and checking their relocations:

ar -x liblog4cplus.a  
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'

If the output is empty, then the static library is not position-independent and cannot be used to generate a shared object.

Since the static library contains object code which was already compiled, providing the -fPIC flag won't help.

You need to get ahold of a version of liblog4cplus.a compiled with -fPIC and use that one instead.

Can I use DIV class and ID together in CSS?

#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

Linq to Entities - SQL "IN" clause

Seriously? You folks have never used

where (t.MyTableId == 1 || t.MyTableId == 2 || t.MyTableId == 3)

Document directory path of Xcode Device Simulator

NSLog below code somewhere in "AppDelegate", run your project and follow the path. This will be easy for you to get to the documents rather than searching randomly inside "~/Library/Developer/CoreSimulator/Devices/"

Objective-C

NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

Swift
If you are using Swift 1.2, use the code below which will only output in development when using the Simulator because of the #if #endif block:

#if arch(i386) || arch(x86_64)
  let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
  NSLog("Document Path: %@", documentsPath)
#endif

Copy your path from "/Users/ankur/Library/Developer/CoreSimulator/Devices/7BA821..." go to "Finder" and then "Go to Folder" or command + shift + g and paste your path, let the mac take you to your documents directory :)

Setting table row height

line-height only works when it is larger then the current height of the content of <td> . So, if you have a 50x50 icon in the table, the tr line-height will not make a row smaller than 50px (+ padding).

Since you've already set the padding to 0 it must be something else,
for example a large font-size inside td that is larger than your 14px.

How do I set default values for functions parameters in Matlab?

if you would use octave you could do it like this - but sadly matlab does not support this possibility

function hello (who = "World")
  printf ("Hello, %s!\n", who);
endfunction

(taken from the doc)

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to determine whether a Pandas Column contains a particular value

found = df[df['Column'].str.contains('Text_to_search')]
print(found.count())

the found.count() will contains number of matches

And if it is 0 then means string was not found in the Column.

AngularJS Directive Restrict A vs E

One of the pitfalls as I know is IE problem with custom elements. As quoted from the docs:

3) you do not use custom element tags such as (use the attribute version instead)

4) if you do use custom element tags, then you must take these steps to make IE 8 and below happy

<!doctype html>
  <html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
    <head>
      <!--[if lte IE 8]>
        <script>
          document.createElement('ng-include');
          document.createElement('ng-pluralize');
          document.createElement('ng-view');

          // Optionally these for CSS
          document.createElement('ng:include');
          document.createElement('ng:pluralize');
          document.createElement('ng:view');
        </script>
      <![endif]-->
    </head>
    <body>
      ...
    </body>
  </html>

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

How to delete from a text file, all lines that contain a specific string?

You can use sed to replace lines in place in a file. However, it seems to be much slower than using grep for the inverse into a second file and then moving the second file over the original.

e.g.

sed -i '/pattern/d' filename      

or

grep -v "pattern" filename > filename2; mv filename2 filename

The first command takes 3 times longer on my machine anyway.

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

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

<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1

Concatenate String in String Objective-c

You would normally use -stringWithFormat here.

NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

When you say 2^8 you get 256, but the numbers in computers terms begins from the number 0. So, then you got the 255, you can probe it in a internet mask for the IP or in the IP itself.

255 is the maximum value of a 8 bit integer : 11111111 = 255

Does that help?

How do I find files with a path length greater than 260 characters in Windows?

do a dir /s /b > out.txt and then add a guide at position 260

In powershell cmd /c dir /s /b |? {$_.length -gt 260}

Android: ProgressDialog.show() crashes with getApplicationContext

Had a similar problem with (compatibility) Fragments in which using a getActivity() within ProgressDialog.show() crashes it. I'd agree that it is because of timing.

A possible fix:

mContext = getApplicationContext();

if (mContext != null) {
    mProgressDialog = ProgressDialog.show(mContext, "", getString(R.string.loading), true);
}

instead of using

mProgressDialog = ProgressDialog.show(getApplicationContext(), "", getString(R.string.loading), true);

Place the mContext as early as possible to give it more time to grab the context. There's still no guarantee that this will work, it just reduces the likelihood of a crash. If it still doesn't work, you'd have to resort to the timer hack (which can cause other timing problems like dismissing the dialog later).

Of course, if you can use this or ActivityName.this, it's more stable because this already points to something. But in some cases, like with certain Fragment architectures, it's not an option.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

SQL Switch/Case in 'where' clause

The problem with this is that when the SQL engine goes to evaluate the expression, it checks the FROM portion to pull the proper tables, and then the WHERE portion to provide some base criteria, so it cannot properly evaluate a dynamic condition on which column to check against.

You can use a WHERE clause when you're checking the WHERE criteria in the predicate, such as

WHERE account_location = CASE @locationType
                              WHEN 'business' THEN 45
                              WHEN 'area' THEN 52
                         END

so in your particular case, you're going to need put the query into a stored procedure or create three separate queries.

How do you copy and paste into Git Bash

Copy:

Long-term solution: Click on Topleft icon > Defaults > Select "QuickEdit Mode" under "Edit Options" > Okay

Then select the text you want to copy. Press Enter

Short-term solution: Click on Topleft icon > Edit > Mark. Press Enter.

Paste:

Press Insert

(If the "QuickEdit Mode" is on, Right clicking might work too.)

Set UITableView content inset permanently

automaticallyAdjustsScrollViewInsets is deprecated in iOS11 (and the accepted solution no longer works). use:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

Iterating over Typescript Map

You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void instead

Use it like this:

myMap.forEach((value: boolean, key: string) => {
    console.log(key, value);
});

How to correctly use "section" tag in HTML5?

that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.

you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/

How to create a DataTable in C# and how to add rows?

DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`

dt.Columns.Add(Age);

DataRow dr=dt.NewRow();

dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();

dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();

Can I fade in a background image (CSS: background-image) with jQuery?

It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

How to use ESLint with Jest

ESLint supports this as of version >= 4:

/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;

module.exports = {
  extends: "eslint:recommended",
  env: {
    es6: true
  },
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true // now **/*.test.js files' env has both es6 *and* jest
      },
      // Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
      // "extends": ["plugin:jest/recommended"]
      plugins: ["jest"],
      rules: {
        "jest/no-disabled-tests": "warn",
        "jest/no-focused-tests": "error",
        "jest/no-identical-title": "error",
        "jest/prefer-to-have-length": "warn",
        "jest/valid-expect": "error"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

How can I get selector from jQuery object

How about:

var selector = "*"
$(selector).click(function() {
    alert(selector);
});

I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});

Test if a vector contains a given element

I will group the options based on output. Assume the following vector for all the examples.

v <- c('z', 'a','b','a','e')

For checking presence:

%in%

> 'a' %in% v
[1] TRUE

any()

> any('a'==v)
[1] TRUE

is.element()

> is.element('a', v)
[1] TRUE

For finding first occurance:

match()

> match('a', v)
[1] 2

For finding all occurances as vector of indices:

which()

> which('a' == v)
[1] 2 4

For finding all occurances as logical vector:

==

> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE

Edit: Removing grep() and grepl() from the list for reason mentioned in comments

Git Server Like GitHub?

If you want pull requests, there are the open source projects of RhodeCode and GitLab and the paid Stash

How to monitor the memory usage of Node.js?

Also, if you'd like to know global memory rather than node process':

var os = require('os');

os.freemem();
os.totalmem();

See documentation

Getting the actual usedrange

This function returns the actual used range to the lower right limit. It returns "Nothing" if the sheet is empty.

'2020-01-26
Function fUsedRange() As Range
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim rngLastCell As Range
    On Error Resume Next
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in rows
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastRow = rngLastCell.Row
    End If
    Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious)
    If rngLastCell Is Nothing Then  'look for data backwards in columns
        Set fUsedRange = Nothing
        Exit Function
    Else
        lngLastCol = rngLastCell.Column
    End If
    Set fUsedRange = ActiveSheet.Range(Cells(1, 1), Cells(lngLastRow, lngLastCol))  'set up range
End Function

How to set the size of button in HTML

button { 
  width:1000px; 
} 

or even

 button { 
    width:1000px !important
 } 

If thats what you mean

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

public class Splash extends Activity {

    Location location;
    LocationManager locationManager;
    LocationListener locationlistener;
    ImageView image_view;
    ublic static ProgressDialog progressdialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        progressdialog = new ProgressDialog(Splash.this);
           image_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                        locationManager.requestLocationUpdates("gps", 100000, 1, locationlistener);
                        Toast.makeText(getApplicationContext(), "Getting Location plz wait...", Toast.LENGTH_SHORT).show();

                            progressdialog.setMessage("getting Location");
                            progressdialog.show();
                            Intent intent = new Intent(Splash.this,Show_LatLng.class);
//                          }
        });
    }

Text here:-
use this for getting activity context for progressdialog

 progressdialog = new ProgressDialog(Splash.this);

or progressdialog = new ProgressDialog(this);

use this for getting application context for BroadcastListener not for progressdialog.

progressdialog = new ProgressDialog(getApplicationContext());
progressdialog = new ProgressDialog(getBaseContext());

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

Safari 3rd party cookie iframe trick no longer working?

Let me share my fix in ASP.NET MVC 4. The main idea like in correct answer for PHP. The next code added in main Layout in header near scripts section:

@if (Request.Browser.Browser=="Safari")
{
    string pageUrl = Request.Url.GetLeftPart(UriPartial.Path);
    if (Request.Params["safarifix"] != null && Request.Params["safarifix"] == "doSafariFix")
    {
        Session["IsActiveSession"] = true;
        Response.Redirect(pageUrl);
        Response.End();
    }
        else if(Session["IsActiveSession"]==null)
    {
        <script>top.window.location = "?safarifix=doSafariFix";</script>
    }
}

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

Array inside a JavaScript Object?

var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Angular 2 http post params and body

Let said our backend looks like this:

public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}

We have a HttpService like this:

    post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
        return this.http.post<T>(url, body, { headers: headers, params});
    }

Following is how we can pass the body and the notes as parameter: // how to call it

const headers: HttpHeaders = new HttpHeaders({
    'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});

const bodyData = this.getBodyData(); // get whatever we want to send as body

let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');

this.httpService.post<any>(url, bodyData, headers, params);

It worked for me (using angular 7^), I hope is useful for somebody.

Embedding SVG into ReactJS

There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.

https://www.npmjs.com/package/convert-svg-react

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

How to return a struct from a function in C++?

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

How to multiply values using SQL

You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.

SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC

How to create query parameters in Javascript?

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

How do I remove all non-ASCII characters with regex and Notepad++?

To keep new lines:

  1. First select a character for new line... I used #.
  2. Select replace option, extended.
  3. input \n replace with #
  4. Hit Replace All

Next:

  1. Select Replace option Regular Expression.
  2. Input this : [^\x20-\x7E]+
  3. Keep Replace With Empty
  4. Hit Replace All

Now, Select Replace option Extended and Replace # with \n

:) now, you have a clean ASCII file ;)

How to write "not in ()" sql query using join

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

How to Upload Image file in Retrofit 2

Totally agree with @tir38 and @android_griezmann. This would be the version in kotlin:

interface servicesEndPoint {
@Multipart
@POST("user/updateprofile")
fun updateProfile(@Part("user_id") id:RequestBody, @Part("full_name") other:fullName, @Part image: MultipartBody.Part, @Part("other") other:RequestBody): Single<UploadPhotoResponse>

companion object {
        val API_BASE_URL = "YOUR_URL"

        fun create(): servicesPhotoEndPoint {
            val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(API_BASE_URL)
                .build()
            return retrofit.create(servicesPhotoEndPoint::class.java)
        }
    }
}

// pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))  
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)

// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)

// add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")

servicesEndPoint.create().updateProfile(id, fullName, body, fullName)

To obtain the real path, use RealPathUtils. Check this class in the answers of @Harsh Bhavsar in this question: How to get the Full file path from URI.

To getRealPathFromURI_API19 you need permissions of READ_EXTERNAL_STORAGE

Determine the type of an object?

You can do that using type():

>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

Redirect to specified URL on PHP script completion?

<?
ob_start(); // ensures anything dumped out will be caught

// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever

// clear out the output buffer
while (ob_get_status()) 
{
    ob_end_clean();
}

// no redirect
header( "Location: $url" );
?>

Undo working copy modifications of one file in Git?

I don't know why but when I try to enter my code, it comes up as an image.

enter image description here

PHP refresh window? equivalent to F5 page reload?

with php you can use two redirections. It works same as refresh in some issues.

you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.

like this: your page:

<?php
header("location:redirec.php?ref=".$your_url);
?>

redirect.php:

<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>

that worked for me good.

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

How do you validate a URL with a regular expression in Python?

An easy way to parse (and validate) URL's is the urlparse (py2, py3) module.

A regex is too much work.


There's no "validate" method because almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

Bottom Line. Parse it, and look at the pieces to see if they're displeasing in some way.

Do you want the scheme to always be "http"? Do you want the netloc to always be "www.somename.somedomain"? Do you want the path to look unix-like? Or windows-like? Do you want to remove the query string? Or preserve it?

These are not RFC-specified validations. These are validations unique to your application.

don't fail jenkins build if execute shell fails

Another one answer with some tips, can be helpful for somebody:

remember to separate your commands with the following rule:

command1 && command2 - means, that command2 will be executed, only if command1 success

command1 ; command2 - means, that command 2 will be executed despite on result of command1

for example:

String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test ;set -e;echo 0 ", returnStdout: true).trim()
println run_tests 

will be executed successfully with set -e and echo 0 commands if gmake test failed (your tests failed), while the following code snipped:

String run_tests = sh(script: "set +e && cd ~/development/tests/ && gmake test && set -e && echo 0 ", returnStdout: true).trim()
println run_tests 

a bit wrong and commands set -e and echo 0 in&& gmake test && set -e && echo 0 will be skipped, with the println run_tests statement, because failed gmake test will abort the jenkins build. As workaround you can switch to returnStatus:true, but then you will miss the output from your command.

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Does MS Access support "CASE WHEN" clause if connect with ODBC?

I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.

IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))

All remaining will stay Null.

How can I inspect element in chrome when right click is disabled?

So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way

How to test if a file is a directory in a batch script?

A very simple way is to check if the child exists.

If a child does not have any child, the exist command will return false.

IF EXIST %1\. (
  echo %1 is a folder
) else (
  echo %1 is a file
)

You may have some false negative if you don't have sufficient access right (I have not tested it).

Stop and Start a service via batch or cmd file?

Here is the Windows 10 command to start System Restore using batch :

sc config swprv start= Auto

You may also like those commands :

  • Change registry value to auto start System restore

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" /v DisableSR /t REG_DWORD /d 0 /f

  • Create a system restore point

    Wmic.exe /Namespace:\root\default Path SystemRestore Call CreateRestorePoint "djibe saved your PC", 100, 12

  • Change System Restore disk usage

    vssadmin resize shadowstorage /for=C: /on=C: /maxsize=10%

Enjoy

When to use %r instead of %s in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

Add timestamp column with default NOW() for new rows only

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

How can I open Java .class files in a human-readable way?

Using Jad to decompile it is probably your best option. Unless the code has been obfuscated, it will produce an okay result.

Difference between ref and out parameters in .NET

Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            // u can try giving int i=100 but is useless as that value is not passed into
            // the method. Only variable goes into the method and gets changed its
            // value and comes out. 
            int i; 

            a.abc(out i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(out int i)
        {

            i = 10;

        }

    }
}

Output:

10

===============================================

Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.

namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            int i = 0;

            a.abc(ref i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(ref int i)
        {
            System.Console.WriteLine(i);
            i = 10;

        }

    }
}

Output:

    0
    10

=================================

Hope its clear now.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Example JavaScript code to parse CSV data

jQuery-CSV

It's a jQuery plugin designed to work as an end-to-end solution for parsing CSV into JavaScript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google spreadsheet exports (i.e., mostly involving null values) that the specification is missing.

Example:

track,artist,album,year

Dangerous,'Busta Rhymes','When Disaster Strikes',1997

// Calling this
music = $.csv.toArrays(csv)

// Outputs...
[
  ["track", "artist", "album", "year"],
  ["Dangerous", "Busta Rhymes", "When Disaster Strikes", "1997"]
]

console.log(music[1][2]) // Outputs: 'When Disaster Strikes'

Update:

Oh yeah, I should also probably mention that it's completely configurable.

music = $.csv.toArrays(csv, {
  delimiter: "'", // Sets a custom value delimiter character
  separator: ';', // Sets a custom field separator character
});

Update 2:

It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same library.

Update 3:

Since the Google Code shutdown, jquery-csv has been migrated to GitHub.

Disclaimer: I am also the author of jQuery-CSV.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Fast Bitmap Blur For Android SDK

I found that decreasing contrast, brightness and saturation a little makes blurred images more pretty so I combined various methods from stack overflow and made this Blur Class which deals with blurring images, changing brightness, saturation, contrast and size of the blurred images. It can also convert images from drawable to bitmap and vice-versa.

How to run multiple Python versions on Windows

cp c:\python27\bin\python.exe as python2.7.exe

cp c:\python34\bin\python.exe as python3.4.exe

they are all in the system path, choose the version you want to run

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I developed desktop application using C#.net with 2.0 framework along with system.data.oracleclient for connecting oracle db and I was facing similar error message ,"Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed."

following solutions were applied

  • Project, properties, Build TAB, select platform target : x86
  • Project, clean build, ReBuild solution
  • Install Oracle 11G*32 bit client

now, it work because application is set for 32bit and oracle 32bit client installed over Win2012 R2 server, hopefully will work for you.

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Vue.js getting an element within a component

In Vue2 be aware that you can access this.$refs.uniqueName only after mounting the component.

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")
         document.getElementById("test").style.color="black";
    else
         document.getElementById("test").style.color="red";
}

Java Date cut off time information

The recommended way to do date/time manipulation is to use a Calendar object:

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();

Converting byte array to string in javascript

This should work:

String.fromCharCode(...array);

Or

String.fromCodePoint(...array)