Programs & Examples On #Bundler

Bundler is a tool that makes it easier to keep track of what Ruby gems (and what versions of those gems) an application depends upon. It does so by installing all the gems in your application’s Gemfile. Bundler itself is a gem and can be installed with the following: $ gem install bundler

"Could not find bundler" error

The command is bundle update (there is no "r" in the "bundle").

To check if bundler is installed do : gem list bundler or even which bundle and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler.

How can I specify a local gem in my Gemfile?

You can reference gems with source:

source: 'https://source.com', git repository (:github => 'git/url') and with local path

:path => '.../path/gem_name'.

You can learn more about [Gemfiles and how to use them] (https://kolosek.com/rails-bundle-install-and-gemfile) in this article.

rails bundle clean

When searching for an answer to the very same question I came across gem_unused.
You also might wanna read this article: http://chill.manilla.com/2012/12/31/clean-up-your-dirty-gemsets/
The source code is available on GitHub: https://github.com/apolzon/gem_unused

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

Should Gemfile.lock be included in .gitignore?

A little late to the party, but answers still took me time and foreign reads to understand this problem. So I want to summarize what I have find out about the Gemfile.lock.

When you are building a Rails App, you are using certain versions of gems in your local machine. If you want to avoid errors in the production mode and other branches, you have to use that one Gemfile.lock file everywhere and tell bundler to bundle for rebuilding gems every time it changes.

If Gemfile.lock has changed on your production machine and Git doesn't let you git pull, you should write git reset --hard to avoid that file change and write git pull again.

Why won't bundler install JSON gem?

Run this command then everything will be ok

sudo apt-get install libgmp-dev

How do I specify local .gem files in my Gemfile?

I would unpack your gem in the application vendor folder

gem unpack your.gem --target /path_to_app/vendor/gems/

Then add the path on the Gemfile to link unpacked gem.

gem 'your', '2.0.1', :path => 'vendor/gems/your'

bundle install fails with SSL certificate verification error

Download rubygems-update-2.6.7.gem .

Now, using your Command Prompt:

C:\>gem install --local C:\rubygems-update-2.6.7.gem
C:\>update_rubygems --no-ri --no-rdoc

After this, gem --version should report the new update version.

You can now safely uninstall rubygems-update gem:

C:\>gem uninstall rubygems-update -x
Removing update_rubygems
Successfully uninstalled rubygems-update-2.6.7

Could not locate Gemfile

I had the same problem and got it solved by using a different directory.

bash-4.2$ bundle install
Could not locate Gemfile
bash-4.2$ pwd
/home/amit/redmine/redmine-2.2.2-0/apps/redmine
bash-4.2$ cd htdocs/
bash-4.2$ ls
app  config db   extra  Gemfile   lib  plugins  Rakefile     script  tmp
bin  config.ru  doc  files  Gemfile.lock  log  public   README.rdoc  test    vendor
bash-4.2$ cd plugins/
bash-4.2$ bundle install
Using rake (0.9.2.2) 
Using i18n (0.6.0) 
Using multi_json (1.3.6) 
Using activesupport (3.2.11) 
Using builder (3.0.0) 
Using activemodel (3.2.11) 
Using erubis (2.7.0) 
Using journey (1.0.4) 
Using rack (1.4.1) 
Using rack-cache (1.2) 
Using rack-test (0.6.1) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.2.1) 
Using actionpack (3.2.11) 
Using mime-types (1.19) 
Using polyglot (0.3.3) 
Using treetop (1.4.10) 
Using mail (2.4.4) 
Using actionmailer (3.2.11) 
Using arel (3.0.2) 
Using tzinfo (0.3.33) 
Using activerecord (3.2.11) 
Using activeresource (3.2.11) 
Using coderay (1.0.6) 
Using rack-ssl (1.3.2) 
Using json (1.7.5) 
Using rdoc (3.12) 
Using thor (0.15.4) 
Using railties (3.2.11) 
Using jquery-rails (2.0.3) 
Using mysql2 (0.3.11) 
Using net-ldap (0.3.1) 
Using ruby-openid (2.1.8) 
Using rack-openid (1.3.1) 
Using bundler (1.2.3) 
Using rails (3.2.11) 
Using rmagick (2.13.1) 
Your bundle i

Bundler: Command not found

Step 1:Make sure you are on path actual workspace.For example, workspace/blog $: Step2:Enter the command: gem install bundler. Step 3: You should be all set to bundle install or bundle update by now

Understanding the Gemfile.lock file

I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.

You'll find the following headings in a lockfile generated by Bundler 1.x:

GEM (optional but very common)

These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:

  • remote: one or more lines specifying the location of the Rubygems index(es)
  • specs: a list of dependencies, with their version number, and the constraints on any subdependencies

GIT (optional)

These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:

  • remote: the git remote. E.g., [email protected]:rails/rails
  • revision: the commit reference the Gemfile.lock is locked to
  • tag: (optional) the tag specified in the Gemfile
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PATH (optional)

These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:

  • remote: the path. E.g., plugins/vendored-dependency
  • specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies

PLATFORMS

The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).

DEPENDENCIES

A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there.

Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).

RUBY VERSION (optional)

The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).

BUNDLED WITH (Bundler >= v1.10.x)

The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.

PLUGIN SOURCE (optional and very rare)

In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!


  1. https://dependabot.com
  2. https://github.com/bundler/bundler/issues/4631
  3. http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/

Update just one gem with bundler

bundle update gem-name [--major|--patch|--minor]

This also works for dependencies.

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

Is it possible to listen to a "style change" event?

Interesting question. The problem is that height() does not accept a callback, so you wouldn't be able to fire up a callback. Use either animate() or css() to set the height and then trigger the custom event in the callback. Here is an example using animate() , tested and works (demo), as a proof of concept :

$('#test').bind('style', function() {
    alert($(this).css('height'));
});

$('#test').animate({height: 100},function(){
$(this).trigger('style');
}); 

How to run a script at a certain time on Linux?

Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.

But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.

Convert normal date to unix timestamp

You could simply use the unary + operator

(+new Date('2012.08.10')/1000).toFixed(0);

http://xkr.us/articles/javascript/unary-add/ - look under Dates.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

How to wait until WebBrowser is completely loaded in VB.NET?

Sounds like you want to catch the DocumentCompleted event of your webbrowser control.

MSDN has a couple of good articles about the webbrowser control - WebBrowser Class has lots of examples, and How to: Add Web Browser Capabilities to a Windows Forms Application

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

How to iterate through a list of objects in C++

It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator, as follows:

for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
    // do whatever you wish but don't modify the list elements
    std::cout << it->name;
}

How to find tags with only certain attributes - BeautifulSoup

find using an attribute in any tag

<th class="team" data-sort="team">Team</th>    
soup.find_all(attrs={"class": "team"}) 

<th data-sort="team">Team</th>  
soup.find_all(attrs={"data-sort": "team"}) 
 

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

How to clear an EditText on click?

after onclick of any action do below step

((EditText) findViewById(R.id.yoursXmlId)).setText("");

or

write this in XML file

<EditText
---------- other stuffs ------ 
android:hint="Enter Name" /> 

its works fine for me. Hope to you all.

Prevent screen rotation on Android

If you are using Android Developer Tools (ADT) and Eclipse you can go to your AndroidManifest.xml --> Application tab --> go down and select your activity. Finally, select your preferred orientation. You can select one of the many options.

jquery change button color onclick

You have to include the jquery framework in your document head from a cdn for example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Then you have to include a own script for example:

(function( $ ) {

  $(document).ready(function(){
      $('input').click(function() {
          $(this).css('background-color', 'green');
      }
  });


  $(window).load(function() { 
  });

})( jQuery );

This part is a mapping of the $ to jQuery, so actually it is jQuery('selector').function();

(function( $ ) {

})( jQuery );

Here you can find die api of jquery where all functions are listed with examples and explanation: http://api.jquery.com/

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

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

Array vs. Object efficiency in JavaScript

I tried to take this to the next dimension, literally.

Given a 2 dimensional array, in which the x and y axes are always the same length, is it faster to:

a) look up the cell by creating a two dimensional array and looking up the first index, followed by the second index, i.e:

var arr=[][]    
var cell=[x][y]    

or

b) create an object with a string representation of the x and y coordinates, and then do a single lookup on that obj, i.e:

var obj={}    
var cell = obj['x,y']    

Result:
Turns out that it's much faster to do two numeric index lookups on the arrays, than one property lookup on the object.

Results here:

http://jsperf.com/arr-vs-obj-lookup-2

Postgresql - unable to drop database because of some auto connections to DB

In my case, I am using AWS Redshift (based on Postgres). And it appears there are no other connections to the DB, but I am getting this same error.

ERROR:  database "XYZ" is being accessed by other users

In my case, it seems the database cluster is still doing some processing on the database, and while there are no other external/user connections, the database is still internally in use. I found this by running the following:

SELECT * FROM stv_sessions;

So my hack was to write a loop in my code, looking for rows with my database name in it. (of course the loop is not infinite, and is a sleepy loop, etc)

SELECT * FROM stv_sessions where db_name = 'XYZ';

If rows found, proceed to delete each PID, one by one.

SELECT pg_terminate_backend(PUT_PID_HERE);

If no rows found, proceed to drop the database

DROP DATABASE XYZ;

Note: In my case, I am writing Java unit/system tests, where this could be considered acceptable. This is not acceptable for production code.


