Programs & Examples On #Dmp

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

Import one schema into another new schema - Oracle

The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave

Not receiving Google OAuth refresh token

I'd like to add a bit more info on this subject for those frustrated souls who encounter this issue. The key to getting a refresh token for an offline app is to make sure you are presenting the consent screen. The refresh_token is only returned immediately after a user grants authorization by clicking "Allow".

enter image description here

The issue came up for me (and I suspect many others) after I'd been doing some testing in a development environment and therefore already authorized my application on a given account. I then moved to production and attempted to authenticate again using an account which was already authorized. In this case, the consent screen will not come up again and the api will not return a new refresh token. To make this work, you must force the consent screen to appear again by either:

prompt=consent

or

approval_prompt=force

Either one will work but you should not use both. As of 2021, I'd recommend using prompt=consent since it replaces the older parameter approval_prompt and in some api versions, the latter was actually broken (https://github.com/googleapis/oauth2client/issues/453). Also, prompt is a space delimited list so you can set it as prompt=select_account%20consent if you want both.

Of course you also need:

access_type=offline

Additional reading:

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

No more data to read from socket error

Another case: If you are sending date parameters to a parameterized sql, make sure you sent java.sql.Timestamp and not java.util.Date. Otherwise you get

java.sql.SQLRecoverableException: No more data to read from socket

Example statement: In our java code, we are using org.apache.commons.dbutils and we have the following:

final String sqlStatement = "select x from person where date_of_birth between ? and ?";
java.util.Date dtFrom = new Date(); //<-- this will fail
java.util.Date dtTo = new Date();   //<-- this will fail
Object[] params = new Object[]{ dtFrom , dtTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params); 

The above was failing until we changed the date parameters to be java.sql.Timestamp

java.sql.Timestamp tFrom = new java.sql.Timestamp (dtFrom.getTime()); //<-- this is OK
java.sql.Timestamp tTo = new java.sql.Timestamp(dtTo.getTime());   //<-- this is OK
Object[] params = new Object[]{ tFrom , tTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params); 

How to import an Oracle database from dmp file and log file?

If you are using impdp command example from @sathyajith-bhat response:

impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;

you will need to use mandatory parameter directory and create and grant it as:

CREATE OR REPLACE DIRECTORY DMP_DIR AS 'c:\Users\USER\Downloads';
GRANT READ, WRITE ON DIRECTORY DMP_DIR TO {USER};

or use one of defined:

select * from DBA_DIRECTORIES;

My ORACLE Express 11g R2 has default named DATA_PUMP_DIR (located at {inst_dir}\app\oracle/admin/xe/dpdump/) you sill need to grant it for your user.

convert htaccess to nginx

Have not tested it yet, but the looks are better than the one Alex mentions.

The description at winginx.com/en/htaccess says:

About the htaccess to nginx converter

The service is to convert an Apache's .htaccess to nginx configuration instructions.

First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.

Note server instructions (e.g. php_value, etc.) are ignored.

The converter does not check syntax, including regular expressions and logic errors.

Please, check the result manually before use.

Could not resolve Spring property placeholder

Ensure 'idm.url' is set in property file and the property file is loaded

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

How do I import a .dmp file into Oracle?

.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.

If you have an oracle client intalled on your machine, you can executed the command

imp help=y

to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.

How do you determine what technology a website is built on?

I use WebParser (http://www.cybermake.com) that allows to determine the CMS used by a website. It allows to determine CMS for multiple websites as well as it can pull the list of websites from the search engines for a given list of keywords. Powerful tool.

How to determine the Schemas inside an Oracle Data Pump Export file

My solution (similar to KyleLanser's answer) (on a Unix box):

strings dumpfile.dmp | grep SCHEMA_LIST

How to stop IIS asking authentication for default website on localhost

What worked for me is ,,,

Click Start>control panel>Administrative Tools>Internet Information Services

Expand the left tree, right-click your WebSite>Properties

Click on Directory Security, then in "Anonymous access and authentication control" click on Edit

Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK

Apply the settings and it should work fine.

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

Stop UIWebView from "bouncing" vertically?

On iOS5 only if you plan to let the users zoom the webview contents (e.i.: double tap) the bounce setting isn't enough. You need to set also alwaysBounceHorizontal and alwaysBounceVertical properties to NO, else when they zoom-out (another double tap...) to default it will bounce again.

"Cannot GET /" with Connect on Node.js

The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.

What is the difference between primary, unique and foreign key constraints, and indexes?

  1. A primary key is a column or a set of columns that uniquely identify a row in a table. A primary key should be short, stable and simple. A foreign key is a column (or set of columns) in a second table whose value is required to match the value of the primary key in the original table. Usually a foreign key is in a table that is different from the table whose primary key is required to match. A table can have multiple foreign keys.
  2. The primary key cannot accept null values. Foreign keys can accept multiple.
  3. We can have only one primary key in a table. We can have more than one foreign key in a table.
  4. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. Foreign keys do not automatically create an index, clustered or non-clustered. You can manually create an index on a foreign key.

How to write a simple Html.DropDownListFor()?

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

"date(): It is not safe to rely on the system's timezone settings..."

@Justis pointed me to the right direction, but his code did not work for me. This did:

// set the default timezone if not set at php.ini
if (!date_default_timezone_get('date.timezone')) {
    // insert here the default timezone
    date_default_timezone_set('America/New_York');
}

Documentation: http://www.php.net/manual/en/function.date-default-timezone-get.php

This solution is not only for those who does not have full system access. It is necessary for any script when you provide it to anyone else but you. You never know on what server the script will run when you distribute it to someone else.

Saving data to a file in C#

Look into the XMLSerializer class.

If you want to save the state of objects and be able to recreate them easily at another time, serialization is your best bet.

Serialize it so you are returned the fully-formed XML. Write this to a file using the StreamWriter class.

Later, you can read in the contents of your file, and pass it to the serializer class along with an instance of the object you want to populate, and the serializer will take care of deserializing as well.

Here's a code snippet taken from Microsoft Support:

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] args)
   {
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());

      // at this step, instead of passing Console.Out, you can pass in a 
      // Streamwriter to write the contents to a file of your choosing.
      x.Serialize(Console.Out, p);


      Console.WriteLine();
      Console.ReadLine();
   }
} 

Which font is used in Visual Studio Code Editor and how to change fonts?

Since the VisualStudio has been updated now (2019). You can try on this method:

  • Go to File->Preference->Settings.
  • Go to Workspace tab and then Text Editor->Font
  • Under Font-Family form, put the font-family names you want to use separated by a comma For e.g I have put these fonts in my Workspace: Click to see my Workspace setting

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

How to install and use "make" in Windows?

Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".

You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.

Keras model.summary() result - Understanding the # of Parameters

The "none" in the shape means it does not have a pre-defined number. For example, it can be the batch size you use during training, and you want to make it flexible by not assigning any value to it so that you can change your batch size. The model will infer the shape from the context of the layers.

To get nodes connected to each layer, you can do the following:

for layer in model.layers:
    print(layer.name, layer.inbound_nodes, layer.outbound_nodes)

Get the second largest number in a list in linear time

O(n): Time Complexity of a loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. For example following functions have O(n) time complexity.

 // Here c is a positive integer constant   
   for (int i = 1; i <= n; i += c) {  
        // some O(1) expressions
   }

To find the second largest number i used the below method to find the largest number first and then search the list if thats in there or not

x = [1,2,3]
A = list(map(int, x))
y = max(A)
k1 = list()
for values in range(len(A)):
if y !=A[values]:
    k.append(A[values])

z = max(k1)
print z

Do I really need to encode '&' as '&amp;'?

Validation aside, the fact remains that encoding certain characters is important to an HTML document so that it can render properly and safely as a web page.

Encoding & as &amp; under all circumstances, for me, is an easier rule to live by, reducing the likelihood of errors and failures.

Compare the following: which is easier? which is easier to bugger up?

Methodology 1

  1. Write some content which includes ampersand characters.
  2. Encode them all.

Methodology 2

