Programs & Examples On #Adm2

What is the best project structure for a Python application?

Non-python data is best bundled inside your Python modules using the package_data support in setuptools. One thing I strongly recommend is using namespace packages to create shared namespaces which multiple projects can use -- much like the Java convention of putting packages in com.yourcompany.yourproject (and being able to have a shared com.yourcompany.utils namespace).

Re branching and merging, if you use a good enough source control system it will handle merges even through renames; Bazaar is particularly good at this.

Contrary to some other answers here, I'm +1 on having a src directory top-level (with doc and test directories alongside). Specific conventions for documentation directory trees will vary depending on what you're using; Sphinx, for instance, has its own conventions which its quickstart tool supports.

Please, please leverage setuptools and pkg_resources; this makes it much easier for other projects to rely on specific versions of your code (and for multiple versions to be simultaneously installed with different non-code files, if you're using package_data).

Install .ipa to iPad with or without iTunes

In the latest version of iOS share ipa through AirDroap from mac to iPhone. it will directly install in your iPhone.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).

ClusterIp exposure < NodePort exposure < LoadBalancer exposure

  • ClusterIp
    Expose service through k8s cluster with ip/name:port
  • NodePort
    Expose service through Internal network VM's also external to k8s ip/name:port
  • LoadBalancer
    Expose service through External world or whatever you defined in your LB.

Google Map API - Removing Markers

You can try this

    markers[markers.length-1].setMap(null);

Hope it works.

How do I find the PublicKeyToken for a particular dll?

sn -T <assembly> in Visual Studio command line. If an assembly is installed in the global assembly cache, it's easier to go to C:\Windows\assembly and find it in the list of GAC assemblies.

On your specific case, you might be mixing type full name with assembly reference, you might want to take a look at MSDN.

RecyclerView - Get view at particular position

I suppose you are using a LinearLayoutManager to show the list. It has a nice method called findViewByPosition that

Finds the view which represents the given adapter position.

All you need is the adapter position of the item you are interested in.

edit: as noted by Paul Woitaschek in the comments, findViewByPosition is a method of LayoutManager so it would work with all LayoutManagers (i.e. StaggeredGridLayoutManager, etc.)

Character reading from file in Python

But it really is "I don\u2018t like this" and not "I don't like this". The character u'\u2018' is a completely different character than "'" (and, visually, should correspond more to '`').

If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.

punctuation = {
  u'\u2018': "'",
  u'\u2019': "'",
}
for src, dest in punctuation.iteritems():
  text = text.replace(src, dest)

There are an awful lot of punctuation characters in unicode, however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.

How to create streams from string in Node.Js?

There's a module for that: https://www.npmjs.com/package/string-to-stream

var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got the same error, what worked for me is:

  1. Fix references error.
  2. Close Visual Studio.
  3. Delete Packages.
  4. Delete .vs folder.
  5. Run Project Again.
  6. Rebuild Project.

JSONException: Value of type java.lang.String cannot be converted to JSONObject

Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.

So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.

BTW. i used UTF-8 encoding on both sides. PHP side: header('Content-type=application/json; charset=utf-8');

JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

So try the solution one by one 1,2,3,4...! Hope it helps you guys!

try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

How to get first and last day of previous month (with timestamp) in SQL Server

select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) --First day of previous month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1) --Last Day of previous month

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

How to round an image with Glide library?

its very simple i have seen Glide library its very good library and essay base on volley Google's library

usethis library for rounded image view

https://github.com/hdodenhof/CircleImageView

now

//For a simple view:

 @Override
 public void onCreate(Bundle savedInstanceState) {
  ...

  CircleImageView civProfilePic = (CircleImageView)findViewById(R.id.ivProfile);
  Glide.load("http://goo.gl/h8qOq7").into(civProfilePic);
}

//For a list:

@Override
public View getView(int position, View recycled, ViewGroup container) {
final ImageView myImageView;
 if (recycled == null) {
    myImageView = (CircleImageView) inflater.inflate(R.layout.my_image_view,
            container, false);
} else {
    myImageView = (CircleImageView) recycled;
}

String url = myUrls.get(position);

Glide.load(url)
    .centerCrop()
    .placeholder(R.drawable.loading_spinner)
    .animate(R.anim.fade_in)
    .into(myImageView);

  return myImageView;
}

and in XML

<de.hdodenhof.circleimageview.CircleImageView
   android:id="@+id/ivProfile
   android:layout_width="160dp"
   android:layout_height="160dp"
   android:layout_centerInParent="true"
   android:src="@drawable/hugh"
   app:border_width="2dp"
   app:border_color="@color/dark" />

PHP json_encode encoding numbers as strings

try $arr = array('var1' => 100, 'var2' => 200);
$json = json_encode( $arr, JSON_NUMERIC_CHECK);

But it just work on PHP 5.3.3. Look at this PHP json_encode change log http://php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog

'Connect-MsolService' is not recognized as the name of a cmdlet

Following worked for me:

  1. Uninstall the previously installed ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’.
  2. Install 64-bit versions of ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’. https://littletalk.wordpress.com/2013/09/23/install-and-configure-the-office-365-powershell-cmdlets/

If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267

  1. Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

https://stackoverflow.com/a/16018733/5810078.

(But I have actually copied all the possible files from

C:\Windows\System32\WindowsPowerShell\v1.0\

to

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

(For copying you need to alter the security permissions of that folder))

How to create a custom string representation for a class object?

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print C

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

401 Unauthorized: Access is denied due to invalid credentials

I had a slightly different problem. The credential problem was for the underlying user running the application, not the user trying to login. One way to test this is to go to IIS Management -> Sites -> Your Site -> Basic Settings -> Test Settings.

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

How do I get a reference to the app delegate in Swift?

As of iOS 12.2 and Swift 5.0, AppDelegate is not a recognized symbol. UIApplicationDelegate is. Any answers referring to AppDelegate are therefore no longer correct. The following answer is correct and avoids force-unwrapping, which some developers consider a code smell:

import UIKit

extension UIViewController {
  var appDelegate: UIApplicationDelegate {
    guard let appDelegate = UIApplication.shared.delegate else {
      fatalError("Could not determine appDelegate.")
    }
    return appDelegate
  }
}

How to round up the result of integer division?

HOW TO ROUND UP THE RESULT OF INTEGER DIVISION IN C#

I was interested to know what the best way is to do this in C# since I need to do this in a loop up to nearly 100k times. Solutions posted by others using Math are ranked high in the answers, but in testing I found them slow. Jarod Elliott proposed a better tactic in checking if mod produces anything.

int result = (int1 / int2);
if (int1 % int2 != 0) { result++; }

I ran this in a loop 1 million times and it took 8ms. Here is the code using Math:

int result = (int)Math.Ceiling((double)int1 / (double)int2);

Which ran at 14ms in my testing, considerably longer.

How to create an empty file at the command line in Windows?

Yet another way:

copy nul 2>empty_file.txt

Something like 'contains any' for Java set?