Here is the complete hack, in Java (ignore my test/utility classes).

  int i = 0;
  while (i < 10) {
    try {
      i++;
      logStandardOut("First try to delete session PIDs, before dropping the DB");
      String getSessionPIDs = String.format("SELECT stv_sessions.process, stv_sessions.* FROM stv_sessions where db_name = '%s'", dbNameToReset);
      ResultSet resultSet = databaseConnection.execQuery(getSessionPIDs);
      while (resultSet.next()) {
        int sessionPID = resultSet.getInt(1);
        logStandardOut("killPID: %s", sessionPID);
        String killSessionPID = String.format("select pg_terminate_backend(%s)", sessionPID);
        try {
          databaseConnection.execQuery(killSessionPID);
        } catch (DatabaseException dbEx) {
          //This is most commonly when a session PID is transient, where it ended between my query and kill lines
          logStandardOut("Ignore it, you did your best: %s, %s", dbEx.getMessage(), dbEx.getCause());
        }
      }

      //Drop the DB now
      String dropDbSQL = String.format("DROP DATABASE %s", dbNameToReset);
      logStandardOut(dropDbSQL);
      databaseConnection.execStatement(dropDbSQL);
      break;
    } catch (MissingDatabaseException ex) {
      //ignore, if the DB was not there (to be dropped)
      logStandardOut(ex.getMessage());
      break;
    } catch (Exception ex) {
      logStandardOut("Something went wrong, sleeping for a bit: %s, %s", ex.getMessage(), ex.getCause());
      sleepMilliSec(1000);
    }
  }

from list of integers, get number closest to a given value

It's important to note that Lauritz's suggestion idea of using bisect does not actually find the closest value in MyList to MyNumber. Instead, bisect finds the next value in order after MyNumber in MyList. So in OP's case you'd actually get the position of 44 returned instead of the position of 4.

>>> myList = [1, 3, 4, 44, 88] 
>>> myNumber = 5
>>> pos = (bisect_left(myList, myNumber))
>>> myList[pos]
...
44

To get the value that's closest to 5 you could try converting the list to an array and using argmin from numpy like so.

>>> import numpy as np
>>> myNumber = 5   
>>> myList = [1, 3, 4, 44, 88] 
>>> myArray = np.array(myList)
>>> pos = (np.abs(myArray-myNumber)).argmin()
>>> myArray[pos]
...
4

I don't know how fast this would be though, my guess would be "not very".

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Drawing Circle with OpenGL

We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say base=X and Y=vertical. Now we can write X=hypotenuse*cos? and Y=hypotenuse*sin?. We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

How can I check MySQL engine type for a specific table?

SHOW CREATE TABLE <tablename>;

Less parseable but more readable than SHOW TABLE STATUS.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

How to create an empty array in PHP with predefined size?

Possibly related, if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:

$a = range(1, 5);  // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

You would need to enable https binding on server side. IISExpress in this case. Select Properties on website project in solution explorer (not double click). In the properties pane then you need to enable SSL.

What is a classpath and how do I set it?

The classpath is the path where the Java Virtual Machine look for user-defined classes, packages and resources in Java programs.

In this context, the format() method load a template file from this path.

Counting unique / distinct values by group in a data frame

This is a simple solution with the function aggregate:

aggregate(order_no ~ name, myvec, function(x) length(unique(x)))

Alternate background colors for list items

You can by hardcoding the sequence, like so:

li, li + li + li, li + li + li + li + li {
  background-color: black;
}

li + li, li + li + li + li {
  background-color: white;
}

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

ArrayList insertion and retrieval order

If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.

No tests found with test runner 'JUnit 4'

I have this problem from time to time. The thing that resolves the issue most for me is to run the JUnit test from Run configurations... ensuring that JUnit 4 is set as the test runner.

Generally, I see this issue when attempting to Run As... Junit test from the context menu on the Package Explorer. If you right click the code for the test you are trying to run and instead of selecting Run As... Junit Test you select Run configurations... ensure the Project, Test Class and test runner are set correctly, clicking apply, then run works all the time for me.

How to include js and CSS in JSP with spring MVC

You cant directly access anything under the WEB-INF foldere. When browsers request your CSS file, they can not see inside the WEB-INF folder.

Try putting your files css/css folder under WebContent.

And add the following in dispatcher servlet to grant access ,

<mvc:resources mapping="/css/**" location="/css/" />

similarly for your js files . A Nice example here on this

SQLite: How do I save the result of a query as a CSV file?

In addition to the above answers you can also use .once in a similar way to .output. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout.

So in the above example

.mode csv
.headers on
.once test.csv
select * from tbl1;

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

Read JSON data in a shell script

Similarly using Bash regexp. Shall be able to snatch any key/value pair.

key="Body"
re="\"($key)\": \"([^\"]*)\""

while read -r l; do
    if [[ $l =~ $re ]]; then
        name="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        echo "$name=$value"
    else
        echo "No match"
    fi
done

Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded ". This is an illustration. Better to use some "industrial" parser :)

CSS: Position loading indicator in the center of the screen

change the position absolute of div busy to fixed

How to add jQuery code into HTML Page

for latest Jquery. Simply:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

RecyclerView - How to smooth scroll to top of item on a certain position?

We can try like this

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());

Showing empty view when ListView is empty

Just to add that you don't really need to create new IDs, something like the following will work.

In the layout:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@android:id/empty"
    android:text="Empty"/>

Then in the activity:

    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));

How to use NULL or empty string in SQL

select 
   isnull(column,'') column, * 
from Table  
Where column = ''

Detecting user leaving page with react-router

react-router v4 introduces a new way to block navigation using Prompt. Just add this to the component that you would like to block:

import { Prompt } from 'react-router'

const MyComponent = () => (
  <React.Fragment>
    <Prompt
      when={shouldBlockNavigation}
      message='You have unsaved changes, are you sure you want to leave?'
    />
    {/* Component JSX */}
  </React.Fragment>
)

This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):

componentDidUpdate = () => {
  if (shouldBlockNavigation) {
    window.onbeforeunload = () => true
  } else {
    window.onbeforeunload = undefined
  }
}

onbeforeunload has various support by browsers.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

Word-wrap in an HTML table

The only thing that needs to be done is add width to the <td> or the <div> inside the <td> depending on the layout you want to achieve.

eg:

<table style="width: 100%;" border="1"><tr>
<td><div style="word-wrap: break-word; width: 100px;">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>

or

 <table style="width: 100%;" border="1"><tr>
    <td width="100" ><div style="word-wrap: break-word; ">looooooooooodasdsdaasdasdasddddddddddddddddddddddddddddddasdasdasdsadng word</div></td>
    <td><span style="display: inline;">Foo</span></td>

</tr></table>

no match for ‘operator<<’ in ‘std::operator

Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.

ex

#include <iostream>

using namespace std;

class mystruct

{
private:
    int m_a;
    float m_b;

public:
    mystruct(int x, float y)
    {
            m_a = x;
            m_b = y;
    }
    public:
    void getm_aAndm_b()
    {
        cout<<m_a<<endl;
        cout<<m_b<<endl;
    }



};

int main()
{

    mystruct m = mystruct(5,3.14);

    cout << "my structure " << endl;
    m.getm_aAndm_b();
    return 0;

}

Not that this is just a one way of doing it

How to read a text file into a string variable and strip newlines?

You can also strip each line and concatenate into a final string.

myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
    data = data + line.strip();

This would also work out just fine.

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

Best way to get child nodes

Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg> elements.

I have used both .childNodes and .children and have preferred working with the HTMLCollection delivered by the .children getter.

Today however, I ran into issues with IE/Edge failing when using .children on an <svg>. While .children is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.

For me, I was able to simply grab the needed elements via .childNodes[n] because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.

Hope this is helpful to someone scratching their head trying to figure out why .children works elsewhere in their js on modern IE and fails on document or SVG elements.

node and Error: EMFILE, too many open files

This may happen after changing the Node version ERR emfile too many open files

  • Restart the computer
  • brew install watchman

It should be absolutely fixed the issue

jQuery UI autocomplete with item and id

My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.