(with a grain of salt, please ;) )

  1. Write some content which includes a ampersand characters.
  2. On a case-by-case basis, look at each ampersand. Determine if:
    • It is isolated, and as such unambiguously an ampersand. eg. volt & amp
       > In that case don't bother encoding it.
    • It is not isolated, but you feel it is nonetheless unambiguous, as the resulting entity does not exist and will never exist since the entity list could never evolve. eg amp&volt
       > In that case don't bother encoding it.
    • It is not isolated, and ambiguous. eg. volt&amp
       > Encode it.

??

Passing capturing lambda as function pointer

A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section 5.1.2 [expr.prim.lambda] says (emphasis mine):

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Note, cppreference also covers this in their section on Lambda functions.

So the following alternatives would work:

typedef bool(*DecisionFn)(int);

Decide greaterThanThree{ []( int x ){ return x > 3; } };

and so would this:

typedef bool(*DecisionFn)();

Decide greaterThanThree{ [](){ return true ; } };

and as 5gon12eder points out, you can also use std::function, but note that std::function is heavy weight, so it is not a cost-less trade-off.

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

How to hide a View programmatically?

You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

Set up git to pull and push all branches

The simplest way is to do:

git push --all origin

This will push tags and branches.

How can building a heap be O(n) time complexity?

@bcorso has already demonstrated the proof of the complexity analysis. But for the sake of those still learning complexity analysis, I have this to add:

The basis of your original mistake is due to a misinterpretation of the meaning of the statement, "insertion into a heap takes O(log n) time". Insertion into a heap is indeed O(log n), but you have to recognise that n is the size of the heap during the insertion.

In the context of inserting n objects into a heap, the complexity of the ith insertion is O(log n_i) where n_i is the size of the heap as at insertion i. Only the last insertion has a complexity of O (log n).

Unzip All Files In A Directory

The following bash script extracts all zip files in the current directory into new dirs with the filename of the zip file, i.e.:

The following files:

myfile1.zip
myfile2.zip 

Will be extracted to:

./myfile1/files...
./myfile2/files...

Shell script:

#!/bin/sh
for zip in *.zip
do
  dirname=`echo $zip | sed 's/\.zip$//'`
  if mkdir "$dirname"
  then
    if cd "$dirname"
    then
      unzip ../"$zip"
      cd ..
      # rm -f $zip # Uncomment to delete the original zip file
    else
      echo "Could not unpack $zip - cd failed"
    fi
  else
    echo "Could not unpack $zip - mkdir failed"
  fi
done

How to make HTML Text unselectable

No one here posted an answer with all of the correct CSS variations, so here it is:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Things possible in IntelliJ that aren't possible in Eclipse?

Structural search and replace.

For example, search for something like:

  System.out.println($string$ + $expr$);

Where $string$ is a literal, and $expr$ is an expression of type my.package.and.Class, and then replace with:

  $expr$.inspect($string$);

Java: Getting a substring from a string starting after a particular character

A very simple implementation with String.split():

String path = "/abc/def/ghfj.doc";
// Split path into segments
String segments[] = path.split("/");
// Grab the last segment
String document = segments[segments.length - 1];

Adding Http Headers to HttpClient

To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(someURL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);

Default header is SET ON HTTPCLIENT to send on every request to the server.

Error message: "'chromedriver' executable needs to be available in the path"

I had this problem on Webdriver 3.8.0 (Chrome 73.0.3683.103 and ChromeDriver 73.0.3683.68). The problem disappeared after I did

pip install -U selenium

to upgrade Webdriver to 3.14.1.

git push rejected: error: failed to push some refs

'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'

That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader

Static vs class functions/variables in Swift classes?

Adding to above answers static methods are static dispatch means the compiler know which method will be executed at runtime as the static method can not be overridden while the class method can be a dynamic dispatch as subclass can override these.

using href links inside <option> tag

(I don't have enough reputation to comment on toscho's answer.)

I have no experience with screen readers and I'm sure your points are valid.

However as far as using a keyboard to manipulate selects, it is trivial to select any option by using the keyboard:

TAB to the control

SPACE to open the select list

UP or DOWN arrows to scroll to the desired list item

ENTER to select the desired item

Only on ENTER does the onchange or (JQuery .change()) event fire.

While I personally would not use a form control for simple menus, there are many web applications that use form controls to change the presentation of the page (eg., sort order.) These can be implemented either by AJAX to load new content into the page, or, in older implementations, by triggering new page loads, which is essentially a page link.

IMHO these are valid uses of a form control.

How to convert Double to int directly?

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

How to get text box value in JavaScript

Set the id attribute of the input to txtJob. Your browser is acting quirky when you call getElementById.

AngularJS: Service vs provider vs factory

This is very confusing part for newbie and I have tried to clarify it in easy words

AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page.

In the service, we create function names as property with this object.

AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.

AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function.

Defining and using Service, Factory and Provider are explained at http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider

How to print a float with 2 decimal places in Java?

Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:

System.out.printf("%1.2f", 3.14159D);

See the docs on the Formatter for more information about the printf format string.

How to change DataTable columns order

If you have more than 2-3 columns, SetOrdinal is not the way to go. A DataView's ToTable method accepts a parameter array of column names. Order your columns there:

DataView dataView = dataTable.DefaultView;
dataTable = dataView.ToTable(true, "Qty", "Unit", "Id");

VueJs get url query

Current route properties are present in this.$route, this.$router is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query

Bootstrap dropdown menu not working (not dropping down when clicked)

I had the same issue I remove the following script and it worked for me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

Initializing a list to a known number of elements in Python

You could do this:

verts = list(xrange(1000))

That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list does a __len__ first to size the new list it should be fairly efficient.

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

It only appeared in my Chrome browser a few days ago too. I checked a few websites I developed in the past that haven't been changed and they also show the same error. So I'd suggest it's not down to your coding, rather a bug in the latest Chrome release.

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

Saving and Reading Bitmaps/Images from Internal memory in Android

    public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
        String selectedOutputPath = "";
        if (isSDCARDMounted()) {
            File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
            // Create a storage directory if it does not exist
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("PhotoEditorSDK", "Failed to create directory");
                }
            }
            // Create a media file name
            selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
            Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
            File file = new File(selectedOutputPath);
            try {
                FileOutputStream out = new FileOutputStream(file);
                if (layoutCollage != null) {
                    layoutCollage.setDrawingCacheEnabled(true);
                    layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return selectedOutputPath;
    }



private static boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I tried almost all the possible suggestions mention here but for me problem got solved after changing "Access for less secure apps" to ENABLE in my Google account security settings tab. Hope this might useful for others !

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

i put this method so imageuri path easily get in content.

enter code here
public Uri getImageUri(Context context, Bitmap inImage)
{
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), 
    inImage, "Title", null);
    return Uri.parse(path);
}

Interfaces with static fields in java for sharing 'constants'

I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.

Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.

If a client wants to compare cars prior to buying he can have a method like this:

public List<Decision> compareCars(List<I_Somecar> pCars);

An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

DOUBLE vs DECIMAL in MySQL

The example from MySQL documentation http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html (i shrink it, documentation for this section is the same for 5.5)

mysql> create table t1 (i int, d1 double, d2 double);

mysql> insert into t1 values (2, 0.00  , 0.00),
                             (2, -13.20, 0.00),
                             (2, 59.60 , 46.40),
                             (2, 30.40 , 30.40);

mysql> select
         i,
         sum(d1) as a,
         sum(d2) as b
       from
         t1
       group by
         i
       having a <> b; -- a != b

+------+-------------------+------+
| i    | a                 | b    |
+------+-------------------+------+
|    2 | 76.80000000000001 | 76.8 |
+------+-------------------+------+
1 row in set (0.00 sec)

Basically if you sum a you get 0-13.2+59.6+30.4 = 76.8. If we sum up b we get 0+0+46.4+30.4=76.8. The sum of a and b is the same but MySQL documentation says:

A floating-point value as written in an SQL statement may not be the same as the value represented internally.

If we repeat the same with decimal:

mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));
Query OK, 0 rows  affected (0.09 sec)

mysql> insert into t2 values (2, 0.00  , 0.00),
                             (2, -13.20, 0.00),
                             (2, 59.60 , 46.40),
                             (2, 30.40 , 30.40);