I would recommend creating a HashMap from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|) time (as there would be no collisions), whereas retainAll(Collection<?> c) must run in O(|A|*|B|) time.

What are the ways to sum matrix elements in MATLAB?

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end

append option to select menu?

Something like this:

var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

how to loop through each row of dataFrame in pyspark

It might not be the best practice, but you can simply target a specific column using collect(), export it as a list of Rows, and loop through the list.

Assume this is your df:

+----------+----------+-------------------+-----------+-----------+------------------+ 
|      Date|  New_Date|      New_Timestamp|date_sub_10|date_add_10|time_diff_from_now|
+----------+----------+-------------------+-----------+-----------+------------------+ 
|2020-09-23|2020-09-23|2020-09-23 00:00:00| 2020-09-13| 2020-10-03| 51148            | 
|2020-09-24|2020-09-24|2020-09-24 00:00:00| 2020-09-14| 2020-10-04| -35252           |
|2020-01-25|2020-01-25|2020-01-25 00:00:00| 2020-01-15| 2020-02-04| 20963548         |
|2020-01-11|2020-01-11|2020-01-11 00:00:00| 2020-01-01| 2020-01-21| 22173148         |
+----------+----------+-------------------+-----------+-----------+------------------+

to loop through rows in Date column:

rows = df3.select('Date').collect()

final_list = []
for i in rows:
    final_list.append(i[0])

print(final_list)

Html table tr inside td

_x000D_
_x000D_
<table border="1px;" width="100%">
  <tr align="center">
    <td>Product</td>
    <td>quantity</td>
    <td>Price</td>
    <td>Totall</td>
  </tr>
  <tr align="center">
    <td>Item-1</td>
    <td>Item-1</td>
    <td>
      <table border="1px;" width="100%">
        <tr align="center">
          <td>Name1</td>
          <td>Price1</td>
        </tr>
        <tr align="center">
          <td>Name2</td>
          <td>Price2</td>
        </tr>
        <tr align="center">
          <td>Name3</td>
          <td>Price3</td>
        </tr>
        <tr>
          <td>Name4</td>
          <td>Price4</td>
        </tr>
      </table>
    </td>
    <td>Item-1</td>
  </tr>
  <tr align="center">
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
  </tr>
  <tr align="center">
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

The name 'ViewBag' does not exist in the current context

I had the same problem and crimbo gave me the right clue, it was caused by the ./Views/Web.config file which was present but not containing the right namespaces I guess...

I created a blank MVC5 project and imported its ./Views/Web.config into my existing project and the red waves under every ViewBag use are gone !

Uploading images using Node.js, Express, and Mongoose

It will become easy to store files after converting in string you just have to convert string in image in your frontend

convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder

"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

to delete the file

       let resultHandler = function (err) {
            if (err) {
                console.log("unlink failed", err);
            } else {
                console.log("file deleted");
            }
        }

        fs.unlink(req.file.path, resultHandler);

at your routes import multer

 `multer const multer = require('multer');
  const upload = multer({ dest: __dirname + '/uploads/images' });`
  Add upload.single('img') in your request

  router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]), 
        upload.single('img'), usersController.fellowsdetails);

OR

If you want save images in localstorage and want save path in database you can try following approach

you have to install first the fs-extra which will create folder. I am creating separate folders by id's if you want to remove it you can remove it. and to save path of image where it is uploaded add this code in your api or controller you are using to save image and and add it in database with other data

    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;

create separate folder for multer like multerHelper.js

 const multer = require('multer');
 let fs = require('fs-extra');

 let storage = multer.diskStorage({
 destination: function (req, file, cb) {
    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;
    fs.mkdirsSync(path);
    cb(null, path);
 },
 filename: function (req, file, cb) {
    // console.log(file);

  let extArray = file.mimetype.split("/");
  let extension = extArray[extArray.length - 1];
  cb(null, file.fieldname + '-' + Date.now() + "." + extension);
 }
})

let upload = multer({ storage: storage });

let createUserImage = upload.array('images', 100);

let multerHelper = {
     createUserImage,
}

   module.exports = multerHelper;

In your routes import multerhelper file

   const multerHelper = require("../helpers/multer_helper");

   router.post(multerHelper. createUserImage , function(req, res, next) {
      //Here accessing the body datas.
    })

Generic List - moving an item within the list

Insert the item currently at oldIndex to be at newIndex and then remove the original instance.

list.Insert(newIndex, list[oldIndex]);
if (newIndex <= oldIndex) ++oldIndex;
list.RemoveAt(oldIndex);

You have to take into account that the index of the item you want to remove may change due to the insertion.

Mutex example / tutorial?

I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).

I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).

Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    // these vars are shared among the following threads
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(5));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );


    std::thread thrProducer(
        [&]()
        {
            using namespace std;

            int nNum = 13;
            unique_lock<mutex> lock( mtxQuit );

            while ( ! m_bQuit )
            {
                while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
                {
                    nNum = nNum + 13 / 2;

                    unique_lock<mutex> qLock(mtxQueue);
                    cout << "Produced: " << nNum << "\n";
                    nNumbers.push( nNum );
                }
            }
        }   
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;
            unique_lock<mutex> lock(mtxQuit);

            while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

Read response body in JAX-RS client from a post request

I also had the same issue, trying to run a unit test calling code that uses readEntity. Can't use getEntity in production code because that just returns a ByteInputStream and not the content of the body and there is no way I am adding production code that is hit only in unit tests.

My solution was to create a response and then use a Mockito spy to mock out the readEntity method:

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

Note that you can't use the when(mockResponse.readEntity(String.class) option because that throws the same IllegalStateException.

Hope this helps!

How do I add a newline to a windows-forms TextBox?

TextBox2.Text = "Line 1" & Environment.NewLine & "Line 2"

or

TextBox2.Text = "Line 1"
TextBox2.Text += Environment.NewLine
TextBox2.Text += "Line 2"

This, is how it is done.

How to get query params from url in Angular 2?

My old school solution:

queryParams(): Map<String, String> {
  var pairs = location.search.replace("?", "").split("&")
  var params = new Map<String, String>()
  pairs.map(x => {
    var pair = x.split("=")
    if (pair.length == 2) {
      params.set(pair[0], pair[1])
    }
  })

  return params
}

How to avoid "Permission denied" when using pip with virtualenv

If you created virtual environment using root then use this command

sudo su

it will give you the root access and then activate your virtual environment using this

source /root/.env/ENV_NAME/bin/activate

Add to integers in a list

Yes, it is possible since lists are mutable.

Look at the built-in enumerate() function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).

How to hide the soft keyboard from inside a fragment?

Use this code in any fragment button listener:

InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

Get a list of dates between two dates

You can use MySQL's user variables like this:

SET @num = -1;
SELECT DATE_ADD( '2009-01-01', interval @num := @num+1 day) AS date_sequence, 
your_table.* FROM your_table
WHERE your_table.other_column IS NOT NULL
HAVING DATE_ADD('2009-01-01', interval @num day) <= '2009-01-13'