$('#sistema_select').autocomplete({

    minLength: 3,
    source: <?php echo $lista_sistemas;?> ,
    select: function (event, ui) {
         $('#sistema_select').val(ui.item.label); // display the selected text
         $('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
         return false;
     },
    change: function( event, ui ) {
        $( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
    } 
});

In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:

var $local_source = [
       {value: 1,  label: "c++"}, 
       {value: 2,  label: "java"}]

and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.

SFTP in Python? (platform independent)

If you want easy and simple, you might also want to look at Fabric. It's an automated deployment tool like Ruby's Capistrano, but simpler and of course for Python. It's build on top of Paramiko.

You might not want to do 'automated deployment' but Fabric would suit your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work):

fab_putfile.py:

from fabric.api import *

env.hosts = ['THEHOST.com']
env.user = 'THEUSER'
env.password = 'THEPASSWORD'

def put_file(file):
    put(file, './THETARGETDIRECTORY/') # it's copied into the target directory

Then run the file with the fab command:

fab -f fab_putfile.py put_file:file=./path/to/my/file

And you're done! :)

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

Vertical Tabs with JQuery?

super simple function that will allow you to create your own tab / accordion structure here: http://jsfiddle.net/nabeezy/v36DF/

bindSets = function (tabClass, tabClassActive, contentClass, contentClassHidden) {
        //Dependent on jQuery
        //PARAMETERS
        //tabClass: 'the class name of the DOM elements that will be clicked',
        //tabClassActive: 'the class name that will be applied to the active tabClass element when clicked (must write your own css)',
        //contentClass: 'the class name of the DOM elements that will be modified when the corresponding tab is clicked',
        //contentClassHidden: 'the class name that will be applied to all contentClass elements except the active one (must write your own css)',
        //MUST call bindSets() after dom has rendered

        var tabs = $('.' + tabClass);
        var tabContent = $('.' + contentClass);
        if(tabs.length !== tabContent.length){console.log('JS bindSets: sets contain a different number of elements')};
        tabs.each(function (index) {
            this.matchedElement = tabContent[index];
            $(this).click(function () {
                tabs.each(function () {
                    this.classList.remove(tabClassActive);
                });
                tabContent.each(function () {
                    this.classList.add(contentClassHidden);
                });
                this.classList.add(tabClassActive);
                this.matchedElement.classList.remove(contentClassHidden);
            });
        })
        tabContent.each(function () {
            this.classList.add(contentClassHidden);
        });

        //tabs[0].click();
    }
bindSets('tabs','active','content','hidden');

Found shared references to a collection org.hibernate.HibernateException

In a one to many and many to one relationship this error will occur. If you attempt to devote same instance from many to one entity to more than one instance from one to many entity.

For example, each person can have many books but each of these books can be owned by only one person if you consider more than one owner for a book this issue is raised.

How to get complete current url for Cakephp

Getting current URL for CakePHP 3.x ?

In your layout :

<?php 
    $here = $this->request->here();
    $canonical = $this->Url->build($here, true);
?>

You will get the full URL of the current page including query string parameters.

e.g. http://website.example/controller/action?param=value

You can use it in a meta tag canonical if you need to do some SEO.

<link rel="canonical" href="<?= $canonical; ?>">

Migration: Cannot add foreign key constraint

If none of the solutions above work for newbies check if both IDs have the same type: both are integer or both are bigInteger, ... You can have something like this:

Main Table (users for example)

$table->bigIncrements('id');

Child Table (priorities for example)

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

This query will failed because users.id is a BIG INTEGER whereas priorities.user_id is an INTEGER.

The right query in this case would be the following:

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

keycloak Invalid parameter: redirect_uri

even I faced the same issue. I rectified it by going to the particular client under the realm respectively therein redirect URL add * after your complete URL.

THE PROBLEM WILL BE SOLVED

Example: redirect URI: http:localhost:3000/myapp/generator/*

How to get a list of all files in Cloud Storage in a Firebase app?

Since there's no language listed, I'll answer this in Swift. We highly recommend using Firebase Storage and the Firebase Realtime Database together to accomplish lists of downloads:

Shared:

// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()

Upload:

let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
  // When the image has successfully uploaded, we get it's download URL
  let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
  // Write the download URL to the Realtime Database
  let dbRef = database.reference().child("myFiles/myFile")
  dbRef.setValue(downloadURL)
}

Download:

let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
  // Get download URL from snapshot
  let downloadURL = snapshot.value() as! String
  // Create a storage reference from the URL
  let storageRef = storage.referenceFromURL(downloadURL)
  // Download the data, assuming a max size of 1MB (you can change this as necessary)
  storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
    // Create a UIImage, add it to the array
    let pic = UIImage(data: data)
    picArray.append(pic)
  })
})

For more information, see Zero to App: Develop with Firebase, and it's associated source code, for a practical example of how to do this.

onActivityResult is not being called in Fragment

Option 1:

If you're calling startActivityForResult() from the fragment then you should call startActivityForResult(), not getActivity().startActivityForResult(), as it will result in fragment onActivityResult().

If you're not sure where you're calling on startActivityForResult() and how you will be calling methods.

Option 2:

Since Activity gets the result of onActivityResult(), you will need to override the activity's onActivityResult() and call super.onActivityResult() to propagate to the respective fragment for unhandled results codes or for all.

If above two options do not work, then refer to option 3 as it will definitely work.

Option 3:

An explicit call from fragment to the onActivityResult function is as follows.

In the parent Activity class, override the onActivityResult() method and even override the same in the Fragment class and call as the following code.

In the parent class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.dualPane);
    fragment.onActivityResult(requestCode, resultCode, data);
}

In the child class:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // In fragment class callback
}

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Intel's HAXM equivalent for AMD on Windows OS

This limitation (of Windows) should be publicly announced! The issue for me is the combination of the following: Windows 10 + AMD CPU (with AMD-V/SMV) +/- Hyper Visor

I have no issues running: Intel (with VT-x) + Linux or AMD (with AMD-V) + Linux

Link to Android studio issue here:

https://developer.android.com/studio/run/emulator.html#accel-vm

Xamarin/Visual Studio seems to have a workaround, but I haven't tested it yet:

If you need to use Hyper-V for other emulators then I'd recommend using the Microsoft Android Emulator instead, which uses Hyper-V and can also be used with Xamarin Studio/Visual Studio. You can download it for free from here.

I will update this after I confirm it works. Wish I would have known this before purchasing a new machine.

UPDATE!! It does not work "Requires Intel ..." error message is shown

Final note:

*Must be revision F3 or grater or must be F2 with BIOS support. Presence or absence of SVM Disable or other virtualization options in the bios does not ensure presence of BIOS support. You should contact the OEM to ensure support of Hyper-V.

*Some AMD BIOS's have options to enable/disable SVM (virtualization assistance)

*Some BIOS's list this as SVM Disable and it's a double negative, i.e. you want to disable SVM disable to enable SVM.

*Some BIOS's list this as Secure Virtualization, thus enabling Secure Virtualization will enable SVM

*Must have No-Execute enabled in the BIOS, sometime this is referred to as NX or Execute Disable

*If you want to find CPU's that are F3 see AMD's guide http://products.amd.com/en-us/DesktopCPUFilter.aspx or http://products.amd.com/en-us/OpteronCPUFilter.aspx?f1=Second-Generation+AMD+Opteron%e2%84%a2

How to completely uninstall python 2.7.13 on Ubuntu 16.04

How I do:

# Remove python2
sudo apt purge -y python2.7-minimal

# You already have Python3 but 
# don't care about the version 
sudo ln -s /usr/bin/python3 /usr/bin/python

# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip

# Confirm the new version of Python: 3
python --version

How can we generate getters and setters in Visual Studio?

You just simply press Alt + Ins in Android Studio.

After declaring variables, you will get the getters and setters in the generated code.

test if display = none

If you want to get the visible tbody elements, you could do this:

$('tbody:visible').highlight(myArray[i]);

It looks similar to the answer that Agent_9191 gave, but this one removes the space from the selector, which makes it selects the visible tbody elements instead of the visible descendants.


EDIT:

If you specifically wanted to use a test on the display CSS property of the tbody elements, you could do this:

$('tbody').filter(function() {
     return $(this).css('display') != 'none';
}).highlight(myArray[i]);

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

How to pip install a package with min and max version range?

You can do:

$ pip install "package>=0.2,<0.3"

And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

This also applies to pip requirements files. See the full details on version specifiers in PEP 440.

How to set the matplotlib figure default size in ipython notebook?

Worked liked a charm for me:

matplotlib.rcParams['figure.figsize'] = (20, 10)

How to examine processes in OS X's Terminal?

Using top and ps is okay, but I find that using htop is far better & clearer than the standard tools Mac OS X uses. My fave use is to hit the T key while it is running to view processes in tree view (see screenshot). Shows you what processes are co-dependent on other processes.

htop on OSX

You can install it from Homebrew using:

brew install htop

And if you have Xcode and related tools such as git installed on your system and you want to install the latest development code from the official source repository—just follow these steps.

First clone the source code from the htop GitHub repository:

git clone [email protected]:hishamhm/htop.git

Now go into the repository directory:

cd htop

Run autogen.sh:

./autogen.sh

Run this configure command:

./configure

Once the configure process completes, run make:

make

Finally install it by running sudo make install:

sudo make install

MySQL Workbench Edit Table Data is read only

MySQL will run in Read-Only mode when you fetch by joining two tables and columns from two tables are included in the result. Then you can't update the values directly.

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

Equivalent to AssemblyInfo in dotnet core/csproj

I do the following for my .NET Standard 2.0 projects.

Create a Directory.Build.props file (e.g. in the root of your repo) and move the properties to be shared from the .csproj file to this file.

MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs.

They also get applied to the nuget package when building one with dotnet pack or via the UI in Visual Studio 2017.

See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build

Example:

<Project>
    <PropertyGroup>
        <Company>Some company</Company>
        <Copyright>Copyright © 2020</Copyright>
        <AssemblyVersion>1.0.0.1</AssemblyVersion>
        <FileVersion>1.0.0.1</FileVersion>
        <Version>1.0.0.1</Version>
        <!-- ... -->
    </PropertyGroup>
</Project>

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

How to SHA1 hash a string in Android?

You don't need andorid for this. You can just do it in simple java.

Have you tried a simple java example and see if this returns the right sha1.

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AeSimpleSHA1 {
    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] textBytes = text.getBytes("iso-8859-1");
        md.update(textBytes, 0, textBytes.length);
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
}

Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong.

Validating a Textbox field for only numeric input.

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

How to generate UML diagrams (especially sequence diagrams) from Java code?

I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.

you can install PlantUML plugin in the netbeans by this method:

Netbeans Menu -> Tools -> Plugin

Now select Available Plugins and then find PlantUML and install it.

For more information go to website: www.plantuml.com

jquery datatables hide column

$(document).ready(function() {
$('#example').DataTable( {
    "columnDefs": [
        {
            "targets": [ 2 ],
            "visible": false,
            "searchable": false
        },
        {
            "targets": [ 3 ],
            "visible": false
        }
    ]
});});

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Live video streaming using Java?

Hi not an expert in streaming but my understanding is that it is included in th Java Media Framework JMF http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/support-rtsp.html

Java reading a file into an ArrayList?

List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
    words.add(line);
}
reader.close();

When do I need to use AtomicBoolean in Java?

There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.

public final class MyThreadSafeClass{

    private AtomicBoolean myBoolean = new AtomicBoolean(false);
    private SomeThreadSafeObject someObject = new SomeThreadSafeObject();

    public boolean doSomething(){
         someObject.doSomeWork(myBoolean);
         return myBoolean.get(); //will return true
    }
}

and in the someObject class

public final class SomeThreadSafeObject{
    public void doSomeWork(AtomicBoolean b){
        b.set(true);
    }
}

More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.

Draw line in UIView

You can user UIBezierPath Class for this:

And can draw as many lines as you want:

I have subclassed UIView :

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

And initialized the pathArray and dictPAth objects which will be used for line drawing. I am writing the main portion of the code from my own project:

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

touchesBegin method :

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

touchesMoved Method:

UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

touchesEnded Method:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];

The CSRF token is invalid. Please try to resubmit the form

I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path and cookie_domain settings to framework.session fixed it.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

The conversion of the varchar value overflowed an int column

Thanks Ravi and other users .... Nevertheless I have got the solution

SELECT @phoneNumber=
CASE 
  WHEN  ISNULL(rdg2.nPhoneNumber  ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0') 
  WHEN ISNULL(rdg2.nMobileNumber, '0')  in ('0','-',NULL)
THEN '0'
  ELSE ISNULL(rdg2.nPhoneNumber  ,'0')
END 
FROM tblReservation_Details_Guest  rdg2 
WHERE nReservationID=@nReservationID

Just need to put '0' instead of 0

Working with dictionaries/lists in R

Shorter variation of Dirk's answer:

# Create a Color Palette Dictionary 
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')

> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
> 
> color_palette
$navy.blue
[1] "#336A91"

$gold
[1] "#F3C117"

$dark.gray
[1] "#7F7F7F"

SQL update statement in C#

private void button4_Click(object sender, EventArgs e)
    {
        String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("????");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }



    private void button6_Click(object sender, EventArgs e)
    {
        String st = "SELECT * FROM suppliers";

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            SqlDataReader reader = sqlcom.ExecuteReader();
            DataTable datatable = new DataTable();
            datatable.Load(reader);
            dataGridView1.DataSource = datatable;
            //MessageBox.Show("LEFT OUTER??");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

How to listen for changes to a MongoDB collection?

Check out this: Change Streams

January 10, 2018 - Release 3.6

*EDIT: I wrote an article about how to do this https://medium.com/riow/mongodb-data-collection-change-85b63d96ff76

https://docs.mongodb.com/v3.6/changeStreams/


It's new in mongodb 3.6 https://docs.mongodb.com/manual/release-notes/3.6/ 2018/01/10

$ mongod --version
db version v3.6.2

In order to use changeStreams the database must be a Replication Set

More about Replication Sets: https://docs.mongodb.com/manual/replication/

Your Database will be a "Standalone" by default.

How to Convert a Standalone to a Replica Set: https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/


The following example is a practical application for how you might use this.
* Specifically for Node.

/* file.js */
'use strict'


module.exports = function (
    app,
    io,
    User // Collection Name
) {
    // SET WATCH ON COLLECTION 
    const changeStream = User.watch();  

    // Socket Connection  
    io.on('connection', function (socket) {
        console.log('Connection!');

        // USERS - Change
        changeStream.on('change', function(change) {
            console.log('COLLECTION CHANGED');

            User.find({}, (err, data) => {
                if (err) throw err;

                if (data) {
                    // RESEND ALL USERS
                    socket.emit('users', data);
                }
            });
        });
    });
};
/* END - file.js */

Useful links:
https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set
https://docs.mongodb.com/manual/tutorial/change-streams-example

https://docs.mongodb.com/v3.6/tutorial/change-streams-example
http://plusnconsulting.com/post/MongoDB-Change-Streams

How to create multiple output paths in Webpack config

Webpack does support multiple output paths.

Set the output paths as the entry key. And use the name as output template.

webpack config:

entry: {
    'module/a/index': 'module/a/index.js',
    'module/b/index': 'module/b/index.js',
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
}

generated:

+-- module
    +-- a
    ¦   +-- index.js
    +-- b
        +-- index.js

Javascript Regex: How to put a variable inside a regular expression?

accepted answer doesn't work for me and doesn't follow MDN examples

see the 'Description' section in above link

I'd go with the following it's working for me:

let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

// that makes dynamicRegExp = /findMe/gi

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Working fine for the button size 80x80 pixels.

[self.leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, 10.0, 20.0, 10.0)];    
[self.leftButton setTitleEdgeInsets:UIEdgeInsetsMake(60, -75.0, 0.0, 0.0)];

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I had the same problem and solved it by simply downloading a chromedriver file for a previous version of chrome. I have found that version 79 of Chrome is compatible with the current version of Selenium.