Query OK, 4 rows affected (0.07 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select
         i,
         sum(d1) as a,
         sum(d2) as b
       from
         t2
       group by
         i
       having a <> b;

Empty set (0.00 sec)

The result as expected is empty set.

So as long you do not perform any SQL arithemetic operations you can use DOUBLE, but I would still prefer DECIMAL.

Another thing to note about DECIMAL is rounding if fractional part is too large. Example:

mysql> create table t3 (d decimal(5,2));
Query OK, 0 rows affected (0.07 sec)

mysql> insert into t3 (d) values(34.432);
Query OK, 1 row affected, 1 warning (0.10 sec)

mysql> show warnings;
+-------+------+----------------------------------------+
| Level | Code | Message                                |
+-------+------+----------------------------------------+
| Note  | 1265 | Data truncated for column 'd' at row 1 |
+-------+------+----------------------------------------+
1 row in set (0.00 sec)

mysql> select * from t3;
+-------+
| d     |
+-------+
| 34.43 |
+-------+
1 row in set (0.00 sec)

open() in Python does not create a file if it doesn't exist

The advantage of the following approach is that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

with open("file.dat","a+") as f:
    f.write(...)
    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

seek() method sets the file's current position.

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail.

How to overlay density plots in R?

use lines for the second one:

plot(density(MyData$Column1))
lines(density(MyData$Column2))

make sure the limits of the first plot are suitable, though.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

LINQ's Distinct() on a particular property

You can do it (albeit not lightning-quickly) like so:

people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));

That is, "select all people where there isn't another different person in the list with the same ID."

Mind you, in your example, that would just select person 3. I'm not sure how to tell which you want, out of the previous two.

Core dumped, but core file is not in the current directory?

ulimit -c unlimited made the core file correctly appear in the current directory after a "core dumped".

Save and load MemoryStream to/from a file

I use a Panel Control to add a image or even stream video, but you can save the image on SQL Server as Image or MySQL as largeblob. This code works for me a lot. Check it out.

Here you save the image

MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, panel1.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // here you can change the Image format
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
ms.Close();

And here you can load, but I used a PictureBox Control.

MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);

Hope helps.

Validating a Textbox field for only numeric input.

You can do it by javascript on client side or using some regex validator on the textbox.

Javascript

script type="text/javascript" language="javascript">
    function validateNumbersOnly(e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
            return true;
        }
        else {

            window.alert("This field accepts only Numbers");
            return false;
        }
    }
</script>

Textbox (with fixed ValidationExpression)

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator> 

Drawing in Java using Canvas

The following should work:

public static void main(String[] args)
{
    final String title = "Test Window";
    final int width = 1200;
    final int height = width / 16 * 9;

    //Creating the frame.
    JFrame frame = new JFrame(title);

    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    //Creating the canvas.
    Canvas canvas = new Canvas();

    canvas.setSize(width, height);
    canvas.setBackground(Color.BLACK);
    canvas.setVisible(true);
    canvas.setFocusable(false);


    //Putting it all together.
    frame.add(canvas);

    canvas.createBufferStrategy(3);

    boolean running = true;

    BufferStrategy bufferStrategy;
    Graphics graphics;

    while (running) {
        bufferStrategy = canvas.getBufferStrategy();
        graphics = bufferStrategy.getDrawGraphics();
        graphics.clearRect(0, 0, width, height);

        graphics.setColor(Color.GREEN);
        graphics.drawString("This is some text placed in the top left corner.", 5, 15);

        bufferStrategy.show();
        graphics.dispose();
    }
}

Android image caching

I would consider using droidfu's image cache. It implements both an in-memory and disk-based image cache. You also get a WebImageView that takes advantage of the ImageCache library.

Here is the full description of droidfu and WebImageView: http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/

What is the Maximum Size that an Array can hold?

I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

CSS centred header image

I think this is what you need if I'm understanding you correctly:

<div id="wrapperHeader">
 <div id="header">
  <img src="images/logo.png" alt="logo" />
 </div> 
</div>



div#wrapperHeader {
 width:100%;
 height;200px; /* height of the background image? */
 background:url(images/header.png) repeat-x 0 0;
 text-align:center;
}

div#wrapperHeader div#header {
 width:1000px;
 height:200px;
 margin:0 auto;
}

div#wrapperHeader div#header img {
 width:; /* the width of the logo image */
 height:; /* the height of the logo image */
 margin:0 auto;
}

Check if a number has a decimal place/is a whole number

Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):

var guard = {

    guard: function(x) {
        if (!this.test(x)) {
            throw new TypeError("expected " + this);
        }
    }

    // ...
};

// ...

var number = Object.create(guard);
number.test = function(x) {
    return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
    return "number";
};


var uint32 = Object.create(guard);
uint32.test = function(x) {
    return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
    return "uint32";
};


var decimal = Object.create(guard);
decimal.test = function(x) {
    return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
    return "decimal";
};


uint32.guard(1234);     // fine
uint32.guard(123.4);    // TypeError: expected uint32

decimal.guard(1234);    // TypeError: expected decimal
decimal.guard(123.4);   // fine

How can I verify a Google authentication API access token?

An arbitrary OAuth access token can't be used for authentication, because the meaning of the token is outside of the OAuth Core spec. It could be intended for a single use or narrow expiration window, or it could provide access which the user doesn't want to give. It's also opaque, and the OAuth consumer which obtained it might never have seen any type of user identifier.

An OAuth service provider and one or more consumers could easily use OAuth to provide a verifiable authentication token, and there are proposals and ideas to do this out there, but an arbitrary service provider speaking only OAuth Core can't provide this without other co-ordination with a consumer. The Google-specific AuthSubTokenInfo REST method, along with the user's identifier, is close, but it isn't suitable, either, since it could invalidate the token, or the token could be expired.

If your Google ID is an OpenId identifier, and your 'public interface' is either a web app or can call up the user's browser, then you should probably use Google's OpenID OP.

OpenID consists of just sending the user to the OP and getting a signed assertion back. The interaction is solely for the benefit of the RP. There is no long-lived token or other user-specific handle which could be used to indicate that a RP has successfully authenticated a user with an OP.

One way to verify a previous authentication against an OpenID identifier is to just perform authentication again, assuming the same user-agent is being used. The OP should be able to return a positive assertion without user interaction (by verifying a cookie or client cert, for example). The OP is free to require another user interaction, and probably will if the authentication request is coming from another domain (my OP gives me the option to re-authenticate this particular RP without interacting in the future). And in Google's case, the UI that the user went through to get the OAuth token might not use the same session identifier, so the user will have to re-authenticate. But in any case, you'll be able to assert the identity.

Using colors with printf

I use this c code for printing coloured shell output. The code is based on this post.

//General Formatting
#define GEN_FORMAT_RESET                "0"
#define GEN_FORMAT_BRIGHT               "1"
#define GEN_FORMAT_DIM                  "2"
#define GEN_FORMAT_UNDERSCORE           "3"
#define GEN_FORMAT_BLINK                "4"
#define GEN_FORMAT_REVERSE              "5"
#define GEN_FORMAT_HIDDEN               "6"

//Foreground Colors
#define FOREGROUND_COL_BLACK            "30"
#define FOREGROUND_COL_RED              "31"
#define FOREGROUND_COL_GREEN            "32"
#define FOREGROUND_COL_YELLOW           "33"
#define FOREGROUND_COL_BLUE             "34"
#define FOREGROUND_COL_MAGENTA          "35"
#define FOREGROUND_COL_CYAN             "36"
#define FOREGROUND_COL_WHITE            "37"

//Background Colors
#define BACKGROUND_COL_BLACK            "40"
#define BACKGROUND_COL_RED              "41"
#define BACKGROUND_COL_GREEN            "42"
#define BACKGROUND_COL_YELLOW           "43"
#define BACKGROUND_COL_BLUE             "44"
#define BACKGROUND_COL_MAGENTA          "45"
#define BACKGROUND_COL_CYAN             "46"
#define BACKGROUND_COL_WHITE            "47"

#define SHELL_COLOR_ESCAPE_SEQ(X) "\x1b["X"m"
#define SHELL_FORMAT_RESET  ANSI_COLOR_ESCAPE_SEQ(GEN_FORMAT_RESET)

int main(int argc, char* argv[])
{
    //The long way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW), stdout);
    fputs("Text in gold\n", stdout);
    fputs(SHELL_FORMAT_RESET, stdout);
    fputs("Text in default color\n", stdout);

    //The short way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW)"Text in gold\n"SHELL_FORMAT_RESET"Text in default color\n", stdout);

    return 0;
}

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Spring @ContextConfiguration how to put the right location for the xml