@num is -1 because you add to it the first time you use it. Also, you can't use "HAVING date_sequence" because that makes the user variable increment twice for each row.

How to write to a JSON file in the correct format

With formatting

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output

{
    "key_a":"val_a",
    "key_b":"val_b"
}

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

You get this warning message when the servlet api jar file has already been loaded in the container and you try to load it once again from lib directory.

The Servlet specs say you are not allowed to have servlet.jar in your webapps lib directory.

  • Get rid of the warning message by simply removing servlet.jar from your lib directory.
  • If you don't find the jar in the lib directory scan for your build path and remove the jar.

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\project\WEB-INF\lib

If you are running a maven project, change the javax.servlet-api dependency to scope provided in you pom.xml since the container already provided the servlet jar in itself.

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This question keeps coming up and I did not find a satisfying result yet, so here is what worked for me (based on a previous answer https://stackoverflow.com/a/52706362/1806760, which is not working):

My server is https://gitlab.dev with a self-signed certificate.

First run git config --system --edit (from an elevated command prompt, change --system to --global if you want to do it for just your user), then insert the following snippet after any previous [http] sections:

[http "https://gitlab.dev"]
        sslVerify = false

Then check if you did everything correctly:

> git config --type=bool --get-urlmatch http.sslVerify https://gitlab.dev
false

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Resize image in the wiki of GitHub using Markdown

This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?


In December 2015, it seems that only links to files on github.com or cloud.githubusercontent.com or the like work. Steps that worked for me in a gist:

  1. Make a gist, say Mygist.md (and optionally more files)
  2. Go to the "Write Comment" box at the end
  3. Click "Attach files ... by selecting them"; select your local image file
  4. GitHub echos a long long string where it put the image, e.g. ![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
  5. Cut-paste that by hand into your Mygist.md.

But: GitHub people may change this behavior tomorrow, without documenting it.

Laravel - Return json along with http status code

It's better to do it with helper functions rather than Facades. This solution will work well from Laravel 5.7 onwards

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

How to run a stored procedure in oracle sql developer?

-- If no parameters need to be passed to a procedure, simply:

BEGIN
   MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

What is Vim recording and how can it be disabled?

It sounds like you have macro recording turned on. To shut it off, press q.

Refer to ":help recording" for further information.

Related links:

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

How to create permanent PowerShell Aliases

It's not a good idea to add this kind of thing directly to your $env:WINDIR powershell folders.
The recommended way is to add it to your personal profile:

cd $env:USERPROFILE\Documents
md WindowsPowerShell -ErrorAction SilentlyContinue
cd WindowsPowerShell
New-Item Microsoft.PowerShell_profile.ps1 -ItemType "file" -ErrorAction SilentlyContinue
powershell_ise.exe .\Microsoft.PowerShell_profile.ps1

Now add your alias to the Microsoft.PowerShell_profile.ps1 file that is now opened:

function Do-ActualThing {
    # do actual thing
}

Set-Alias MyAlias Do-ActualThing

Then save it, and refresh the current session with:

. $profile

Note: Just in case, if you get permission issue like

CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess

Try the below command and refresh the session again.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

batch to copy files with xcopy

After testing most of the switches this worked for me:

xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y

This will copy the folder folder1 into the folder folder2. So the directory tree would look like:

C:
   Folder1
   Folder2
      Folder1

How to detect scroll position of page using jQuery

Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.

//jQuery

jQuery(document).ready(function () {

    $(window).scrollTop($("#<%=hidScroll.ClientID %>").val());

    $(window).scroll(function (event) {
        $("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
    });
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function () {

    $(window).scrollTop($("#<%=hidScroll.ClientID %>").val());

    $(window).scroll(function (event) {
        $("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
    });
});

//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.x, on_delete is required.

Django Documentation

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

Maven: Failed to retrieve plugin descriptor error

I had the same error. In my case I am using Netbeans 7.1.2, I am posting this because maybe someone end up here same as I did.

I tried to configure the proxy options from the GUI, but the documentation says that maven doesn't read those. So I checked the NetBeans FAQ here :

What mainly you have to do is create (if it does not exist) a settings.xml under

user.home/.m2/settings.xml

if you don't have it you can copy from

netbeans.home/java/maven/conf/settings.xml

then uncomment if you already have it otherwise just fill this section:

<proxies>
 <proxy>
   <active>true</active>
   <host>myproxy.host.net</host>
   <port>80</port>
 </proxy>
</proxies>

you have to check your proxy configuration and replace it there

Onclick on bootstrap button

<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>

$('#fire').on('click', function (e) {

     //your awesome code here

})

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Centering floating divs within another div

The following solution does not use inline blocks. However, it requires two helper divs:

  1. The content is floated
  2. The inner helper is floated (it stretches as much as the content)
  3. The inner helper is pushed right 50% (its left aligns with center of outer helper)
  4. The content is pulled left 50% (its center aligns with left of inner helper)
  5. The outer helper is set to hide the overflow

_x000D_
_x000D_
.ca-outer {_x000D_
  overflow: hidden;_x000D_
  background: #FFC;_x000D_
}_x000D_
.ca-inner {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: 50%;_x000D_
  background: #FDD;_x000D_
}_x000D_
.content {_x000D_
  float: left;_x000D_
  position: relative;_x000D_
  left: -50%;_x000D_
  background: #080;_x000D_
}_x000D_
/* examples */_x000D_
div.content > div {_x000D_
  float: left;_x000D_
  margin: 10px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #FFF;_x000D_
}_x000D_
ul.content {_x000D_
  padding: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
ul.content > li {_x000D_
  margin: 10px;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <div class="content">_x000D_
      <div>Box 1</div>_x000D_
      <div>Box 2</div>_x000D_
      <div>Box 3</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<hr>_x000D_
<div class="ca-outer">_x000D_
  <div class="ca-inner">_x000D_
    <ul class="content">_x000D_
      <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>_x000D_
      <li>Nullam efficitur nulla in libero consectetur dictum ac a sem.</li>_x000D_
      <li>Suspendisse iaculis risus ut dapibus cursus.</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

python ignore certificate validation urllib2

urllib2 does not verify server certificate by default. Check this documentation.

Edit: As pointed out in below comment, this is not true anymore for newer versions (seems like >= 2.7.9) of Python. Refer the below ANSWER

More than one file was found with OS independent path 'META-INF/LICENSE'

I had same error and i solved this error using this

Solution and Code

Add this package options in the app’s build.gradle

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
   
}

Android Firebase, simply get one child object's data

I store my data this way:

accountsTable ->
  key1 -> account1
  key2 -> account2

in order to get object data:

accountsDb = mDatabase.child("accountsTable");

accountsDb.child("some   key").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {

                    try{

                        Account account  = snapshot.getChildren().iterator().next()
                                  .getValue(Account.class);


                    } catch (Throwable e) {
                        MyLogger.error(this, "onCreate eror", e);
                    }
                }
                @Override public void onCancelled(DatabaseError error) { }
            });

Passing parameters to addTarget:action:forControlEvents

There is another one way, in which you can get indexPath of the cell where your button was pressed:

using usual action selector like:

 UIButton *btn = ....;
    [btn addTarget:self action:@selector(yourFunction:) forControlEvents:UIControlEventTouchUpInside];

and then in in yourFunction:

   - (void) yourFunction:(id)sender {

    UIButton *button = sender;
    CGPoint center = button.center;
    CGPoint rootViewPoint = [button.superview convertPoint:center toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:rootViewPoint];
    //the rest of your code goes here
    ..
}

since you get an indexPath it becames much simplier.

CSS div element - how to show horizontal scroll bars only?

This solution is without height/width specification for the father div so it will be responsive to window resizing and most useful cause horizontal scrollbars appears just if needed.

.container{
    padding:20px;
    border:dotted 1px;
    white-space:nowrap;
    overflow-x:auto;
}

.box{
    width:100px;
    height:180px;
    background-color: red;
    margin:10px;
    display:inline-block
}

Take a look at DEMO

How to create text file and insert data to that file on Android

Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.

An example from the android documentation:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

How to get the device's IMEI/ESN programmatically in android?

for API Level 11 or above:

case TelephonyManager.PHONE_TYPE_SIP: 
return "SIP";

TelephonyManager tm= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(tm));

How do I remove blank elements from an array?

Shortest way cities.select(&:present?)

Regular expression for first and last name

After going through all of these answers I found a way to build a tiny regex that supports most languages and only allows for word characters. It even supports some special characters like hyphens, spaces and apostrophes. I've tested in python and it supports the characters below:

^[\w'\-,.][^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]]{2,}$

Characters supported:

abcdefghijklmnopqrstwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
áéíóúäëïöüÄ'
???
lLoOuUZàáâäãåacceèéêëeiìíîïlnòóôöõøùúûüuu
ÿýzzñçcšžÀÁÂÄÃÅACCEEÈÉÊËÌÍÎÏIL
NÒÓÔÖÕØÙÚÛÜUUŸÝZZÑßÇŒÆCŠŽ.-
ñÑâê?????????????
????????? ?????? ??

After MySQL install via Brew, I get the error - The server quit without updating PID file

I had the similar issue. But the following commands saved me.

cd /usr/local/Cellar
sudo chown _mysql mysql

Efficient way to apply multiple filters to pandas DataFrame or Series

Why not do this?

def filt_spec(df, col, val, op):
    import operator
    ops = {'eq': operator.eq, 'neq': operator.ne, 'gt': operator.gt, 'ge': operator.ge, 'lt': operator.lt, 'le': operator.le}
    return df[ops[op](df[col], val)]
pandas.DataFrame.filt_spec = filt_spec

Demo:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b':[5,4,3,2,1]})
df.filt_spec('a', 2, 'ge')

Result:

   a  b
 1  2  4
 2  3  3
 3  4  2
 4  5  1

You can see that column 'a' has been filtered where a >=2.

This is slightly faster (typing time, not performance) than operator chaining. You could of course put the import at the top of the file.

How to update specific key's value in an associative array in PHP?

PHP array_walk() function is specifically for altering array.

Try this:

array_walk ( $data, function (&$key) { 
    $key["transaction_date"] = date('d/m/Y',$key["transaction_date"]); 
});

HAProxy redirecting http to https (ssl)

A slight variation of user2966600's solution...

To redirect all except a single URL (In case of multiple frontend/backend):

redirect scheme https if !{ hdr(Host) -i www.mydomain.com } !{ ssl_fc }

How to scroll page in flutter

Two way to add Scroll in page

1. Using SingleChildScrollView :

     SingleChildScrollView(
          child: Column(
            children: [
              Container(....),
              SizedBox(...),
              Container(...),
              Text(....)
            ],
          ),
      ),

2. Using ListView : ListView is default provide Scroll no need to add extra widget for scrolling

     ListView(
          children: [
            Container(..),
            SizedBox(..),
            Container(...),
            Text(..)
          ],
      ),

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

How to remove part of a string?

If you're specifically targetting "11223344", then use str_replace:

// str_replace($search, $replace, $subject)
echo str_replace("11223344", "","REGISTER 11223344 here");

Why is the GETDATE() an invalid identifier

SYSDATE and GETDATE perform identically.

SYSDATE is compatible with Oracle syntax, and GETDATE is compatible with Microsoft SQL Server syntax.

What is the difference between String.slice and String.substring?

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.

Here is his article about this.

Creating an array from a text file in Bash

This answer says to use

mapfile -t myArray < file.txt

I made a shim for mapfile if you want to use mapfile on bash < 4.x for whatever reason. It uses the existing mapfile command if you are on bash >= 4.x

Currently, only options -d and -t work. But that should be enough for that command above. I've only tested on macOS. On macOS Sierra 10.12.6, the system bash is 3.2.57(1)-release. So the shim can come in handy. You can also just update your bash with homebrew, build bash yourself, etc.

It uses this technique to set variables up one call stack.

Embed HTML5 YouTube video without iframe?

Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.

If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.

Hope this helps!


Useful:

(https://developers.google.com/youtube/player_parameters)

IFrame embeds using the IFrame Player API

Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

...

IFrame embeds using tags

Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.

If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:

...

AS3 object embeds

Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

How to set the font size in Emacs?

From Emacswiki, GNU Emacs 23 has a built-in key combination:

C-xC-+ and C-xC-- to increase or decrease the buffer text size

Sort a list of tuples by 2nd item (integer value)

As a python neophyte, I just wanted to mention that if the data did actually look like this:

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical.

jQuery convert line breaks to br (nl2br equivalent)

Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Android sqlite how to check if a record exists

because of possible data leaks best solution via cursor:

 Cursor cursor = null;
    try {
          cursor =  .... some query (raw or not your choice)
          return cursor.moveToNext();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

1) From API KITKAT u can use resources try()

try (cursor = ...some query)

2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'

3) dont use moveToFirst() is used when you need to start iterating from beggining

4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

Check if a file is executable

Also seems nobody noticed -x operator on symlinks. A symlink (chain) to a regular file (not classified as executable) fails the test.

java.util.Date and getYear()

Don't use Date, use Calendar:

// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR);  // 2012
int month = date.get(Calendar.MONTH);  // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH);  // 5

It supports time as well:

Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY);  // 15
int minute = dateTime.get(Calendar.MINUTE);  // 16
int second = dateTime.get(Calendar.SECOND);  // 17

Catching multiple exception types in one catch block

As an extension to the accepted answer, you could switch the type of Exception resulting in a pattern that is somewhat like the original example:

try {

    // Try something

} catch (Exception $e) {

    switch (get_class($e)) {

        case 'AError':
        case 'BError':
            // Handle A or B
            break;

        case 'CError':
            // Handle C
            break;

        case default:
            // Rethrow the Exception
            throw $e;

    }

}

How to manually set REFERER header in Javascript?

If you want to change the referer (url) header that will be sent to the server when a user clicks an anchor or iframe is opened, you can do it without any hacks. Simply do history.replaceState, you will change the url as it will appear in the browser bar and also the referer that will be send to the server.

Normalizing a list of numbers in Python

There isn't any function in the standard library (to my knowledge) that will do it, but there are absolutely modules out there which have such functions. However, its easy enough that you can just write your own function:

def normalize(lst):
    s = sum(lst)
    return map(lambda x: float(x)/s, lst)

Sample output:

>>> normed = normalize(raw)
>>> normed
[0.25, 0.5, 0.25]

How does C compute sin() and other math functions?

Functions like sine and cosine are implemented in microcode inside microprocessors. Intel chips, for example, have assembly instructions for these. A C compiler will generate code that calls these assembly instructions. (By contrast, a Java compiler will not. Java evaluates trig functions in software rather than hardware, and so it runs much slower.)

Chips do not use Taylor series to compute trig functions, at least not entirely. First of all they use CORDIC, but they may also use a short Taylor series to polish up the result of CORDIC or for special cases such as computing sine with high relative accuracy for very small angles. For more explanation, see this StackOverflow answer.

Error: Argument is not a function, got undefined

This seriously took me 4 HOURS (including endless searches on SO) but finally I found it: by mistake (unintentionally) I added a space somewhere.

Can you spot it?

angular.module('bwshopper.signup').controller('SignupCtrl ', SignupCtrl);

So ... 4 hours later I saw that it should be:

angular.module('bwshopper.signup').controller('SignupCtrl', SignupCtrl);

Almost impossible to see with just the naked eye.

This stresses the vital importance of revision control (git or whatever) and unit/regression testing.

Purpose of ESI & EDI registers?

Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,

mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Java Strings: "String s = new String("silly");"

You can't. Things in double-quotes in Java are specially recognised by the compiler as Strings, and unfortunately you can't override this (or extend java.lang.String - it's declared final).

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

Adding class to element using Angular JS

try this code

<script>
       angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>

click the link and understand more

Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()

Sort objects in an array alphabetically on one property of the array

To support unicode:

objArray.sort(function(a, b) {
   return a.DepartmentName.localeCompare(b.DepartmentName);
});

pySerial write() won't take my string

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))

What is the best way to add options to a select from a JavaScript object with jQuery?

Using the $.map() function, you can do this in a more elegant way:

$('#mySelect').html( $.map(selectValues, function(val, key){
    return '<option value="' + val + '">'+ key + '</option>';
}).join(''));

How to make a div with no content have a width?

Use min-height: 1px; Everything has at least min-height of 1px so no extra space is taken up with nbsp or padding, or being forced to know the height first.

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

center MessageBox in parent form

Surely using your own panel or form would be by far the simplest approach if a little more heavy on the background (designer) code. It gives all the control in terms of centring and manipulation without writing all that custom code.

What's the difference between JavaScript and JScript?

There are some code differences to be aware of.

A negative first parameter to subtr is not supported, e.g. in Javascript: "string".substr(-1) returns "g", whereas in JScript: "string".substr(-1) returns "string"

It's possible to do "string"[0] to get "s" in Javascript, but JScript doesn't support such a construct. (Actually, only modern browsers appear to support the "string"[0] construct.

hadoop copy a local file system folder to HDFS

Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:

To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"

eg)./hadoop fs -put /opt/csv/load.csv /user/load

Here the /opt/csv/load.csv is source file path from my local linux system.

/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"

To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"

eg)hadoop fs -get /user/load/a.csv /opt/csv/

After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.

This uploaded files could also be seen through HDFS NameNode web UI.

Is it bad practice to use break to exit a loop in Java?

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.

List only stopped Docker containers

The typical command is:

docker container ls -f 'status=exited'

However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:

  • created
  • restarting
  • running
  • removing
  • paused
  • exited
  • dead

You can filter on multiple statuses by passing multiple filters on the status:

docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'

If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q, and you can also limit to just the containers that exited successfully with an exit code filter:

docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')

For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

C# Change A Button's Background Color

this.button2.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(190)))), ((int)(((byte)(149)))));

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