I then saved it in a specified path, and linked that path to my webdriver.

The exact steps are specified in this link: http://chromedriver.chromium.org/downloads

how can I Update top 100 records in sql server

What's even cooler is the fact that you can use an inline Table-Valued Function to select which (and how many via TOP) row(s) to update. That is:

UPDATE MyTable
SET Column1=@Value1
FROM tvfSelectLatestRowOfMyTableMatchingCriteria(@Param1,@Param2,@Param3)

For the table valued function you have something interesting to select the row to update like:

CREATE FUNCTION tvfSelectLatestRowOfMyTableMatchingCriteria
(
    @Param1 INT,
    @Param2 INT,
    @Param3 INT
)
RETURNS TABLE AS RETURN
(
    SELECT TOP(1) MyTable.*
    FROM MyTable
    JOIN MyOtherTable
      ON ...
    JOIN WhoKnowsWhatElse
      ON ...
    WHERE MyTable.SomeColumn=@Param1 AND ...
    ORDER BY MyTable.SomeDate DESC
)

..., and there lies (in my humble opinion) the true power of updating only top selected rows deterministically while at the same time simplifying the syntax of the UPDATE statement.

Programmatically center TextView text

try this method

  public void centerTextView(LinearLayout linearLayout) {
    TextView textView = new TextView(context);
    textView.setText(context.getString(R.string.no_records));
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(18.0f);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    linearLayout.addView(textView);
}

Sqlite convert string to date

If Source Date format isn't consistent there is some problem with substr function, e.g.:

1/1/2017 or 1/11/2017 or 11/11/2017 or 1/1/17 etc.

So I followed a different apporach using a temporary table. This snippet outputs 'YYYY-MM-DD' + time if exists.

Note that this version accepts Day/Month/Year format. If you want Month/Day/Year swap the first two variables DayPart and MonthPart. Also, two year dates '44-'99 assumes 1944-1999 whereas '00-'43 assumes 2000-2043.

 BEGIN;

    CREATE TEMP TABLE [DateconvertionTable] (Id TEXT PRIMARY KEY, OriginalDate  TEXT  , SepA  INTEGER,  DayPart TEXT,Rest1 TEXT, SepB  INTEGER,  MonthPart TEXT, Rest2 TEXT, SepC  INTEGER,  YearPart TEXT, Rest3 TEXT, NewDate TEXT);
    INSERT INTO [DateconvertionTable] (Id,OriginalDate)  SELECT SourceIdColumn, SourceDateColumn From  [SourceTable];

    --day Part (If day is first)

    UPDATE [DateconvertionTable] SET SepA=instr(OriginalDate ,'/');
    UPDATE [DateconvertionTable] SET DayPart=substr(OriginalDate,1,SepA-1) ;
    UPDATE [DateconvertionTable] SET Rest1=substr(OriginalDate,SepA+1);

    --Month Part (If Month is second)

    UPDATE [DateconvertionTable] SET SepB=instr(Rest1,'/');
    UPDATE [DateconvertionTable]  SET MonthPart=substr(Rest1, 1,SepB-1);
    UPDATE [DateconvertionTable] SET Rest2=substr(Rest1,SepB+1);

    --Year Part (3d)

    UPDATE [DateconvertionTable] SET SepC=instr(Rest2,' ');

           --Use Cases In case of time string included
    UPDATE [DateconvertionTable]  SET YearPart= CASE WHEN SepC=0 THEN Rest2 ELSE substr(Rest2,1,SepC-1)  END;

           --The Rest considered time
    UPDATE [DateconvertionTable]  SET Rest3= CASE WHEN SepC=0 THEN  '' ELSE substr(Rest2,SepC+1) END;

           -- Convert 1 digit day and month to 2 digit
    UPDATE [DateconvertionTable] SET DayPart=0||DayPart WHERE CAST(DayPart AS INTEGER)<10;
    UPDATE [DateconvertionTable] SET MonthPart=0||MonthPart WHERE CAST(MonthPart AS INTEGER)<10;

           --If there is a need to convert 2 digit year to 4 digit year, make some assumptions...
    UPDATE [DateconvertionTable] SET YearPart=19||YearPart WHERE CAST(YearPart AS INTEGER)>=44 AND CAST(YearPart AS INTEGER)<100;
    UPDATE [DateconvertionTable] SET YearPart=20||YearPart WHERE CAST(YearPart AS INTEGER)<44 AND CAST(YearPart AS INTEGER)<100;

    UPDATE [DateconvertionTable] SET NewDate = YearPart  || '-' || MonthPart || '-' || DayPart || ' ' || Rest3;  

    UPDATE [SourceTable] SET SourceDateColumn=(Select NewDate FROM DateconvertionTable WHERE [DateconvertionTable].id=SourceIdColumn);
    END;

Turning a Comma Separated string into individual rows

You can use the following function to extract data

CREATE FUNCTION [dbo].[SplitString]
(    
    @RowData NVARCHAR(MAX),
    @Delimeter NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE 
(
    ID INT IDENTITY(1,1),
    Data NVARCHAR(MAX)
) 
AS
BEGIN 
    DECLARE @Iterator INT
    SET @Iterator = 1

    DECLARE @FoundIndex INT
    SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)

    WHILE (@FoundIndex>0)
    BEGIN
        INSERT INTO @RtnValue (data)
        SELECT 
            Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))

        SET @RowData = SUBSTRING(@RowData,
                @FoundIndex + DATALENGTH(@Delimeter) / 2,
                LEN(@RowData))

        SET @Iterator = @Iterator + 1
        SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
    END

    INSERT INTO @RtnValue (Data)
    SELECT Data = LTRIM(RTRIM(@RowData))

    RETURN