This is a maven specific problem I think. Maven does not copy the files form /src/main/resources to the target-test folder. You will have to do this yourself by configuring the resources plugin, if you absolutely want to go this way.

An easier way is to instead put a test specific context definition in the /src/test/resources directory and load via:

@ContextConfiguration(locations = { "classpath:mycontext.xml" })

How do I get interactive plots again in Spyder/IPython/matplotlib?

After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel enter image description here

And you will surely get Interactive Plot. Happy Coding!

How to handle authentication popup with Selenium WebDriver using Java

The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box.

WebDriverWait wait = new WebDriverWait(driver, 10);      
Alert alert = wait.until(ExpectedConditions.alertIsPresent());     
alert.authenticateUsing(new UserAndPassword(username, password));

As of Selenium 3.4 it is still in beta

Right now implementation is only done for InternetExplorerDriver

Difference between hamiltonian path and euler path

I'll use a common example in biology; reconstructing a genome by making DNA samples.

De-novo assembly

To construct a genome from short reads, it's necessary to construct a graph of those reads. We do it by breaking the reads into k-mers and assemble them into a graph.

enter image description here

We can reconstruct the genome by visiting each node once as in the diagram. This is known as Hamiltonian path.

Unfortunately, constructing such path is NP-hard. It's not possible to derive an efficient algorithm for solving it. Instead, in bioinformatics we construct a Eulerian cycle where an edge represents an overlap.

enter image description here

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.

The return type of jsonSites.get(i) is JSONArray not JSONObject. Because sites have two '[', two means there are two arrays here.

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

.toLowerCase not working, replacement function?

It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)), but in this case there is nothing that expect the number to be a string.

Here's a makeLowerCase function. :)

function makeLowerCase(value) {
  return value.toString().toLowerCase();
}

Mock HttpContext.Current in Test Init Method

If your application third party redirect internally, so it is better to mock HttpContext in below way :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

Error Message: Gradle sync failed: Minimum supported Gradle version is 4.9. Current version is 4.1-milestone-1. If using the gradle wrapper, try editing the distributionUrl in SampleProj/app/gradle/wrapper/gradle-wrapper.properties to gradle-4.9-all.zip

I am using Android studio IDE version 3.2 beta 2.

Solution: When we open gradle-wrapper.properties file in IDE it shows correct distributionUrl. but originally it has not been updated. So change the distributionUrl property manually.

Example : open a gradle-wrapper.properties file in notepad or any other editor. /Project/app/gradle/wrapper/gradle-wrapper.properties and change distributionUrl property to like this

distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

How to get pip to work behind a proxy server

First Try to set proxy using the following command

SET HTTPS_PROXY=http://proxy.***.com:PORT#

Then Try using the command

pip install ModuleName

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

is there a require for json in node.js

Two of the most common

First way :

let jsonData = require('./JsonFile.json')

let jsonData = require('./JsonFile') // if we omitting .json also works

OR

import jsonData from ('./JsonFile.json')

Second way :

1) synchronously

const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))

2) asynchronously

const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
  if (err) throw err

  jsonData = JSON.parse(data)
})

Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')

2) The fs.readFile or fs.readFileSync will always re read the file, and get changes

ConnectivityManager getNetworkInfo(int) deprecated

This can help someone Kotlin

fun isNetworkConnected(context: Context) : Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val capabilities =  connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        capabilities.also {
            if (it != null){
                if (it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
                    return true
                else if (it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    return true
                }
            }
        }
        return false
    }

Excel VBA - How to Redim a 2D array?

Here ya go.

Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

Finding an item in a List<> using C#

For .NET 2.0:

list.Find(delegate(Item i) { return i.Property == someValue; });

Package name does not correspond to the file path - IntelliJ

I had this same issue, and fixed it by modifying my project's .iml file:

From:

<content url="file://$MODULE_DIR$">
  <sourceFolder url="file://$MODULE_DIR$/src/wrong/entry/here" isTestSource="false" />
  <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
  <excludeFolder url="file://$MODULE_DIR$/target" />
</content>

To:

<content url="file://$MODULE_DIR$">
  <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
  <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
  <excludeFolder url="file://$MODULE_DIR$/target" />
</content>

Somehow a package folder became specified as the root source directory when this project was imported.

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

How do I correctly setup and teardown for my pytest class with tests?

As @Bruno suggested, using pytest fixtures is another solution that is accessible for both test classes or even just simple test functions. Here's an example testing python2.7 functions:

import pytest

@pytest.fixture(scope='function')
def some_resource(request):
    stuff_i_setup = ["I setup"]

    def some_teardown():
        stuff_i_setup[0] += " ... but now I'm torn down..."
        print stuff_i_setup[0]
    request.addfinalizer(some_teardown)

    return stuff_i_setup[0]

def test_1_that_needs_resource(some_resource):
    print some_resource + "... and now I'm testing things..."

So, running test_1... produces:

I setup... and now I'm testing things...
I setup ... but now I'm torn down...

Notice that stuff_i_setup is referenced in the fixture, allowing that object to be setup and torn down for the test it's interacting with. You can imagine this could be useful for a persistent object, such as a hypothetical database or some connection, that must be cleared before each test runs to keep them isolated.

Set textarea width to 100% in bootstrap modal

I am new to .NET/MVC programming, but my understanding is that the Site.css file (under the Content folder in MVC) is a site-level override for Bootstrap CSS, allowing you to override bootstrap native settings in a portable and non-destructive manner (e.g. you can easily save and reapply your site.css changes when updating Bootstrap on your system.)

In Bootstrap 3.0.0, Site.css has the following style setting:

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Other blogs have suggested that this 280px width was added in haste near a release date, in a desire to make the UI look better than it does with 100% width input. Fortunately it was placed in a "visible" location in the site file so you would notice it.

Simply change the width setting, either for all three input types, or pull out textarea and give it its own setting if you want to leave the others alone.

How to send an email with Gmail as provider using Python?

    import smtplib

    fromadd='[email protected]'
    toadd='[email protected]'

    msg='''hi,how r u'''
    username='[email protected]'
    passwd='password'

    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(username,passwd)

        server.sendmail(fromadd,toadd,msg)
        print("Mail Send Successfully")
        server.quit()

   except:
        print("Error:unable to send mail")

   NOTE:https://www.google.com/settings/security/lesssecureapps that                                                         should be enabled

Stop setInterval call in JavaScript

Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);

// Add task(s) based on tick intervals.
timer.add({
    id: 'job1',         // unique id of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (omit for unlimited times)
    callback(task) {
        // code to be executed on each run
        console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
        // stop the timer anytime you like
        if (someCondition()) timer.stop();
        // or simply remove this task if you have others
        if (someCondition()) timer.remove(task.id);
    }
});

// Start the timer
timer.start();

In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

See more here.

How do I tar a directory of files and folders without including the directory itself?

Have a look at --transform/--xform, it gives you the opportunity to massage the file name as the file is added to the archive:

% mkdir my_directory
% touch my_directory/file1
% touch my_directory/file2
% touch my_directory/.hiddenfile1
% touch my_directory/.hiddenfile2
% tar -v -c -f my_dir.tgz --xform='s,my_directory/,,' $(find my_directory -type f)
my_directory/file2
my_directory/.hiddenfile1
my_directory/.hiddenfile2
my_directory/file1
% tar -t -f my_dir.tgz 
file2
.hiddenfile1
.hiddenfile2
file1

Transform expression is similar to that of sed, and we can use separators other than / (, in the above example).
https://www.gnu.org/software/tar/manual/html_section/tar_52.html

Easiest way to toggle 2 classes in jQuery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

$('body').toggle2classes('a', 'b');

How to Programmatically Add Views to Views

Calling addView is the correct answer, but you need to do a little more than that to get it to work.

If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

For example, you might have the following code in your onCreate() function assuming your LinearLayout has id R.id.main:

LinearLayout myLayout = findViewById(R.id.main);

Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.MATCH_PARENT,
                                     LinearLayout.LayoutParams.MATCH_PARENT));

myLayout.addView(myButton);

Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.