How do I create and access the global variables in Groovy?

class Globals {
   static String ouch = "I'm global.."
}

println Globals.ouch

Create stacked barplot where each stack is scaled to sum to 100%

prop.table is a nice friendly way of obtaining proportions of tables.

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Leaving margin blank gives you proportions of the whole table

 prop.table(m, margin=NULL)
     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

Giving it 1 gives you row proportions

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667

And 2 is column proportions

 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286

How to create a property for a List<T>

Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.

public class MyClass<T>
{
  etc

Form Submission without page refresh

<script type="text/javascript">
    var frm = $('#myform');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });

        ev.preventDefault();
    });
</script>

<form id="myform" action="/your_url" method="post">
    ...
</form>

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

How to hide action bar before activity is created, and then show it again?

Put your splash screen in a separate activity and use startActivityForResult from your main activity's onCreate method to display it. This works because, according to the docs:

As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.

You should probably do this only if the argument to onCreate is null (indicating a fresh launch of your activity, as opposed to a restart due to a configuration change).

How to add a class to body tag?

I had the same problem,

<body id="body">

Add an ID tag to the body:

$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.

Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.

Xcode 6: Keyboard does not show up in simulator

I had the same issue. My solution was as follows:

  1. iOS Simulator -> Hardware -> Keyboard
  2. Uncheck "Connect Hardware Keyboard"