END

C# Copy a file to another location with a different name

The easiest method you can use is this:

System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);

This will take care of everything you requested.

Why is the <center> tag deprecated in HTML?

According to W3Schools.com,

The center element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.

The HTML 4.01 spec gives this reason for deprecating the tag:

The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center".

'console' is undefined error for Internet Explorer

if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}

Calling virtual functions inside constructors

The C++ FAQ Lite Covers this pretty well:

Essentially, during the call to the base classes constructor, the object is not yet of the derived type and thus the base type's implementation of the virtual function is called and not the derived type's.

Get the value of checked checkbox?

In my project, I usually use this snippets:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

What is jQuery Unobtrusive Validation?

For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.

Both use the following JavaScript with jQuery:

  $("#commentForm").validate({
    submitHandler: function(form) {
      // some other code
      // maybe disabling submit button
      // then:
      alert("This is a valid form!");
//      form.submit();
    }
  });

The main differences between the two plugins are the attributes used for each approach.

jQuery Validation

Simply use the following attributes:

  • Set required if required
  • Set type for proper formatting (email, etc.)
  • Set other attributes such as size (min length, etc.)

Here's the form...

<form id="commentForm">
  <label for="form-name">Name (required, at least 2 characters)</label>
  <input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
  <input type="submit" value="Submit">
</form>

jQuery Validation Unobtrusive

The following data attributes are needed:

  • data-msg-required="This is required."
  • data-rule-required="true/false"

Here's the form...

<form id="commentForm">
  <label for="form-x-name">Name (required, at least 2 characters)</label>
  <input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
  <input type="submit" value="Submit">
</form>

Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.

References: - jQuery Validation: https://jqueryvalidation.org/documentation/

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

String.strip() in Python

No, it is better practice to leave them out.

Without strip(), you can have empty keys and values:

apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>

Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.

Chrome Extension: Make it run every page load

From a background script you can listen to the chrome.tabs.onUpdated event and check the property changeInfo.status on the callback. It can be loading or complete. If it is complete, do the action.

Example:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

    // do your things

  }
})

Because this will probably trigger on every tab completion, you can also check if the tab is active on its homonymous attribute, like this:

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete' && tab.active) {

    // do your things

  }
})

regex for zip-code

For the listed three conditions only, these expressions might work also:

^\d{5}[-\s]?(?:\d{4})?$
^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
^\[0-9]{5}[-\s]?(?:\d{4})?$
^\d{5}[-\s]?(?:[0-9]{4})?$

Please see this demo for additional explanation.

If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:

123451234
12345 1234
12345  1234

this expression for instance would be a secondary option with less constraints:

^\d{5}([-]|\s*)?(\d{4})?$

Please see this demo for additional explanation.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;_x000D_
const str = `12345_x000D_
12345-6789_x000D_
12345 1234_x000D_
123451234_x000D_
12345 1234_x000D_
12345  1234_x000D_
1234512341_x000D_
123451`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
        regex.lastIndex++;_x000D_
    }_x000D_
    _x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
[…]
Encoders:
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 ------
[…]
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

Best way to detect when a user leaves a web page?

Try the onbeforeunload event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo.

Alternatively, you can send out an Ajax request when he leaves.

Boolean Field in Oracle

To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.

Update query using Subquery in Sql Server

you can join both tables even on UPDATE statements,

UPDATE  a
SET     a.marks = b.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

for faster performance, define an INDEX on column marks on both tables.

using SUBQUERY

UPDATE  tempDataView 
SET     marks = 
        (
          SELECT marks 
          FROM tempData b 
          WHERE tempDataView.Name = b.Name
        )

How to convert a file to utf-8 in Python?

This worked for me in a small test:

sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")

target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))

byte[] to file in Java

From Java 7 onward you can use the try-with-resources statement to avoid leaking resources and make your code easier to read. More on that here.

To write your byteArray to a file you would do:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}

What exactly do "u" and "r" string flags do, and what are raw string literals?

Unicode string literals

Unicode string literals (string literals prefixed by u) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.

Raw string literals

If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n to your string literal. So when you print the 'hello\nworld' string, the words will be printed on separate lines. That's very handy!

On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:

'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'

In such situations you can just prefix the string literal with the r character like this: r'hello\nworld' and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.

Raw string literals are not completely "raw"?

Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.

From the lexical definition of a string literal:

string     ::=  "'" stringitem* "'"
stringitem ::=  stringchar | escapeseq
stringchar ::=  <any source character except "\" or newline or the quote>
escapeseq  ::=  "\" <any source character>

It is clear that string literals (raw or not) containing a bare quote character: 'hello'world' or ending with a backslash: 'hello world\' are not valid.

OracleCommand SQL Parameters Binding

string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";

System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
    con.Open();

    System.Data.OracleClient.OracleCommand Cmd = 
        new System.Data.OracleClient.OracleCommand(
            "SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);

//for oracle..it is :object_name and for sql it s @object_name
    Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));

    System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
    DataSet myDS = new DataSet();
    da.Fill(myDS);
    try
    {
        lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
        lblBatch.ForeColor = System.Drawing.Color.Green;
        lblBatch.Visible = true;
    }
    catch 
    {
        lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
        lblBatch.ForeColor = System.Drawing.Color.Red;
        lblBatch.Visible = true;   
    }
    da.Dispose();
    con.Close();

Why aren't variable-length arrays part of the C++ standard?

You could always use alloca() to allocate memory on the stack at runtime, if you wished:

void foo (int n)
{
    int *values = (int *)alloca(sizeof(int) * n);
}

Being allocated on the stack implies that it will automatically be freed when the stack unwinds.

Quick note: As mentioned in the Mac OS X man page for alloca(3), "The alloca() function is machine and compiler dependent; its use is dis-couraged." Just so you know.

Split by comma and strip whitespace in Python

import re
result=[x for x in re.split(',| ',your_string) if x!='']

this works fine for me.

How to merge every two lines into one from the command line?

Another solutions using vim (just for reference).

Solution 1:

Open file in vim vim filename, then execute command :% normal Jj

This command is very easy to understand:

  • % : for all the lines,
  • normal : execute normal command
  • Jj : execute Join command, then jump to below line

After that, save the file and exit with :wq

Solution 2:

Execute the command in shell, vim -c ":% normal Jj" filename, then save the file and exit with :wq.

Detect if Android device has Internet connection

The latest way to do that from the documentation is to use the ConnectivityManager to query the active network and determine if it has Internet connectivity.

public boolean hasInternetConnectivity() {
    ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return (activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting());
}

Add these two permissions to your AndroidManifest.xml file:

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

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

Bat file to run a .exe at the command prompt

If you want to be real smart, at the command line type:

echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd

Then you have CreateService.cmd that you can run whenever you want (.cmd is just another extension for .bat files)

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

How can I get the external SD card path for Android 4.0+?

Yes. Different manufacturer use different SDcard name like in Samsung Tab 3 its extsd, and other samsung devices use sdcard like this different manufacturer use different names.

I had the same requirement as you. so i have created a sample example for you from my project goto this link Android Directory chooser example which uses the androi-dirchooser library. This example detect the SDcard and list all the subfolders and it also detects if the device has morethan one SDcard.

Part of the code looks like this For full example goto the link Android Directory Chooser

/**
* Returns the path to internal storage ex:- /storage/emulated/0
 *
* @return
 */
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
 }

/**
 * Returns the SDcard storage path for samsung ex:- /storage/extSdCard
 *
 * @return
 */
    private String getSDcardDirectoryPath() {
    return System.getenv("SECONDARY_STORAGE");
}


 mSdcardLayout.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        String sdCardPath;
        /***
         * Null check because user may click on already selected buton before selecting the folder
         * And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
         */

        if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
            mCurrentInternalPath = mSelectedDir.getAbsolutePath();
        } else {
            mCurrentInternalPath = getInternalDirectoryPath();
        }
        if (mCurrentSDcardPath != null) {
            sdCardPath = mCurrentSDcardPath;
        } else {
            sdCardPath = getSDcardDirectoryPath();
        }
        //When there is only one SDcard
        if (sdCardPath != null) {
            if (!sdCardPath.contains(":")) {
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File(sdCardPath);
                changeDirectory(dir);
            } else if (sdCardPath.contains(":")) {
                //Multiple Sdcards show root folder and remove the Internal storage from that.
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File("/storage");
                changeDirectory(dir);
            }
        } else {
            //In some unknown scenario at least we can list the root folder
            updateButtonColor(STORAGE_EXTERNAL);
            File dir = new File("/storage");
            changeDirectory(dir);
        }


    }
});

How to add app icon within phonegap projects?

Just add this code into your config.xml file

<icon src="path to your icon image">

eg:

<icon src="icon.png">

Al ways remember you need to use .png extension

Set a variable if undefined in JavaScript

I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.

function setDefaultVal(value, defaultValue){
   return (value === undefined) ? defaultValue : value;
}  

Usage:

hasPoints = setDefaultVal(this.hasPoints, true);

Cannot ignore .idea/workspace.xml - keeps popping up

Just tell git to not assume it is changed never matter what:

git update-index --assume-unchanged src/file/to/ignore

yes, you can remove the files from the git repository. But if your team all use the same IDE or you are by yourself, you probably don't want to do that. For yourself, you want to have an ok starting point to resume working, for your teammates as well.

EXCEL VBA Check if entry is empty or not 'space'

You can use the following code to check if a textbox object is null/empty

'Checks if the box is null

If Me.TextBox & "" <> "" Then

        'Enter Code here...

End if

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);  

To this:

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);

How to save DataFrame directly to Hive?

For Hive external tables I use this function in PySpark:

def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
    print("Saving result in {}.{}".format(database, table_name))
    output_schema = "," \
        .join(["{} {}".format(x.name.lower(), x.dataType) for x in list(dataframe.schema)]) \
        .replace("StringType", "STRING") \
        .replace("IntegerType", "INT") \
        .replace("DateType", "DATE") \
        .replace("LongType", "INT") \
        .replace("TimestampType", "INT") \
        .replace("BooleanType", "BOOLEAN") \
        .replace("FloatType", "FLOAT")\
        .replace("DoubleType","FLOAT")
    output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)

    sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))

    query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
        .format(database, table_name, output_schema, save_format, database, table_name)
    sparkSession.sql(query)
    dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.

source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

Convert array into csv

A slight adaptation to the solution above by kingjeffrey for when you want to create and echo the CSV within a template (Ie - most frameworks will have output buffering enabled and you are required to set headers etc in controllers.)

// Create Some data
<?php
    $data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );


// Create a stream opening it with read / write mode
$stream = fopen('data://text/plain,' . "", 'w+');

// Iterate over the data, writting each line to the text stream
foreach ($data as $val) {
    fputcsv($stream, $val);
}

// Rewind the stream
rewind($stream);

// You can now echo it's content
echo stream_get_contents($stream);

// Close the stream 
fclose($stream);

Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.

Convert char array to single int?

I'll just leave this here for people interested in an implementation with no dependencies.

inline int
stringLength (char *String)
    {
    int Count = 0;
    while (*String ++) ++ Count;
    return Count;
    }

inline int
stringToInt (char *String)
    {
    int Integer = 0;
    int Length = stringLength(String);
    for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
        {
        if (String[Caret] == '-') return Integer * -1;
        Integer += (String[Caret] - '0') * Digit;
        }

    return Integer;
    }

Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.

XAMPP permissions on Mac OS X?

What worked for me was,

  • Open Terminal from the XAMPP app,
  • type in this,

chmod -R 0777 /opt/lampp/htdocs/

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

How can I get Docker Linux container information from within the container itself?

Use docker inspect.