NuGet auto package restore does not work with MSBuild

In Visual Studio 2017 - When you compile using IDE - It will download all the missing nuget packages and save in the folder "packages".

But on the build machine compilation was done using msbuild.exe. In that case, I downloaded nuget.exe and kept in path.

During each build process before executing msbuild.exe. It will execute -> nuget.exe restore NAME_OF_SLN_File (if there is only one .SLN file then you can ignore that parameter)

Sending email with PHP from an SMTP server

When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).

For example, I usually use PHPMailer with similar settings to this ones:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com"; // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username"; // SMTP account username example
$mail->Password   = "password";        // SMTP account password example

// Content
$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();

You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer

Query to list all users of a certain group

If the DC is Win2k3 SP2 or above, you can use something like:

(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))

to get the nested group membership.

Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

Razor View throwing "The name 'model' does not exist in the current context"

In my case, I recently updated from MVC 4 to MVC 5, which screws up the web.config pretty badly. This article helped tremendously.

http://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

The bottom line is that you need to check all your version number references in your web.config and Views/web.config to make sure that they are referencing the correct upgraded versions associated with MVC 5.

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with /> at the end. In React, we have to close every element. Your code should be:

<input id="icon_prefix" type="text" class="validate/">

Javascript | Set all values of an array

There's no built-in way, you'll have to loop over all of them:

function setAll(a, v) {
    var i, n = a.length;
    for (i = 0; i < n; ++i) {
        a[i] = v;
    }
}

http://jsfiddle.net/alnitak/xG88A/

If you really want, do this:

Array.prototype.setAll = function(v) {
    var i, n = this.length;
    for (i = 0; i < n; ++i) {
        this[i] = v;
    }
};

and then you could actually do cool.setAll(42) (see http://jsfiddle.net/alnitak/ee3hb/).

Some people frown upon extending the prototype of built-in types, though.

EDIT ES5 introduced a way to safely extend both Object.prototype and Array.prototype without breaking for ... in ... enumeration:

Object.defineProperty(Array.prototype, 'setAll', {
    value: function(v) {
        ...
    }
});

EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

Why is a primary-foreign key relation required when we can join without it?

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

How do C++ class members get initialized if I don't do it explicitly?

Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.

Of course for object parameters (like string) the object's constructor could do a default initialization.

In your example:

int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value

Error while inserting date - Incorrect date value:

As MySql accepts the date in y-m-d format in date type column, you need to STR_TO_DATE function to convert the date into yyyy-mm-dd format for insertion in following way:

INSERT INTO table_name(today) 
VALUES(STR_TO_DATE('07-25-2012','%m-%d-%y'));  

Similary, if you want to select the date in different format other than Mysql format, you should try DATE_FORMAT function

SELECT DATE_FORMAT(today, '%m-%d-%y') from table_name; 

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

What is the MySQL JDBC driver connection string?

Assuming your driver is in path,

String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Connection conn = DriverManager.getConnection (url, "username", "password");

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

How to flush output of print function?

Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):
    self.f.write(x)
    self.f.flush()

import sys
sys.stdout = flushfile(sys.stdout)

... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Unix's 'ls' sort by name

For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort

To sort them in reverse order:
ls -1 | sort -r

How to browse for a file in java swing library?

I ended up using this quick piece of code that did exactly what I needed:

final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);

try {
    // Open an input stream
    Scanner reader = new Scanner(fc.getSelectedFile());
}

Output (echo/print) everything from a PHP Array

Similar to karim's, but with print_r which has a much small output and I find is usually all you need:

function PrintR($var) {
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}

DateTime group by date and hour

In my case... with MySQL:

SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))

What does auto do in margin:0 auto?

margin:0 auto;

0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container.

Generally if you want to put any element at center position then margin:auto works perfectly. But it only works in block elements.

Adding a Method to an Existing Object Instance

Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from object, but otherwise the code should remain the same.

Adding a Method to an Existing Object Instance

I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python.

I understand that it's not always a good decision to do so. But, how might one do this?

Yes, it is possible - But not recommended

I don't recommend this. This is a bad idea. Don't do it.

Here's a couple of reasons:

  • You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory. Bound methods are typically only created for the short duration of their call, and they then cease to exist when automatically garbage collected. If you do this manually, you'll have a name binding referencing the bound method - which will prevent its garbage collection on usage.
  • Object instances of a given type generally have its methods on all objects of that type. If you add methods elsewhere, some instances will have those methods and others will not. Programmers will not expect this, and you risk violating the rule of least surprise.
  • Since there are other really good reasons not to do this, you'll additionally give yourself a poor reputation if you do it.

Thus, I suggest that you not do this unless you have a really good reason. It is far better to define the correct method in the class definition or less preferably to monkey-patch the class directly, like this:

Foo.sample_method = sample_method

Since it's instructive, however, I'm going to show you some ways of doing this.

How it can be done

Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter.

class Foo(object):
    '''An empty class to demonstrate adding a method to an instance'''

Create an instance:

foo = Foo()

Create a method to add to it:

def sample_method(self, bar, baz):
    print(bar + baz)

Method nought (0) - use the descriptor method, __get__

Dotted lookups on functions call the __get__ method of the function with the instance, binding the object to the method and thus creating a "bound method."

foo.sample_method = sample_method.__get__(foo)

and now:

>>> foo.sample_method(1,2)
3

Method one - types.MethodType

First, import types, from which we'll get the method constructor:

import types

Now we add the method to the instance. To do this, we require the MethodType constructor from the types module (which we imported above).

The argument signature for types.MethodType is (function, instance, class):

foo.sample_method = types.MethodType(sample_method, foo, Foo)

and usage:

>>> foo.sample_method(1,2)
3

Method two: lexical binding

First, we create a wrapper function that binds the method to the instance:

def bind(instance, method):
    def binding_scope_fn(*args, **kwargs): 
        return method(instance, *args, **kwargs)
    return binding_scope_fn

usage:

>>> foo.sample_method = bind(foo, sample_method)    
>>> foo.sample_method(1,2)
3

Method three: functools.partial

A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus:

>>> from functools import partial
>>> foo.sample_method = partial(sample_method, foo)
>>> foo.sample_method(1,2)
3    

This makes sense when you consider that bound methods are partial functions of the instance.

Unbound function as an object attribute - why this doesn't work:

If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument.

>>> foo.sample_method = sample_method
>>> foo.sample_method(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sample_method() takes exactly 3 arguments (2 given)

We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the self argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance):

>>> foo.sample_method(foo, 1, 2)
3

Conclusion

You now know several ways you could do this, but in all seriousness - don't do this.

Python: Finding differences between elements of a list

Using the := walrus operator available in Python 3.8+:

>>> t = [1, 3, 6]
>>> prev = t[0]; [-prev + (prev := x) for x in t[1:]]
[2, 3]

How to use store and use session variables across pages?

All you want to do is write --- session_start(); ----- on both pages..

<!-- first page -->
<?php
  session_start(); 
  $_SESSION['myvar'] = 'hello';
?>

<!-- second page -->
<?php
    session_start();
    echo $_SESSION['myvar']; // it will print hello 

?>

Configure apache to listen on port other than 80