Mine was checked because I was using my mac keyboard, but if you make sure it is unchecked the iPhone keyboard will always come up.

How can I set a css border on one side only?

#testDiv{
    /* set green border independently on each side */
    border-left: solid green 2px;
    border-right: solid green 2px;
    border-bottom: solid green 2px;
    border-top: solid green 2px;
}

How to Find And Replace Text In A File With C#

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

Test file upload using HTTP PUT method

curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

Use 'import module' or 'from module import'?

since many people answered here but i am just trying my best :)

  1. import module is best when you don't know which item you have to import from module. In this way it may be difficult to debug when problem raises because you don't know which item have problem.

  2. form module import <foo> is best when you know which item you require to import and also helpful in more controlling using importing specific item according to your need. Using this way debugging may be easy because you know which item you imported.

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

This is the hardware serial number. To access it on

  • Android Q (>= SDK 29) android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE is required. Only system apps can require this permission. If the calling package is the device or profile owner then the READ_PHONE_STATE permission suffices.

  • Android 8 and later (>= SDK 26) use android.os.Build.getSerial() which requires the dangerous permission READ_PHONE_STATE. Using android.os.Build.SERIAL returns android.os.Build.UNKNOWN.

  • Android 7.1 and earlier (<= SDK 25) and earlier android.os.Build.SERIAL does return a valid serial.

It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read here.

For a solution involving reflection without requiring a permission see this answer.

JSON.stringify output to div in pretty print way

My proposal is based on:

  • replace each '\n' (newline) with a <br>
  • replace each space with &nbsp;

_x000D_
_x000D_
var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };_x000D_
_x000D_
_x000D_
document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)_x000D_
     .replace(/\n( *)/g, function (match, p1) {_x000D_
         return '<br>' + '&nbsp;'.repeat(p1.length);_x000D_
     });