$ docker ps # get conteiner id
$ docker inspect 4abbef615af7
[{
    "ID": "4abbef615af780f24991ccdca946cd50d2422e75f53fb15f578e14167c365989",
    "Created": "2014-01-08T07:13:32.765612597Z",
    "Path": "/bin/bash",
    "Args": [
        "-c",
        "/start web"
    ],
    "Config": {
        "Hostname": "4abbef615af7",
...

Can get ip as follows.

$ docker inspect -format="{{ .NetworkSettings.IPAddress }}" 2a5624c52119
172.17.0.24

What is the difference between require and require-dev sections in composer.json?

  1. According to composer's manual:

    require-dev (root-only)

    Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

    So running composer install will also download the development dependencies.

  2. The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

How to set up a cron job to run an executable every hour?

use

path_to_exe >> log_file

to see the output of your command also errors can be redirected with

path_to_exe &> log_file

also you can use

crontab -l

to check if your edits were saved.

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

.map() a Javascript ES6 Map?

You can map() arrays, but there is no such operation for Maps. The solution from Dr. Axel Rauschmayer:

  • Convert the map into an array of [key,value] pairs.
  • Map or filter the array.
  • Convert the result back to a map.

Example:

let map0 = new Map([
  [1, "a"],
  [2, "b"],
  [3, "c"]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => [k * 2, '_' + v])
);

resulted in

{2 => '_a', 4 => '_b', 6 => '_c'}

How to set aliases in the Git Bash for Windows?

There is two easy way to set the alias.

  1. Using Bash
  2. Updating .gitconfig file

Using Bash

Open bash terminal and type git command. For instance:

$ git config --global alias.a add
$ git config --global alias.aa 'add .'
$ git config --global alias.cm 'commit -m'
$ git config --global alias.s status
---
---

It will eventually add those aliases on .gitconfig file.

Updating .gitconfig file

Open .gitconfig file located at 'C:\Users\username\.gitconfig' in Windows environment. Then add following lines:

[alias]  
a = add  
aa = add . 
cm = commit -m 
gau = add --update 
au = add --update
b = branch
---
---

How to show code but hide output in RMarkdown?

For completely silencing the output, here what works for me

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({


# Your code here
2 * 2
# etc etc


})})
```

The 5 measures used above are

  1. error = FALSE
  2. warning = FALSE
  3. message = FALSE
  4. invisible()
  5. capture.output()

IEnumerable vs List - What to Use? How do they work?

I will share one misused concept that I fell into one day:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));


// updating existing list
names[0] = "ford";

// Guess what should be printed before continuing
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Expected result

// I was expecting    
print( startingWith_M.ToList() ); // mercedes, mazda
print( startingWith_F.ToList() ); // fiat, ferrari

Actual result

// what printed actualy   
print( startingWith_M.ToList() ); // mazda
print( startingWith_F.ToList() ); // ford, fiat, ferrari

Explanation

As per other answers, the evaluation of the result was deferred until calling ToList or similar invocation methods for example ToArray.

So I can rewrite the code in this case as:

var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};

// updating existing list
names[0] = "ford";

// before calling ToList directly
var startingWith_M = names.Where(x => x.StartsWith("m"));

var startingWith_F = names.Where(x => x.StartsWith("f"));

print( startingWith_M.ToList() );
print( startingWith_F.ToList() );

Play arround

https://repl.it/E8Ki/0

Get OS-level system information

I think the best method out there is to implement the SIGAR API by Hyperic. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is GPL2 Apache licensed. They provide a ton of examples in Java too!

SIGAR == System Information, Gathering And Reporting tool.

Enter export password to generate a P12 certificate

The selected answer apparently does not work anymore in 2019 (at least for me).

I was trying to export a certificate using openssl (version 1.1.0) and the parameter -password doesn't work.

According to that link in the original answer (the same info is in man openssl), openssl has two parameter for passwords and they are -passin for the input parts and -passout for output files.

For the -export command, I used -passin for the password of my key file and -passout to create a new password for my P12 file.

So the complete command without any prompt was like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword

If you does not want a password, you can use pass: like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:

It will works fine with a key without password and the output certificate will be created without password too.

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

Sleep function in C++

Just use it...

Firstly include the unistd.h header file, #include<unistd.h>, and use this function for pausing your program execution for desired number of seconds:

sleep(x);

x can take any value in seconds.

If you want to pause the program for 5 seconds it is like this:

sleep(5);

It is correct and I use it frequently.

It is valid for C and C++.

How to Check whether Session is Expired or not in asp.net

Here I am checking session values(two values filled in text box on previous page)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
    {
        Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
    }
    else
    {

        lblUnit.Text = Session["sessUnit_code"].ToString();
        LblGrcSr.Text = Session["sessgrcSerial"].ToString();
    }
}

"Active Directory Users and Computers" MMC snap-in for Windows 7?

You have to enable the features in Add/Remove Programs section of your Control Panel. Select "Turn Windows features on or off"

Questions every good PHP Developer should be able to answer

Explain why the following code displays 2.5 instead of 3:

$a = 012;
echo $a / 4;

Answer: When a number is preceded by a 0 in PHP, the number is treated as an octal number (base-8). Therefore the octal number 012 is equal to the decimal number 10.

Change the background color in a twitter bootstrap modal?

Add the following CSS;

.modal .modal-dialog .modal-content{  background-color: #d4c484; }

<div class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
...
...

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

phantomjs not waiting for "full" page load

In my program, I use some logic to judge if it was onload: watching it's network request, if there was no new request on past 200ms, I treat it onload.

Use this, after onLoadFinish().

function onLoadComplete(page, callback){
    var waiting = [];  // request id
    var interval = 200;  //ms time waiting new request
    var timer = setTimeout( timeout, interval);
    var max_retry = 3;  //
    var counter_retry = 0;

    function timeout(){
        if(waiting.length && counter_retry < max_retry){
            timer = setTimeout( timeout, interval);
            counter_retry++;
            return;
        }else{
            try{
                callback(null, page);
            }catch(e){}
        }
    }

    //for debug, log time cost
    var tlogger = {};

    bindEvent(page, 'request', function(req){
        waiting.push(req.id);
    });

    bindEvent(page, 'receive', function (res) {
        var cT = res.contentType;
        if(!cT){
            console.log('[contentType] ', cT, ' [url] ', res.url);
        }
        if(!cT) return remove(res.id);
        if(cT.indexOf('application') * cT.indexOf('text') != 0) return remove(res.id);

        if (res.stage === 'start') {
            console.log('!!received start: ', res.id);
            //console.log( JSON.stringify(res) );
            tlogger[res.id] = new Date();
        }else if (res.stage === 'end') {
            console.log('!!received end: ', res.id, (new Date() - tlogger[res.id]) );
            //console.log( JSON.stringify(res) );
            remove(res.id);

            clearTimeout(timer);
            timer = setTimeout(timeout, interval);
        }

    });

    bindEvent(page, 'error', function(err){
        remove(err.id);
        if(waiting.length === 0){
            counter_retry = 0;
        }
    });

    function remove(id){
        var i = waiting.indexOf( id );
        if(i < 0){
            return;
        }else{
            waiting.splice(i,1);
        }
    }

    function bindEvent(page, evt, cb){
        switch(evt){
            case 'request':
                page.onResourceRequested = cb;
                break;
            case 'receive':
                page.onResourceReceived = cb;
                break;
            case 'error':
                page.onResourceError = cb;
                break;
            case 'timeout':
                page.onResourceTimeout = cb;
                break;
        }
    }
}

How can I stop a While loop?

just indent your code correctly:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            return period
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            return 0
        else:   
            return period

You need to understand that the break statement in your example will exit the infinite loop you've created with while True. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break statement by a return statement.

Following your idea to use an infinite loop, this is the best way to write it:

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while True:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        period+=1
        if numpy.array_equal(tmp,universe_array) is True:
            break
        if period>12:  #i wrote this line to stop it..but seems its doesnt work....help..
            period = 0
            break

    return period

Keystore change passwords

[How can I] Change the password, so I can share it with others and let them sign

Using keytool:

keytool -storepasswd -keystore /path/to/keystore
Enter keystore password:  changeit
New keystore password:  new-password
Re-enter new keystore password:  new-password

What is the largest Safe UDP Packet Size on the Internet

I fear i incur upset reactions but nevertheless, to clarify for me if i'm wrong or those seeing this question and being interested in an answer:

my understanding of https://tools.ietf.org/html/rfc1122 whose status is "an official specification" and as such is the reference for the terminology used in this question and which is neither superseded by another RFC nor has errata contradicting the following:

theoretically, ie. based on the written spec., UDP like given by https://tools.ietf.org/html/rfc1122#section-4 has no "packet size". Thus the answer could be "indefinite"

In practice, which is what this questions likely seeked (and which could be updated for current tech in action), this might be different and I don't know.

I apologize if i caused upsetting. https://tools.ietf.org/html/rfc1122#page-8 The "Internet Protocol Suite" and "Architectural Assumptions" don't make clear to me the "assumption" i was on, based on what I heard, that the layers are separate. Ie. the layer UDP is in does not have to concern itself with the layer IP is in (and the IP layer does have things like Reassembly, EMTU_R, Fragmentation and MMS_R (https://tools.ietf.org/html/rfc1122#page-56))

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In my case the tensorflow install was looking for cudart64_101.dll

enter image description here

The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1

I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll

enter image description here

This is the wrong file!! cudart64_101.dll ? cudart64_110.dll

Solution

Download Cuda 10.1 from https://developer.nvidia.com/

Install (mine crashes with NSight Visual Studio Integration, so I switched that off)

enter image description here

When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing

enter image description here

Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library

enter image description here

You may need a reboot if the path is not picked up by the system straight away

enter image description here

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

How to add url parameters to Django template url tag?

1: HTML

           <tbody>
            {% for ticket in tickets %}
              <tr>
                <td class="ticket_id">{{ticket.id}}</td>
                <td class="ticket_eam">{{ticket.eam}}</td>
                <td class="ticket_subject">{{ticket.subject}}</td>
                <td>{{ticket.zone}}</td>
                <td>{{ticket.plaza}}</td>
                <td>{{ticket.lane}}</td>
                <td>{{ticket.uptime}}</td>
                <td>{{ticket.downtime}}</td>
                <td><a href="{% url 'ticket_details' ticket_id=ticket.id %}"><button data-toggle="modal" data-target="#modaldemo3" class="value-modal"><i class="icon ion-edit"></a></i></button> <button><i class="fa fa-eye-slash"></i></button>
              </tr>
            {% endfor %}
            </tbody>

The {% url 'ticket_details' %} is the function name in your views

2: Views.py

def ticket_details(request, ticket_id):

   print(ticket_id)
   return render(request, ticket.html)

ticket_id is the parameter you will get from the ticket_id=ticket.id

3: URL.py

urlpatterns = [
path('ticket_details/?P<int:ticket_id>/', views.ticket_details, name="ticket_details") ]

/?P - where ticket_id is the name of the group and pattern is some pattern to match.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Creating a PDF from a RDLC Report in the Background

The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:

protected void Button1_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;
    string HIJRA_TODAY = "01/10/1435";
    ReportParameter[] param = new ReportParameter[3];
    param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
    param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
    param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);

    byte[] bytes = ReportViewer1.LocalReport.Render(
        "PDF", 
        null, 
        out mimeType, 
        out encoding, 
        out extension, 
        out streamIds, 
        out warnings);

    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader(
        "content-disposition", 
        "attachment; filename= filename" + "." + extension);
    Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    Response.Flush(); // send it to the client to download  
    Response.End();
}    

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

How do I disable a href link in JavaScript?

Install this plugin for jquery and use it

http://plugins.jquery.com/project/jqueryenabledisable

It allows you to disable/enable pretty much any field in the page.

If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.

code looks like this:

<a href="javascript: openPage()" >Click here</a>

and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}

You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,

<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>

This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:

<a href="Visible Link" onclick="showDiv()">

and write the js code as:

function showDiv(){
document.getElememtById("divid").style.display="block";
}

You can also put an id tag to the html tag, so it would be

<a id="myATag" href="whatever"></a>

And get this id on your javascript by using

document.getElementById("myATag").value="#"; 

One of this must work for sure haha

Proper use of errors

The convention for out of range in JavaScript is using RangeError. To check the type use if / else + instanceof starting at the most specific to the most generic

try {
    throw new RangeError();
}
catch (e){
    if (e instanceof RangeError){
        console.log('out of range');
    } else { 
        throw; 
    }
}

How can I make my layout scroll both horizontally and vertically?

I was able to find a simple way to achieve both scrolling behaviors.

Here is the xml for it:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:scrollbars="vertical">

    <HorizontalScrollView 
        android:layout_width="320px" android:layout_height="fill_parent">

        <TableLayout
            android:id="@+id/linlay" android:layout_width="320px"
            android:layout_height="fill_parent" android:stretchColumns="1"
            android:background="#000000"/>

    </HorizontalScrollView>

</ScrollView>

How do I install a custom font on an HTML site

there is a simple way to do this: in the html file add:

<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />

Note: you put the name of .ttf file you have. then go to to your css file and add:

h1 {
    color: blue;
    font-family: vermin vibes;
}

Note: you put the font family name of the font you have.

Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.

SQL split values to multiple rows

My variant: stored procedure that takes table name, field names and delimiter as arguments. Inspired by post http://www.marcogoncalves.com/2011/03/mysql-split-column-string-into-rows/

delimiter $$

DROP PROCEDURE IF EXISTS split_value_into_multiple_rows $$
CREATE PROCEDURE split_value_into_multiple_rows(tablename VARCHAR(20),
    id_column VARCHAR(20), value_column VARCHAR(20), delim CHAR(1))
  BEGIN
    DECLARE id INT DEFAULT 0;
    DECLARE value VARCHAR(255);
    DECLARE occurrences INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE splitted_value VARCHAR(255);
    DECLARE done INT DEFAULT 0;
    DECLARE cur CURSOR FOR SELECT tmp_table1.id, tmp_table1.value FROM 
        tmp_table1 WHERE tmp_table1.value IS NOT NULL AND tmp_table1.value != '';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @expr = CONCAT('CREATE TEMPORARY TABLE tmp_table1 (id INT NOT NULL, value VARCHAR(255)) ENGINE=Memory SELECT ',
        id_column,' id, ', value_column,' value FROM ',tablename);
    PREPARE stmt FROM @expr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    DROP TEMPORARY TABLE IF EXISTS tmp_table2;
    CREATE TEMPORARY TABLE tmp_table2 (id INT NOT NULL, value VARCHAR(255) NOT NULL) ENGINE=Memory;

    OPEN cur;
      read_loop: LOOP
        FETCH cur INTO id, value;
        IF done THEN
          LEAVE read_loop;
        END IF;

        SET occurrences = (SELECT CHAR_LENGTH(value) -
                           CHAR_LENGTH(REPLACE(value, delim, '')) + 1);
        SET i=1;
        WHILE i <= occurrences DO
          SET splitted_value = (SELECT TRIM(SUBSTRING_INDEX(
              SUBSTRING_INDEX(value, delim, i), delim, -1)));
          INSERT INTO tmp_table2 VALUES (id, splitted_value);
          SET i = i + 1;
        END WHILE;
      END LOOP;

      SELECT * FROM tmp_table2;
    CLOSE cur;
    DROP TEMPORARY TABLE tmp_table1;
  END; $$

delimiter ;

Usage example (normalization):

CALL split_value_into_multiple_rows('my_contacts', 'contact_id', 'interests', ',');

CREATE TABLE interests (
  interest_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  interest VARCHAR(30) NOT NULL
) SELECT DISTINCT value interest FROM tmp_table2;

CREATE TABLE contact_interest (
  contact_id INT NOT NULL,
  interest_id INT NOT NULL,
  CONSTRAINT fk_contact_interest_my_contacts_contact_id FOREIGN KEY (contact_id) REFERENCES my_contacts (contact_id),
  CONSTRAINT fk_contact_interest_interests_interest_id FOREIGN KEY (interest_id) REFERENCES interests (interest_id)
) SELECT my_contacts.contact_id, interests.interest_id
    FROM my_contacts, tmp_table2, interests
    WHERE my_contacts.contact_id = tmp_table2.id AND interests.interest = tmp_table2.value;

select2 changing items dynamically

For v4 this is a known issue that won't be addressed in 4.0 but there is a workaround. Check https://github.com/select2/select2/issues/2830

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

ALTER DATABASE failed because a lock could not be placed on database

I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

How to default to other directory instead of home directory

(Please read warning below)

Really simple way to do this in Windows (works with git bash, possibly others) is to create an environmental variable called HOME that points to your desired home directory.

  1. Right click on my computer, and choose properties
  2. Choose advanced system settings (location varies by Windows version)
  3. Within system properties, choose the advanced tab
  4. On the advanced tab, choose Environmental Variables (bottom button)
  5. Under "system variable" check to see if you already have a variable called HOME. If so, edit that variable by highlighting the variable name and clicking edit. Make the new variable name the desired path.
  6. If HOME does not already exist, click "new" under system variables and create a new variable called HOME whose value is desired path.

Environmental Variable

NOTE: This may change the way other things work. For example, for me it changes where my .ssh config files live. In my case, I wanted my home to be U:\, because that's my main place that I put project work and application settings (i.e. it really is my "home" directory).

EDIT June 23, 2017: This answer continues to get occasional upvotes, and I want to warn people that although this may "work", I agree with @AnthonyRaymond that it's not recommended. This is more of a temporary fix or a fix if you don't care if other things break. Changing your home won't cause active damage (like deleting your hard drive) but it's likely to cause insidious annoyances later. When you do start to have annoying problems down the road, you probably won't remember this change... so you're likely to be scratching your head later on!

How to write header row with csv.DictWriter?

Another way to do this would be to add before adding lines in your output, the following line :

output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))

The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.

Count the number of all words in a string

Also from stringi package, the straight forward function stri_count_words

stringi::stri_count_words(str1)
#[1] 7

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....

static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";

public static void ReadExcel() {
InputStream inputStream = null;
   try {
        inputStream = new FileInputStream(new File(excelLoc));
        Workbook wb = WorkbookFactory.create(inputStream);
        int numberOfSheet = wb.getNumberOfSheets();

        for (int i = 0; i < numberOfSheet; i++) {
             Sheet sheet = wb.getSheetAt(i);
             //.... Customize your code here
             // To get sheet name, try -> sheet.getSheetName()
        }
   } catch {}
}

How to deal with SettingWithCopyWarning in Pandas

In general the point of the SettingWithCopyWarning is to show users (and especially new users) that they may be operating on a copy and not the original as they think. There are false positives (IOW if you know what you are doing it could be ok). One possibility is simply to turn off the (by default warn) warning as @Garrett suggest.

Here is another option:

In [1]: df = DataFrame(np.random.randn(5, 2), columns=list('AB'))

In [2]: dfa = df.ix[:, [1, 0]]

In [3]: dfa.is_copy
Out[3]: True

In [4]: dfa['A'] /= 2
/usr/local/bin/ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  #!/usr/local/bin/python

You can set the is_copy flag to False, which will effectively turn off the check, for that object:

In [5]: dfa.is_copy = False

In [6]: dfa['A'] /= 2

If you explicitly copy then no further warning will happen:

In [7]: dfa = df.ix[:, [1, 0]].copy()

In [8]: dfa['A'] /= 2

The code the OP is showing above, while legitimate, and probably something I do as well, is technically a case for this warning, and not a false positive. Another way to not have the warning would be to do the selection operation via reindex, e.g.

quote_df = quote_df.reindex(columns=['STK', ...])

Or,

quote_df = quote_df.reindex(['STK', ...], axis=1)  # v.0.21

Checking images for similarity with OpenCV

If for matching identical images ( same size/orientation )

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Source

Rotate camera in Three.js with mouse

Here's a project with a rotating camera. Looking through the source it seems to just move the camera position in a circle.

function onDocumentMouseMove( event ) {

    event.preventDefault();

    if ( isMouseDown ) {

        theta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.5 )
                + onMouseDownTheta;
        phi = ( ( event.clientY - onMouseDownPosition.y ) * 0.5 )
              + onMouseDownPhi;

        phi = Math.min( 180, Math.max( 0, phi ) );

        camera.position.x = radious * Math.sin( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.position.y = radious * Math.sin( phi * Math.PI / 360 );
        camera.position.z = radious * Math.cos( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.updateMatrix();

    }

    mouse3D = projector.unprojectVector(
        new THREE.Vector3(
            ( event.clientX / renderer.domElement.width ) * 2 - 1,
            - ( event.clientY / renderer.domElement.height ) * 2 + 1,
            0.5
        ),
        camera
    );
    ray.direction = mouse3D.subSelf( camera.position ).normalize();

    interact();
    render();

}

Here's another demo and in this one I think it just creates a new THREE.TrackballControls object with the camera as a parameter, which is probably the better way to go.

controls = new THREE.TrackballControls( camera );
controls.target.set( 0, 0, 0 )

Using RegEX To Prefix And Append In Notepad++

Use a Macro.

Macro>Start Recording

Use the keyboard to make your changes in a repeatable manner e.g.

home>type "able">end>down arrow>home

Then go back to the menu and click stop recording then run a macro multiple times.

That should do it and no regex based complications!

Nginx serves .php files as downloads, instead of executing them

If anything else doesn't help you. And maybe earlier you installed apache2 with info.php test file. Just clear App Data (cache,cookie) for localhost.

Adding a library/JAR to an Eclipse Android project

Now for the missing class problem.

I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.

This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.

Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:

  1. Download the library to your host development system.
  2. Create a new folder, libs, in your Eclipse/Android project.
  3. Right-click libs and choose Import -> General -> File System, then Next, Browse in the filesystem to find the library's parent directory (i.e.: where you downloaded it to).
  4. Click OK, then click the directory name (not the checkbox) in the left pane, then check the relevant JAR in the right pane. This puts the library into your project (physically).
  5. Right-click on your project, choose Build Path -> Configure Build Path, then click the Libraries tab, then Add JARs..., navigate to your new JAR in the libs directory and add it. (This, incidentally, is the moment at which your new JAR is converted for use on Android.)

NOTE

Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.

What you've done here accomplishes two things:

  1. Includes a Dalvik-converted JAR in your Android project.
  2. Makes Java definitions available to Eclipse in order to find the third-party classes when developing (that is, compiling) your project's source code.

How to display a range input slider vertically

Its very simple. I had implemented using -webkit-appearance: slider-vertical, It worked in chorme, Firefox, Edge

<input type="range">
input[type=range]{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 50px;
    height: 200px;
    padding: 0 24px;
    outline: none;
    background:transparent;
}

Sorting std::map using value

To build on Oli's solution (https://stackoverflow.com/a/5056797/2472351) using multimaps, you can replace the two template functions he used with the following:

template <typename A, typename B>
multimap<B, A> flip_map(map<A,B> & src) {

    multimap<B,A> dst;

    for(map<A, B>::const_iterator it = src.begin(); it != src.end(); ++it)
        dst.insert(pair<B, A>(it -> second, it -> first));

    return dst;
}

Here is an example program that shows all the key-value pairs being preserved after performing the flip.

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

template <typename A, typename B>
multimap<B, A> flip_map(map<A,B> & src) {

    multimap<B,A> dst;

    for(typename map<A, B>::const_iterator it = src.begin(); it != src.end(); ++it)
        dst.insert(pair<B, A>(it -> second, it -> first));

    return dst;
}

int main() {

    map<string, int> test;
    test["word"] = 1;
    test["spark"] = 15;
    test["the"] = 2;
    test["mail"] = 3;
    test["info"] = 3;
    test["sandwich"] = 15;

    cout << "Contents of original map:\n" << endl;
    for(map<string, int>::const_iterator it = test.begin(); it != test.end(); ++it)
        cout << it -> first << " " << it -> second << endl; 

    multimap<int, string> reverseTest = flip_map(test);

    cout << "\nContents of flipped map in descending order:\n" << endl;
    for(multimap<int, string>::const_reverse_iterator it = reverseTest.rbegin(); it != reverseTest.rend(); ++it)
        cout << it -> first << " " << it -> second << endl; 

    cout << endl;
}

Result:

enter image description here

HTTP GET in VB.NET

Use the WebRequest class

This is to get an image:

Try
    Dim _WebRequest As System.Net.WebRequest = Nothing
    _WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

Try
    _NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

What is the difference between a static and a non-static initialization code block

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

Where is the user's Subversion config file stored on the major operating systems?

Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Hide the browse button on a input type=file

Just add negative text intent as so:

input[type=file] {
  text-indent: -120px;
}

before:

enter image description here

after:

enter image description here

Vertical Alignment of text in a table cell

Try

_x000D_
_x000D_
td.description {_x000D_
  line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

Set the line-height value to the desired value.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

This code should do the trick:

        string strFinalPath = string.Empty;
        string normalizedFirstPath = Path1.TrimEnd(new char[] { '\\' });
        string normalizedSecondPath = Path2.TrimStart(new char[] { '\\' });
        strFinalPath =  Path.Combine(normalizedFirstPath, normalizedSecondPath);
        return strFinalPath;

LINQ to SQL - Left Outer Join with multiple join conditions

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

Or you could use a subquery:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

JQuery string contains check

Please try:

str1.contains(str2)

Play audio from a stream using C#

I've tweaked the source posted in the question to allow usage with Google's TTS API in order to answer the question here:

bool waiting = false;
AutoResetEvent stop = new AutoResetEvent(false);
public void PlayMp3FromUrl(string url, int timeout)
{
    using (Stream ms = new MemoryStream())
    {
        using (Stream stream = WebRequest.Create(url)
            .GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
        }
        ms.Position = 0;
        using (WaveStream blockAlignedStream =
            new BlockAlignReductionStream(
                WaveFormatConversionStream.CreatePcmStream(
                    new Mp3FileReader(ms))))
        {
            using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
            {
                waveOut.Init(blockAlignedStream);
                waveOut.PlaybackStopped += (sender, e) =>
                {
                    waveOut.Stop();
                };
                waveOut.Play();
                waiting = true;
                stop.WaitOne(timeout);
                waiting = false;
            }
        }
    }
}

Invoke with:

var playThread = new Thread(timeout => PlayMp3FromUrl("http://translate.google.com/translate_tts?q=" + HttpUtility.UrlEncode(relatedLabel.Text), (int)timeout));
playThread.IsBackground = true;
playThread.Start(10000);

Terminate with:

if (waiting)
    stop.Set();

Notice that I'm using the ParameterizedThreadDelegate in the code above, and the thread is started with playThread.Start(10000);. The 10000 represents a maximum of 10 seconds of audio to be played so it will need to be tweaked if your stream takes longer than that to play. This is necessary because the current version of NAudio (v1.5.4.0) seems to have a problem determining when the stream is done playing. It may be fixed in a later version or perhaps there is a workaround that I didn't take the time to find.