If you are using Apache on Windows:

  1. Check the name of the Apache service with Win+R+services.msc+Enter (if it's not ApacheX.Y, it should have the name of the software you are using with apache, e.g.: "wampapache64");
  2. Start a command prompt as Administrator (using Win+R+cmd+Enter is not enough);
  3. Change to Apache's directory, e.g.: cd c:\wamp\bin\apache\apache2.4.9\bin;
  4. Check if the config file is OK with: httpd.exe -n "YourServiceName" -t (replace the service name by the one you found on step 1);
  5. Make sure that the service is stopped: httpd.exe -k stop -n "YourServiceName"
  6. Start it with: httpd.exe -k start -n "YourServiceName"
  7. If it starts alright, the problem is no longer there, but if you get:

    AH00072: make_sock: could not bind to address IP:PORT_NUMBER

    AH00451: no listening sockets available, shutting down

    If the port number is not the one you wanted to use, then open the Apache config file (e.g. C:\wamp\bin\apache\apache2.4.9\conf\httpd.conf open with a code editor or wordpad, but not notepad - it does not read new lines properly) and replace the number on the line that starts with Listen with the number of the port you want, save it and repeat step 6. If it is the one you wanted to use, then continue:

  8. Check the PID of the process that is using that port with Win+R+resmon+Enter, click on Network tab and then on Ports subtab;
  9. Kill it with: taskkill /pid NUMBER /f (/f forces it);
  10. Recheck resmon to confirm that the port is free now and repeat step 6.

This ensures that Apache's service was started properly, the configuration on virtual hosts config file as sarul mentioned (e.g.: C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf) is necessary if you are setting your files path in there and changing the port as well. If you change it again, remember to restart the service: httpd.exe -k restart -n "YourServiceName".

Apply CSS Style to child elements

As far as I know this:

div[class=yourclass] table {  your style here; } 

or in your case even this:

div.yourclass table { your style here; }

(but this will work for elements with yourclass that might not be divs) will affect only tables inside yourclass. And, as Ken says, the > is not supported everywhere (and div[class=yourclass] too, so use the point notation for classes).

Java: Unresolved compilation problem

I got this error multiple times and struggled to work out. Finally, I removed the run configuration and re-added the default entries. It worked beautifully.

How to enable CORS in ASP.net Core WebAPI

In launchSettings.json, under iisSettings, set anonymousAuthentication to true:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:4200/",
      "sslPort": 0
    }
  }

Then, in Startup.cs, under ConfigureServices, before services.AddMvc, add:

services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
    builder
        .AllowAnyOrigin()
        .WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
        .AllowAnyMethod()
        .AllowCredentials();
}));

and then, in configure method, before app.UseMvc() add:

app.UseCors("ApiCorsPolicy");

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

How to get the selected value from RadioButtonList?

radiobuttonlist.selected <value> to process with your code.

How to add Certificate Authority file in CentOS 7

copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust

How to both read and write a file in C#

Made an improvement code by @Ipsita - for use asynchronous read\write file I/O

readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
    TextReader tr = new StreamReader(logPath);
    string data = await tr.ReadLineAsync();
    tr.Close();

    TextWriter tw = new StreamWriter(logPath);
    await tw.WriteLineAsync(data + dataToWrite);
    tw.Close();
}
...
await WriteToLogAsync("Write this to file");

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.

Checking whether a String contains a number value in Java

Shef's answer doesn't compile for me. It looks like he's using RegEx in String.contains(). If you want to use RegEx use this:

String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string has a number";

System.out.println(strWithNumber.matches(".*\\d.*"));
System.out.println(strWithoutNumber.matches(".*\\d.*"));

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.

But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.

This may help to understand:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).

Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).

This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

  • it's a bit slower (having to maintain another table and joins uses three tables instead of just two),
  • the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)
  • it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

How do I parse JSON from a Java HTTPResponse?

Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.

Printing an array in C++?

My simple answer is:

#include <iostream>
using namespace std;

int main()
{
    int data[]{ 1, 2, 7 };
    for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
        cout << data[i];
    }

    return 0;
}

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Embed an External Page Without an Iframe?

Question is good, but the answer is : it depends on that.

If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.

But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.

How to convert InputStream to FileInputStream

Long story short: Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.

maven error: package org.junit does not exist

In my case, the culprit was not distinguish the main and test sources folder within pom.xml (generated by eclipse maven project)

<build>
    <sourceDirectory>src</sourceDirectory>
    ....
</build>

If you override default source folder settings in pom file, you must explicitly set the main AND test source folders!!!!

<build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    ....
</build>

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

Insert variable into Header Location PHP

We can also use this with the $_GET method

$employee_id = 'EMP-1234';

header('Location: employee.php?id='.$employee_id);

Remove unwanted parts from strings in a column

In the particular case where you know the number of positions that you want to remove from the dataframe column, you can use string indexing inside a lambda function to get rid of that parts:

Last character:

data['result'] = data['result'].map(lambda x: str(x)[:-1])

First two characters:

data['result'] = data['result'].map(lambda x: str(x)[2:])

android image button

You can use the button :

1 - make the text empty

2 - set the background for it

+3 - you can use the selector to more useful and nice button


About the imagebutton you can set the image source and the background the same picture and it must be (*.png) when you do it you can make any design for the button

and for more beauty button use the selector //just Google it ;)

How can I throw a general exception in Java?

You could create your own Exception class:

public class InvalidSpeedException extends Exception {

  public InvalidSpeedException(String message){
     super(message);
  }

}

In your code:

throw new InvalidSpeedException("TOO HIGH");

How to get a reversed list view on a list in Java?

If i have understood correct then it is one line of code .It worked for me .

 Collections.reverse(yourList);

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

If I understand correctly, what you want to do is to have a clean environment to be set up for DB involving integration tests.

My approach here would be to drop the whole schema and recreate it later.

Reasons:

  1. You probably already have a "create schema" script. Re-using it for test isolation is easy.
  2. Creating a schema is pretty quick.
  3. With that approach, it is pretty easy to set up your script to have each fixture create a NEW schema (with a temporary name), and then you can start running test-fixtures in parallel, making the slowest part of your test suite much faster.

Convert wchar_t to char

In general, no. int(wchar_t(255)) == int(char(255)) of course, but that just means they have the same int value. They may not represent the same characters.

You would see such a discrepancy in the majority of Windows PCs, even. For instance, on Windows Code page 1250, char(0xFF) is the same character as wchar_t(0x02D9) (dot above), not wchar_t(0x00FF) (small y with diaeresis).

Note that it does not even hold for the ASCII range, as C++ doesn't even require ASCII. On IBM systems in particular you may see that 'A' != 65

Convert the first element of an array to a string in PHP

A simple way to create a array to a PHP string array is:

<?PHP
    $array = array("firstname"=>"John", "lastname"=>"doe");
    $json = json_encode($array);
    $phpStringArray = str_replace(array("{", "}", ":"), 
                                  array("array(", "}", "=>"), $json);
    echo phpStringArray;
?>

PHP preg_match - only allow alphanumeric strings and - _ characters

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

Run Stored Procedure in SQL Developer?

To run procedure from SQL developer-only execute following command

EXECUTE PROCEDURE_NAME;

How to get the difference between two arrays of objects in JavaScript

I found this solution using filter and some.

_x000D_
_x000D_
resultFilter = (firstArray, secondArray) => {_x000D_
  return firstArray.filter(firstArrayItem =>_x000D_
    !secondArray.some(_x000D_
      secondArrayItem => firstArrayItem._user === secondArrayItem._user_x000D_
    )_x000D_
  );_x000D_
};
_x000D_
_x000D_
_x000D_

How to read existing text files without defining path

You could use Directory.GetCurrentDirectory:

var path = Path.Combine(Directory.GetCurrentDirectory(), "\\fileName.txt");

Which will look for the file fileName.txt in the current directory of the application.

How to get just one file from another branch

Supplemental to VonC's and chhh's answers.

git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative than just use
git show experiment:app.js > app.js

or

git checkout experiment -- app.js

Attaching click event to a JQuery object not yet added to the DOM

Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.

I bound the table id to .delegate() and used a selector that describes the inputs.

e.g.

HTML

<table id="#mytable">
  <!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
  <tr><td><input name="qty_001" /></td></tr>
  <tr><td><input name="qty_002" /></td></tr>
  <tr><td><input name="qty_003" /></td></tr>
</table>

jQuery

$('#mytable').delegate('click', 'name^=["qty_"]', function() {
    console.log("you clicked cell #" . $(this).attr("name"));
});

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

Can there exist two main methods in a Java program?

the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

How to add an object to an array

You are running into a scope problem if you use your code as such. You have to declare it outside the functions if you plan to use it between them (or if calling, pass it as a parameter).

var a = new Array();
var b = new Object();

function first() {
a.push(b);
// Alternatively, a[a.length] = b
// both methods work fine
}

function second() {
var c = a[0];
}

// code
first();
// more code
second();
// even more code

What causes the Broken Pipe Error?

It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.

Android Failed to install HelloWorld.apk on device (null) Error

What Jichao said always works for me.

Generally when I see this error if I am using Eclipse I will close and reopen the program. I will then uninstall the Application from the target phone. This sometimes fixes the issue but not always.

Next I will open up the command terminal and head into the android-sdk then run:

./adb install <AppName>.apk