_x000D_
<div id="newquote"></div>
_x000D_
_x000D_
_x000D_

How can I brew link a specific version?

If you have installed, for example, php 5.4 it could be switched in the following way to php 5.5:

$ php --version
PHP 5.4.32 (cli) (built: Aug 26 2014 15:14:01) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

$ brew unlink php54

$ brew switch php55 5.5.16

$ php --version
PHP 5.5.16 (cli) (built: Sep  9 2014 14:27:18) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

CSS: create white glow around image

late to the party here; however just wanted to add a bit of extra fun..

box-shadow: 0px 0px 5px rgba(0,0,0,.3);
padding:7px;

will give you a nice looking padded in image. The padding will give you a simulated white border (or whatever border you have set). the rgba is just allowing you to do an opicity on the particular color; 0,0,0 being black. You could just as easily use any other RGB color.

Hope this helps someone!

What is the purpose of flush() in Java streams?

If the buffer is full, all strings that is buffered on it, they will be saved onto the disk. Buffers is used for avoiding from Big Deals! and overhead.

In BufferedWriter class that is placed in java libs, there is a one line like:

private static int defaultCharBufferSize = 8192;

If you do want to send data before the buffer is full, you do have control. Just Flush It. Calls to writer.flush() say, "send whatever's in the buffer, now!

reference book: https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

pages:453

How do I put a clear button inside my HTML text input box like the iPhone does?

@Mahmoud Ali Kaseem

I have just changed some CSS to make it look different and added focus();

https://jsfiddle.net/xn9eogmx/81/

_x000D_
_x000D_
$('#clear').click(function() {_x000D_
  $('#input-outer input').val('');_x000D_
  $('#input-outer input').focus();_x000D_
});
_x000D_
body {_x000D_
  font-family: "Arial";_x000D_
  font-size: 14px;_x000D_
}_x000D_
#input-outer {_x000D_
  height: 2em;_x000D_
  width: 15em;_x000D_
  border: 1px #777 solid;_x000D_
  position: relative;_x000D_
  padding: 0px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#input-outer input {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: 0px;_x000D_
  outline: none;_x000D_
  margin: 0 0 0 0px;_x000D_
  color: #666;_x000D_
  box-sizing: border-box;_x000D_
  padding: 5px;_x000D_
  padding-right: 35px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
#clear {_x000D_
  position: absolute;_x000D_
  float: right;_x000D_
  height: 2em;_x000D_
  width: 2em;_x000D_
  top: 0px;_x000D_
  right: 0px;_x000D_
  background: #aaa;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
  cursor: pointer;_x000D_
  border-radius: 0px 4px 4px 0px;_x000D_
}_x000D_
#clear:after {_x000D_
  content: "\274c";_x000D_
  position: absolute;_x000D_
  top: 4px;_x000D_
  right: 7px;_x000D_
}_x000D_
#clear:hover,_x000D_
#clear:focus {_x000D_
  background: #888;_x000D_
}_x000D_
#clear:active {_x000D_
  background: #666;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="input-outer">_x000D_
  <input type="text">_x000D_
  <div id="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can not change UILabel text color

UIColor's RGB components are scaled between 0 and 1, not up to 255.

Try

categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];

In Swift:

categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)

How do you remove an invalid remote branch reference from Git?

git gc --prune=now is not what you want.

git remote prune public

or git remote prune origin # if thats the the remote source

is what you want

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How to set my default shell on Mac?

You can use chsh to change a user's shell.

Run the following code, for instance, to change your shell to Zsh

chsh -s /bin/zsh

As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells.

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

How to take input in an array + PYTHON?

data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
    x = raw_input('Enter the numbers into the array: ')
    data.append(x)
print(data)

Now this doesn't do any error checking and it stores data as a string.

Is there a difference between "==" and "is"?

There is a simple rule of thumb to tell you when to use == or is.

  • == is for value equality. Use it when you would like to know if two objects have the same value.
  • is is for reference equality. Use it when you would like to know if two references refer to the same object.

In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use ==. For example, the intention of your example is probably to check whether x has a value equal to 2 (==), not whether x is literally referring to the same object as 2.


Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use is to compare for reference equality on integers:

>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False

That's pretty much what we expected: a and b have the same value, but are distinct entities. But what about this?

>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True

This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:

>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
... 
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False

This is another obvious reason not to use is: the behavior is left up to implementations when you're erroneously using it for value equality.

cut or awk command to print first field of first row

Specify NR if you want to capture output from selected rows:

awk 'NR==1{print $1}' /etc/*release

An alternative (ugly) way of achieving the same would be:

awk '{print $1; exit}'

An efficient way of getting the first string from a specific line, say line 42, in the output would be:

awk 'NR==42{print $1; exit}'

How to execute a shell script from C in Linux?

If you're ok with POSIX, you can also use popen()/pclose()

#include <stdio.h>
#include <stdlib.h>

int main(void) {
/* ls -al | grep '^d' */
  FILE *pp;
  pp = popen("ls -al", "r");
  if (pp != NULL) {
    while (1) {
      char *line;
      char buf[1000];
      line = fgets(buf, sizeof buf, pp);
      if (line == NULL) break;
      if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
    }
    pclose(pp);
  }
  return 0;
}

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had the same problem in my grails project. The Bug was, that i overwrite the getter method of a collection field. This returned always a new version of the collection in other thread.

class Entity {
    List collection

    List getCollection() {
        return collection.unique()
    }
}

The solution was to rename the getter method:

class Entity {
    List collection

    List getUniqueCollection() {
        return collection.unique()
    }
}

Cannot read property 'push' of undefined when combining arrays

order[] is undefined that's why

Just define order[1]...[n] to = some value

this should fix it

Firefox "ssl_error_no_cypher_overlap" error

Under advanced settings of firefox you should be able to set the encryption. By default SSL3.0 and TLS1.0 should be checked, so if firefox is trying to create ssl 3.0 connectons try unchecking the ssl 3.0s setting.

if that doesn't work, try searching the about:config page for "ssl2" My Firefox has settings with ssl2 set to false by default...

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Add a auto increment primary key to existing table in oracle

Say your table is called t1 and your primary-key is called id
First, create the sequence:

create sequence t1_seq start with 1 increment by 1 nomaxvalue; 

Then create a trigger that increments upon insert:

create trigger t1_trigger
before insert on t1
for each row
   begin
     select t1_seq.nextval into :new.id from dual;
   end;

Firing a Keyboard Event in Safari, using JavaScript

I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:

element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })

var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);

//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})

UPDATE:

Now my polyfill supports legacy properties "keyCode", "charCode" and "which"

var e = new KeyboardEvent("keydown", {
    bubbles : true,
    cancelable : true,
    char : "Q",
    key : "q",
    shiftKey : true,
    keyCode : 81
});

Examples here

Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)

Polyfill demo

How do I consume the JSON POST data in an Express application

_x000D_
_x000D_
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
_x000D_
_x000D_

This app.use(express.json) will now let you read the incoming post JSON object

Correct way to initialize empty slice

They are equivalent. See this code:

mySlice1 := make([]int, 0)
mySlice2 := []int{}
fmt.Println("mySlice1", cap(mySlice1))
fmt.Println("mySlice2", cap(mySlice2))

Output:

mySlice1 0
mySlice2 0

Both slices have 0 capacity which implies both slices have 0 length (cannot be greater than the capacity) which implies both slices have no elements. This means the 2 slices are identical in every aspect.

See similar questions:

What is the point of having nil slice and empty slice in golang?

nil slices vs non-nil slices vs empty slices in Go language

Let JSON object accept bytes or let urlopen output strings

As of Python 3.6, you can use json.loads() to deserialize a bytesobject directly (the encoding must be UTF-8, UTF-16 or UTF-32). So, using only modules from the standard library, you can do:

import json
from urllib import request

response = request.urlopen(url).read()
data = json.loads(response)

Position Relative vs Absolute?

Position Relative:

If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.

Position Absolute:

When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.

Here is a good tutorial http://www.barelyfitz.com/screencast/html-training/css/positioning/ with the sample usage of both position with respective to absolute and relative positioning.

How long will my session last?

You're searching for gc_maxlifetime, see http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime for a description.

Your session will last 1440 seconds which is 24 minutes (default).

Simple PHP form: Attachment to email (code golf)

PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.

You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.

Difference between final and effectively final

'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'

From a article by 'Brian Goetz',

Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.

lambda-state-final- Brian Goetz

How do you delete a column by name in data.table?

Here is a way when you want to set a # of columns to NULL given their column names a function for your usage :)

deleteColsFromDataTable <- function (train, toDeleteColNames) {

       for (myNm in toDeleteColNames)

       train <- train [,(myNm):=NULL]

       return (train)
}

JavaScript property access: dot notation vs. brackets?

An example where the dot notation fails

json = { 
   "value:":4,
   'help"':2,
   "hello'":32,
   "data+":2,
   "":'',
   "a[]":[ 
      2,
      2
   ]
};

// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);

// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);

The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.

The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter

1) reset

reset Resets the namespace by removing all names defined by the user, if called without arguments.

in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.

reset in out

Another interesting one is array that only removes numpy Arrays:

reset array

2) reset_selective

Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.

Clean Array Example:

In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']

Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

I think it may be a bug in chrome. There was a similar issue long back: See this.

Try in a different browser. I think it should work fine.

MongoDB query with an 'or' condition

Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

Add number of days to a date

Use the following code.

<?php echo date('Y-m-d', strtotime(' + 5 days')); ?>

Reference has found from here - How to Add Days to Current Date in PHP

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

Failed to Connect to MySQL at localhost:3306 with user root

Steps:

1 - Right click on your task bar -->Start Task Manager

2 - Click on Services button (at bottom).

3 - Search for MYSQL57

4 - Right Click on MYSQL57 --> Start

Now again start your mysql-cmd-prompt or MYSQL WorkBench

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

TypeError: 'list' object is not callable in python

You may have used built-in name 'list' for a variable in your code. If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal. In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.

Used Built-in list name for my list

Change my list name to my_list but still get error, Shift+Tab shows that list still hold the values of my_list

Restart Kernal and it's all good

Microsoft.ACE.OLEDB.12.0 is not registered

You have probably installed the 32bit drivers will the job is running in 64bit. More info: http://microsoft-ssis.blogspot.com/2014/02/connecting-to-excel-xlsx-in-ssis.html

jQuery UI Dialog Box - does not open after being closed

.close() is mor general and can be used in reference to more objects. .dialog('close') can only be used with dialogs

How to undo "git commit --amend" done instead of "git commit"

You can do below to undo your git commit —amend

  1. git reset --soft HEAD^
  2. git checkout files_from_old_commit_on_branch
  3. git pull origin your_branch_name

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

Now your changes are as per previous. So you are done with the undo for git commit —amend

Now you can do git push origin <your_branch_name>, to push to the branch.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

How can I delete a query string parameter in JavaScript?

This is a clean version remove query parameter with the URL class for today browsers:

function removeUrlParameter(url, paramKey)
{
  var r = new URL(url);
  r.searchParams.delete(paramKey);
  return r.href;
}

URLSearchParams not supported on old browsers

https://caniuse.com/#feat=urlsearchparams

IE, Edge (below 17) and Safari (below 10.3) do not support URLSearchParams inside URL class.

Polyfills

URLSearchParams only polyfill

https://github.com/WebReflection/url-search-params

Complete Polyfill URL and URLSearchParams to match last WHATWG specifications

https://github.com/lifaon74/url-polyfill

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

Selecting last element in JavaScript array

This worked:

array.reverse()[0]

C# naming convention for constants?

In its article Constants (C# Programming Guide), Microsoft gives the following example:

class Calendar3
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

So, for constants, it appears that Microsoft is recommending the use of camelCasing. But note that these constants are defined locally.

Arguably, the naming of externally-visible constants is of greater interest. In practice, Microsoft documents its public constants in the .NET class library as fields. Here are some examples:

The first two are examples of PascalCasing. The third appears to follow Microsoft's Capitalization Conventions for a two-letter acronym (although pi is not an acryonym). And the fourth one seems to suggest that the rule for a two-letter acryonym extends to a single letter acronym or identifier such as E (which represents the mathematical constant e).

Furthermore, in its Capitalization Conventions document, Microsoft very directly states that field identifiers should be named via PascalCasing and gives the following examples for MessageQueue.InfiniteTimeout and UInt32.Min:

public class MessageQueue
{
    public static readonly TimeSpan InfiniteTimeout;
}

public struct UInt32
{
    public const Min = 0;
}

Conclusion: Use PascalCasing for public constants (which are documented as const or static readonly fields).

Finally, as far as I know, Microsoft does not advocate specific naming or capitalization conventions for private identifiers as shown in the examples presented in the question.

Origin <origin> is not allowed by Access-Control-Allow-Origin

I was facing a problem while calling cross origin resource using ajax from chrome.

I have used node js and local http server to deploy my node js app.

I was getting error response, when I access cross origin resource

I found one solution on that ,

1) I have added below code to my app.js file

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

2) In my html page called cross origin resource using $.getJSON();

$.getJSON("http://localhost:3000/users", function (data) {
    alert("*******Success*********");
    var response=JSON.stringify(data);
    alert("success="+response);
    document.getElementById("employeeDetails").value=response;
});

How do I use su to execute the rest of the bash script as that user?

It's not possible to change user within a shell script. Workarounds using sudo described in other answers are probably your best bet.

If you're mad enough to run perl scripts as root, you can do this with the $< $( $> $) variables which hold real/effective uid/gid, e.g.:

#!/usr/bin/perl -w
$user = shift;
if (!$<) {
    $> = getpwnam $user;
    $) = getgrnam $user;
} else {
    die 'must be root to change uid';
}
system('whoami');