This does the same thing that running through Eclipse does but it will give you an error message.

(9 times out of 10 it simply says 'INSTALL_ALREADY_EXISTS' and I go and uninstall the application off the target phone again then run adb and I am working fine.)

Get Unix timestamp with C++

I created a global define with more information:

#include <iostream>
#include <ctime>
#include <iomanip>

#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__)    // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "

static std::time_t time_now = std::time(nullptr);

Use it like this:

INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;

Sample output:

16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world

Put these lines in your header file. I find this very useful for debugging, etc.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

(Updated - Thanks to the people who commented)

Modern Versions of PostgreSQL

Suppose you have a table named test1, to which you want to add an auto-incrementing, primary-key id (surrogate) column. The following command should be sufficient in recent versions of PostgreSQL:

   ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

Older Versions of PostgreSQL

In old versions of PostgreSQL (prior to 8.x?) you had to do all the dirty work. The following sequence of commands should do the trick:

  ALTER TABLE test1 ADD COLUMN id INTEGER;
  CREATE SEQUENCE test_id_seq OWNED BY test1.id;
  ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq');
  UPDATE test1 SET id = nextval('test_id_seq');

Again, in recent versions of Postgres this is roughly equivalent to the single command above.

Convert JSONObject to Map

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

Display JSON Data in HTML Table

As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.

It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable

To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:

<div id="citytable"></div>

Then in the ajax success method you will want something like this

success: function(data){ 
    $("#citytable").mrjsontable({
        tableClass: "my-table",
        pageSize: 10, //you can change the page size here
        columns: [
            new $.fn.mrjsontablecolumn({
                heading: "City",
                data: "city"
            }),
            new $.fn.mrjsontablecolumn({
                heading: "City Status",
                data: "cStatus"
            })
        ],
        data: data
    });
}

Hope it helps somebody else!

How do I subscribe to all topics of a MQTT broker

Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

mosquitto_sub -h test.mosquitto.org -t "#" -v

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of irisys/V4D-19230005/ to the test MQTT broker , then you could filter the messages:

mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v

Options:

  • -h the hostname (default MQTT port = 1883)
  • -t precedes the topic

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

Java: How to access methods from another class

Maybe you need some dependency injection

public class Alpha {

    private Beta cbeta;

    public Alpha(Beta beta) {
        this.cbeta = beta;
    }

    public void DoSomethingAlpha() {
        this.cbeta.DoSomethingBeta();
    }
}

and then

Alpha cAlpha = new Alpha(new Beta());   

List tables in a PostgreSQL schema

Alternatively to information_schema it is possible to use pg_tables:

select * from pg_tables where schemaname='public';

How to get the file name from a full path using JavaScript?

Just for the sake of performance, I tested all the answers given here:

var substringTest = function (str) {
    return str.substring(str.lastIndexOf('/')+1);
}

var replaceTest = function (str) {
    return str.replace(/^.*(\\|\/|\:)/, '');
}

var execTest = function (str) {
    return /([^\\]+)$/.exec(str)[1];
}

var splitTest = function (str) {
    return str.split('\\').pop().split('/').pop();
}

substringTest took   0.09508600000000023ms
replaceTest   took   0.049203000000000004ms
execTest      took   0.04859899999999939ms
splitTest     took   0.02505500000000005ms

And the winner is the Split and Pop style answer, Thanks to bobince !

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

functional way to iterate over range (ES6/7)

ES7 Proposal

Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method

You can always use something like:

[for (i of Array(7).keys()) i*i];

Running this code on Firefox:

[ 0, 1, 4, 9, 16, 25, 36 ]

This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.

This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:

var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]

Then you can do:

[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25

ES6

A nice way to do this any of:

[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);

This will output:

[ 0, 1, 4, 9, 16, 25, 36 ]

Convert a number to 2 decimal places in Java

try this new DecimalFormat("#.00");

update:

    double angle = 20.3034;

    DecimalFormat df = new DecimalFormat("#.00");
    String angleFormated = df.format(angle);
    System.out.println(angleFormated); //output 20.30

Your code wasn't using the decimalformat correctly

The 0 in the pattern means an obligatory digit, the # means optional digit.

update 2: check bellow answer

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

Split output of command by columns using Bash?

One easy way is to add a pass of tr to squeeze any repeated field separators out:

$ ps | egrep 11383 | tr -s ' ' | cut -d ' ' -f 4

TSQL CASE with if comparison in SELECT statement

You can try with this:

WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID  as UserID FROM Articles A
           Inner Join Users U
           on  A.userId = U.userId 
           Group By A.userId , U.userId   ),

B as (Select us.registrationDate,

      CASE
         WHEN CTE_A.articleNumber < 2 THEN 'Ama'
         WHEN CTE_A.articleNumber < 5 THEN 'SemiAma' 
         WHEN CTE_A.articleNumber < 7 THEN 'Good'  
         WHEN CTE_A.articleNumber < 9 THEN 'Better' 
         WHEN CTE_A.articleNumber < 12 THEN 'Best'
         ELSE 'Outstanding'
         END as Ranking,
         us.hobbies, etc...
         FROM USERS Us Inner Join CTE_A 
         on CTE_A.UserID=us.UserID)

Select * from B

Using jQuery's ajax method to retrieve images as a blob

You can't do this with jQuery ajax, but with native XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is what you're looking for
        handler(this.response);
        console.log(this.response, typeof this.response);
        var img = document.getElementById('img');
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
    }
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();      

EDIT

So revisiting this topic, it seems it is indeed possible to do this with jQuery 3