How to make scipy.interpolate give an extrapolated result beyond the input range?

The below code gives you the simple extrapolation module. k is the value to which the data set y has to be extrapolated based on the data set x. The numpy module is required.

 def extrapol(k,x,y):
        xm=np.mean(x);
        ym=np.mean(y);
        sumnr=0;
        sumdr=0;
        length=len(x);
        for i in range(0,length):
            sumnr=sumnr+((x[i]-xm)*(y[i]-ym));
            sumdr=sumdr+((x[i]-xm)*(x[i]-xm));

        m=sumnr/sumdr;
        c=ym-(m*xm);
        return((m*k)+c)

jQuery Scroll To bottom of the page

You can try this

var scroll=$('#scroll');
scroll.animate({scrollTop: scroll.prop("scrollHeight")});

how to fetch array keys with jQuery?

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

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

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

Which method performs better: .Any() vs .Count() > 0?

If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().

Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

Auto highlight text in a textbox control

I think the easiest way is using TextBox.SelectAll like in an Enter event:

private void TextBox_Enter(object sender, EventArgs e)
{
    ((TextBox)sender).SelectAll();
}

Auto refresh page every 30 seconds

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

<meta http-equiv="refresh" content="30">

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload() (docs) inside a setTimeout():

window.setTimeout(function () {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.

res.sendFile absolute path

I tried this and it worked.

app.get('/', function (req, res) {
    res.sendFile('public/index.html', { root: __dirname });
});

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

LINQ Aggregate algorithm explained

The easiest-to-understand definition of Aggregate is that it performs an operation on each element of the list taking into account the operations that have gone before. That is to say it performs the action on the first and second element and carries the result forward. Then it operates on the previous result and the third element and carries forward. etc.

Example 1. Summing numbers

var nums = new[]{1,2,3,4};
var sum = nums.Aggregate( (a,b) => a + b);
Console.WriteLine(sum); // output: 10 (1+2+3+4)

This adds 1 and 2 to make 3. Then adds 3 (result of previous) and 3 (next element in sequence) to make 6. Then adds 6 and 4 to make 10.

Example 2. create a csv from an array of strings

var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate( (a,b) => a + ',' + b);
Console.WriteLine(csv); // Output a,b,c,d

This works in much the same way. Concatenate a a comma and b to make a,b. Then concatenates a,b with a comma and c to make a,b,c. and so on.

Example 3. Multiplying numbers using a seed

For completeness, there is an overload of Aggregate which takes a seed value.

var multipliers = new []{10,20,30,40};
var multiplied = multipliers.Aggregate(5, (a,b) => a * b);
Console.WriteLine(multiplied); //Output 1200000 ((((5*10)*20)*30)*40)

Much like the above examples, this starts with a value of 5 and multiplies it by the first element of the sequence 10 giving a result of 50. This result is carried forward and multiplied by the next number in the sequence 20 to give a result of 1000. This continues through the remaining 2 element of the sequence.

Live examples: http://rextester.com/ZXZ64749
Docs: http://msdn.microsoft.com/en-us/library/bb548651.aspx


Addendum

Example 2, above, uses string concatenation to create a list of values separated by a comma. This is a simplistic way to explain the use of Aggregate which was the intention of this answer. However, if using this technique to actually create a large amount of comma separated data, it would be more appropriate to use a StringBuilder, and this is entirely compatible with Aggregate using the seeded overload to initiate the StringBuilder.

var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate(new StringBuilder(), (a,b) => {
    if(a.Length>0)
        a.Append(",");
    a.Append(b);
    return a;
});
Console.WriteLine(csv);

Updated example: http://rextester.com/YZCVXV6464

how to put focus on TextBox when the form load?

use form shown event and set

MyTextBox.Focus();

The equivalent of a GOTO in python

Disclaimer: I have been exposed to a significant amount of F77

The modern equivalent of goto (arguable, only my opinion, etc) is explicit exception handling:

Edited to highlight the code reuse better.

Pretend pseudocode in a fake python-like language with goto:

def myfunc1(x)
    if x == 0:
        goto LABEL1
    return 1/x

def myfunc2(z)
    if z == 0:
        goto LABEL1
    return 1/z

myfunc1(0) 
myfunc2(0)

:LABEL1
print 'Cannot divide by zero'.

Compared to python:

def myfunc1(x):
    return 1/x

def myfunc2(y):
    return 1/y


try:
    myfunc1(0)
    myfunc2(0)
except ZeroDivisionError:
    print 'Cannot divide by zero'

Explicit named exceptions are a significantly better way to deal with non-linear conditional branching.

Find records from one table which don't exist in another

There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:

This is the shortest statement, and may be quickest if your phone book is very short:

SELECT  *
FROM    Call
WHERE   phone_number NOT IN (SELECT phone_number FROM Phone_book)

alternatively (thanks to Alterlife)

SELECT *
FROM   Call
WHERE  NOT EXISTS
  (SELECT *
   FROM   Phone_book
   WHERE  Phone_book.phone_number = Call.phone_number)

or (thanks to WOPR)

SELECT * 
FROM   Call
LEFT OUTER JOIN Phone_Book
  ON (Call.phone_number = Phone_book.phone_number)
  WHERE Phone_book.phone_number IS NULL

(ignoring that, as others have said, it's normally best to select just the columns you want, not '*')

Select records from NOW() -1 Day

Judging by the documentation for date/time functions, you should be able to do something like:

SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

R define dimensions of empty data frame

It might help the solution given in another forum, Basically is: i.e.

Cols <- paste("A", 1:5, sep="")
DF <- read.table(textConnection(""), col.names = Cols,colClasses = "character")

> str(DF)
'data.frame':   0 obs. of  5 variables:
$ A1: chr
$ A2: chr
$ A3: chr
$ A4: chr
$ A5: chr

You can change the colClasses to fit your needs.

Original link is https://stat.ethz.ch/pipermail/r-help/2008-August/169966.html

How do I check whether a file exists without exceptions?

If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you're not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path
os.path.isfile(fname) 

if you need to be sure it's a file.

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

To check a directory, do:

if my_file.is_dir():
    # directory exists

To check whether a Path object exists independently of whether is it a file or directory, use exists():

if my_file.exists():
    # path exists

You can also use resolve(strict=True) in a try block:

try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists

Why use pointers?

One reason to use pointers is so that a variable or an object can be modified in a called function.

In C++ it is a better practice to use references than pointers. Though references are essentially pointers, C++ to some extent hides the fact and makes it seem as if you are passing by value. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it.

Consider the following examples:

Using references:

public void doSomething()
{
    int i = 10;
    doSomethingElse(i);  // passes i by references since doSomethingElse() receives it
                         // by reference, but the syntax makes it appear as if i is passed
                         // by value
}

public void doSomethingElse(int& i)  // receives i as a reference
{
    cout << i << endl;
}

Using pointers:

public void doSomething()
{
    int i = 10;
    doSomethingElse(&i);
}

public void doSomethingElse(int* i)
{
    cout << *i << endl;
}