_x000D_
_x000D_
jQuery.ajax({_x000D_
        url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
        cache:false,_x000D_
        xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
            var xhr = new XMLHttpRequest();_x000D_
            xhr.responseType= 'blob'_x000D_
            return xhr;_x000D_
        },_x000D_
        success: function(data){_x000D_
            var img = document.getElementById('img');_x000D_
            var url = window.URL || window.webkitURL;_x000D_
            img.src = url.createObjectURL(data);_x000D_
        },_x000D_
        error:function(){_x000D_
            _x000D_
        }_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
_x000D_
_x000D_

or

use xhrFields to set the responseType

_x000D_
_x000D_
    jQuery.ajax({_x000D_
            url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
            cache:false,_x000D_
            xhrFields:{_x000D_
                responseType: 'blob'_x000D_
            },_x000D_
            success: function(data){_x000D_
                var img = document.getElementById('img');_x000D_
                var url = window.URL || window.webkitURL;_x000D_
                img.src = url.createObjectURL(data);_x000D_
            },_x000D_
            error:function(){_x000D_
                _x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
    <img id="img" width=100%>
_x000D_
_x000D_
_x000D_

How to change font size in Eclipse for Java text editors?

This worked for me:

  1. On the Eclipse toolbar, select Window ? Preferences.

  2. Set the font size (General ? Appearance ? Colors and Fonts ? Basic ? Text Font):

    Enter image description here

  3. Save the preferences.

How do I set ANDROID_SDK_HOME environment variable?

open your adt and open preferences, then modify directory with your sdk dir, it may help you follow the pic link indication

enter image description here

Using module 'subprocess' with timeout

Unfortunately, I'm bound by very strict policies on the disclosure of source code by my employer, so I can't provide actual code. But for my taste the best solution is to create a subclass overriding Popen.wait() to poll instead of wait indefinitely, and Popen.__init__ to accept a timeout parameter. Once you do that, all the other Popen methods (which call wait) will work as expected, including communicate.

Git - Pushing code to two remotes

In recent versions of Git you can add multiple pushurls for a given remote. Use the following to add two pushurls to your origin:

git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git

So when you push to origin, it will push to both repositories.

UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v should reveal the current URLs for each remote.

UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url> adds a pushurl for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurls for a given remote, which then allows you to push to multiple remotes using a single git push. You can verify this behavior below:

$ git clone git://original/repo.git
$ git remote -v
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

Now, if you want to push to two or more repositories using a single command, you may create a new remote named all (as suggested by @Adam Nelson in comments), or keep using the origin, though the latter name is less descriptive for this purpose. If you still want to use origin, skip the following step, and use origin instead of all in all other steps.

So let's add a new remote called all that we'll reference later when pushing to multiple repositories:

$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)               <-- ADDED
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git            <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED

Then let's add a pushurl to the all remote, pointing to another repository:

$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)                 <-- CHANGED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git         <-- ADDED

Here git remote -v shows the new pushurl for push, so if you do git push all master, it will push the master branch to git://another/repo.git only. This shows how pushurl overrides the default url (remote.all.url).

Now let's add another pushurl pointing to the original repository:

$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git        <-- ADDED

You see both pushurls we added are kept. Now a single git push all master will push the master branch to both git://another/repo.git and git://original/repo.git.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

jquery input select all on focus

Found a awesome solution reading this thread

$(function(){

    jQuery.selectText('input:text');
    jQuery.selectText('input:password');

});

jQuery.extend( {
    selectText: function(s) { 
        $(s).live('focus',function() {
            var self = $(this);
            setTimeout(function() {self.select();}, 0);
        });
    }
});

What .NET collection provides the fastest search

If you aren't worried about squeaking every single last bit of performance the suggestion to use a HashSet or binary search is solid. Your datasets just aren't large enough that this is going to be a problem 99% of the time.

But if this just one of thousands of times you are going to do this and performance is critical (and proven to be unacceptable using HashSet/binary search), you could certainly write your own algorithm that walked the sorted lists doing comparisons as you went. Each list would be walked at most once and in the pathological cases wouldn't be bad (once you went this route you'd probably find that the comparison, assuming it's a string or other non-integral value, would be the real expense and that optimizing that would be the next step).

Accessing a local website from another computer inside the local network in IIS 7

Control Panel >> Windows Firewall >> Turn windows firewall on or off >> Turn off.

Advanced settings >> Domain profile >> Windows firewall properties >> Firewall status >> Off.

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

What is cURL in PHP?

Php curl class (GET,POST,FILES UPLOAD, SESSIONS, SEND POST JSON, FORCE SELFSIGNED SSL/TLS):

<?php
    // Php curl class
    class Curl {

        public $error;

        function __construct() {}

        function Get($url = "http://hostname.x/api.php?q=jabadoo&txt=gin", $forceSsl = false,$cookie = "", $session = true){
            // $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);        
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){            
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function GetArray($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function PostJson($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $data = json_encode($data);
            $ch = curl_init($url);                                                                      
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer helo29dasd8asd6asnav7ffa',                                                      
                'Content-Type: application/json',                                                                                
                'Content-Length: ' . strlen($data))                                                                       
            );        
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }

        function Post($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $files = array('ads/ads0.jpg', 'ads/ads1.jpg'), $forceSsl = false, $cookie = "", $session = true){
            foreach ($files as $k => $v) {
                $f = realpath($v);
                if(file_exists($f)){
                    $fc = new CurlFile($f, mime_content_type($f), basename($f)); 
                    $data["file[".$k."]"] = $fc;
                }
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");        
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }
    }
?>

Example:

<?php
    $urlget = "http://hostname.x/api.php?id=123&user=bax";
    $url = "http://hostname.x/api.php";
    $data = array("name" => "Max", "age" => "36");
    $files = array('ads/ads0.jpg', 'ads/ads1.jpg');

    $curl = new Curl();
    echo $curl->Get($urlget, true, "token=12345");
    echo $curl->GetArray($url, $data, true);
    echo $curl->Post($url, $data, $files, true);
    echo $curl->PostJson($url, $data, true);
?>

Php file: api.php

<?php
    /*
    $Cookie = session_get_cookie_params();
    print_r($Cookie);
    */
    session_set_cookie_params(9000, '/', 'hostname.x', isset($_SERVER["HTTPS"]), true);
    session_start();

    $_SESSION['cnt']++;
    echo "Session count: " . $_SESSION['cnt']. "\r\n";
    echo $json = file_get_contents('php://input');
    $arr = json_decode($json, true);
    echo "<pre>";
    if(!empty($json)){ print_r($arr); }
    if(!empty($_GET)){ print_r($_GET); }
    if(!empty($_POST)){ print_r($_POST); }
    if(!empty($_FILES)){ print_r($_FILES); }
    // request headers
    print_r(getallheaders());
    print_r(apache_response_headers());
    // Fetch a list of headers to be sent.
    // print_r(headers_list());
?>

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

Check if a string contains a number

You can use a combination of any and str.isdigit:

def num_there(s):
    return any(i.isdigit() for i in s)

The function will return True if a digit exists in the string, otherwise False.

Demo:

>>> king = 'I shall have 3 cakes'
>>> num_there(king)
True
>>> servant = 'I do not have any cakes'
>>> num_there(servant)
False

How to validate phone numbers using regex

Do a replace on formatting characters, then check the remaining for phone validity. In PHP,

 $replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed
 preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );

Breaking a complex regexp like this can be just as effective, but much more simple.

Is there "\n" equivalent in VBscript?

I had to use vbLf only in an ASP script where the original data was POSTed from a PHP script on a cPanel box over to ASP on a win server

(VBScript)

EmailText = Replace(EmailText, vbLf, "<br>")

Manually Triggering Form Validation using jQuery

I'm not sure it's worth it for me to type this all up from scratch since this article published in A List Apart does a pretty good job explaining it. MDN also has a handy guide for HTML5 forms and validation (covering the API and also the related CSS).

Best way to check if a Data Table has a null value in it

You can loop throw the rows and columns, checking for nulls, keeping track of whether there's a null with a bool, then check it after looping through the table and handle it.

//your DataTable, replace with table get code
DataTable table = new DataTable();
bool tableHasNull = false;

foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        //test for null here
        if (row[col] == DBNull.Value)
        {
            tableHasNull = true;
        }
    }
}

if (tableHasNull)
{
    //handle null in table
}

You can also come out of the foreach loop with a break statement e.g.

//test for null here
if (row[col] == DBNull.Value)
{
    tableHasNull = true;
    break;
}

To save looping through the rest of the table.

Java 32-bit vs 64-bit compatibility

Unless you have native code (machine code compiled for a specific arcitechture) your code will run equally well in a 32-bit and 64-bit JVM.

Note, however, that due to the larger adresses (32-bit is 4 bytes, 64-bit is 8 bytes) a 64-bit JVM will require more memory than a 32-bit JVM for the same task.

SQL SERVER: Get total days between two dates

See DateDiff:

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

How to get textLabel of selected row in swift?

In swift 4 : by overriding method

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let storyboard = UIStoryboard(name : "Main", bundle: nil)
        let next vc = storyboard.instantiateViewController(withIdentifier: "nextvcIdentifier") as! NextViewController

       self.navigationController?.pushViewController(prayerVC, animated: true)
}

iOS 7: UITableView shows under status bar

chappjc's answer works great when working with XIBs.

I found the cleanest solution when creating TableViewControllers programmatically is by wrapping the UITableViewController instance in another UIViewController and setting constraints accordingly.

Here it is:

UIViewController *containerLeftViewController = [[UIViewController alloc] init];
UITableViewController *tableViewController = [[UITableViewController alloc] init];

containerLeftViewController.view.backgroundColor = [UIColor redColor];

hostsAndMoreTableViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
[containerLeftViewController.view addSubview:tableViewController.view];

[containerLeftViewController addChildViewController:tableViewController];
[tableViewController didMoveToParentViewController:containerLeftViewController];

NSDictionary * viewsDict = @{ @"tableView": tableViewController.view ,
                              @"topGuide": containerLeftViewController.topLayoutGuide,
                              @"bottomGuide": containerLeftViewController.bottomLayoutGuide,
                              };
[containerLeftViewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tableView]|"
                                                                                         options:0
                                                                                         metrics:nil
                                                                                           views:viewsDict]];
[containerLeftViewController.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topGuide][tableView][bottomGuide]"
                                                                                         options:0
                                                                                         metrics:nil
                                                                                           views:viewsDict]];

Cheers, Ben

How to differ sessions in browser-tabs?

Another approach that works is to create a unique window id and store this value along with the session id in a database table. The window id I often use is integer(now). This value is created when a window is opened and re-assigned to the same window if the window is refreshed, reloaded or submitted to itself. Window values (inputs) are saved in the local table using the link. When a value is required, it is obtained from the database table based on the window id / session id link. While this approach requires a local database, it is virtually foolproof. The use of a database table was easy for me, but I see no reason why local arrays would not work just as well.