Programs & Examples On #Singular

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Using Java generics for JPA findAll() query with WHERE clause

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Singular matrix issue with Numpy

Use SVD or QR-decomposition to calculate exact solution in real or complex number fields:

numpy.linalg.svd numpy.linalg.qr

Uncaught ReferenceError: jQuery is not defined

jQuery needs to be the first script you import. The first script on your page

<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>

appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

"Invalid form control" only in Google Chrome

It will show that message if you have code like this:

<form>
  <div style="display: none;">
    <input name="test" type="text" required/>
  </div>

  <input type="submit"/>
</form>

solution to this problem will depend on how the site should work

for example if you don't want the form to submit unless this field is required you should disable the submit button

so the js code to show the div should enable the submit button as well

you can hide the button too (should be disabled and hidden because if it's hidden but not disabled the user can submit the form with others way like press enter in any other field but if the button is disabled this won't happen

if you want the form to submit if the div is hidden you should disable any required input inside it and enable the inputs while you are showing the div

if someone need the codes to do so you should tell me exactly what you need

REST URI convention - Singular or plural name of resource while creating it

I don't see the point in doing this either and I think it is not the best URI design. As a user of a RESTful service I'd expect the list resource to have the same name no matter whether I access the list or specific resource 'in' the list. You should use the same identifiers no matter whether you want use the list resource or a specific resource.

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

What are naming conventions for MongoDB?

Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id.

For example, in a dogs collection, a document would have manual references to external documents named like this:

{
  name: 'fido',
  owner_id: '5358e4249611f4a65e3068ab',
  race_id: '5358ee549611f4a65e3068ac',
  colour: 'yellow'
  ...
}

This follows the Mongo convention of naming _id the identifier for every document.

CSS3 Box Shadow on Top, Left, and Right Only

It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.

#servicesContainer {
  /*your css*/
  position: relative;
}

and it's fixed! like magic!

How to check if a word is an English word with Python?

For All Linux/Unix Users

If your OS uses the Linux kernel, there is a simple way to get all the words from the English/American dictionary. In the directory /usr/share/dict you have a words file. There is also a more specific american-english and british-english files. These contain all of the words in that specific language. You can access this throughout every programming language which is why I thought you might want to know about this.

Now, for python specific users, the python code below should assign the list words to have the value of every single word:

import re
file = open("/usr/share/dict/words", "r")
words = re.sub("[^\w]", " ",  file.read()).split()

def is_word(word):
    return word.lower() in words

is_word("tarts") ## Returns true
is_word("jwiefjiojrfiorj") ## Returns False

Hope this helps!!!

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

PHP json_decode() returns NULL with valid JSON?

Maybe some hidden characters are messing with your json, try this:

$json = utf8_encode($yourString);
$data = json_decode($json);

Flash CS4 refuses to let go

What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.

Enum Naming Convention - Plural

Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0. It makes more sense to say Version.1_0 since there is only one 1_0 Version.

Simple 3x3 matrix inverse code (C++)

A rather nice (I think) header file containing macros for most 2x2, 3x3 and 4x4 matrix operations has been available with most OpenGL toolkits. Not as standard but I've seen it at various places.

You can check it out here. At the end of it you will find both inverse of 2x2, 3x3 and 4x4.

vvector.h

Get int value from enum in C#

You can do this by implementing an extension method to your defined enum type:

public static class MyExtensions
{
    public static int getNumberValue(this Question questionThis)
    {
        return (int)questionThis;
    }
}

This simplifies getting the int value of the current enum value:

Question question = Question.Role;
int value = question.getNumberValue();

or

int value = Question.Role.getNumberValue();

How to properly create an SVN tag from trunk?

Just use this:

svn  copy  http://svn.example.com/project/trunk  
           http://svn.example.com/project/branches/release-1
           -m  "branch for release 1.0"

(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.

See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2

Table Naming Dilemma: Singular vs. Plural Names

The system tables/views of the server itself (SYSCAT.TABLES, dbo.sysindexes, ALL_TABLES, information_schema.columns, etc.) are almost always plural. I guess for the sake of consistency I'd follow their lead.

Database, Table and Column Naming Conventions?

I think the best answer to each of those questions would be given by you and your team. It's far more important to have a naming convention then how exactly the naming convention is.

As there's no right answer to that, you should take some time (but not too much) and choose your own conventions and - here's the important part - stick to it.

Of course it's good to seek some information about standards on that, which is what you're asking, but don't get anxious or worried about the number of different answers you might get: choose the one that seems better for you.

Just in case, here are my answers:

  1. Yes. A table is a group of records, teachers or actors, so... plural.
  2. Yes.
  3. I don't use them.
  4. The database I use more often - Firebird - keeps everything in upper case, so it doesn't matter. Anyway, when I'm programming I write the names in a way that it's easier to read, like releaseYear.

Python 2: AttributeError: 'list' object has no attribute 'strip'

You split the string entry of the list. l[0].strip()

Stacking DIVs on top of each other?

Position the outer div however you want, then position the inner divs using absolute. They'll all stack up.

_x000D_
_x000D_
.inner {_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="outer">_x000D_
   <div class="inner">1</div>_x000D_
   <div class="inner">2</div>_x000D_
   <div class="inner">3</div>_x000D_
   <div class="inner">4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java Desktop application: SWT vs. Swing

Pros Swing:

  • part of java library, no need for additional native libraries
  • works the same way on all platforms
  • Integrated GUI Editor in Netbeans and Eclipse
  • good online tutorials by Sun/Oracle
  • Supported by official java extensions (like java OpenGL)

Cons Swing:

  • Native look and feel may behave different from the real native system.
  • heavy components (native/awt) hide swing components, not a problem most of the time as as use of heavy components is rather rare

Pros SWT:

  • uses native elements when possible, so always native behavior
  • supported by eclipse, gui editor VEP (VEP also supports Swing and AWT)
  • large number of examples online
  • has an integrated awt/swt bridge to allow use of awt and swing components

Cons SWT:

  • requires native libraries for each supported system
  • may not support every behavior on all systems because of native resources used (hint options)
  • managing native resources, while native components will often be disposed with their parent other resources such as Fonts have to be manually released or registered as dispose listener to a component for automatic release.

ADB - Android - Getting the name of the current activity

You can use this command,

adb shell dumpsys activity

You can find current activity name in activity stack.

Output :-

 Sticky broadcasts:
 * Sticky action android.intent.action.BATTERY_CHANGED:
   Intent: act=android.intent.action.BATTERY_CHANGED flg=0x60000000
     Bundle[{icon-small=17302169, present=true, scale=100, level=50, technology=Li-ion, status=2, voltage=0, plugged=1, health=2, temperature=0}]
 * Sticky action android.net.thrott.THROTTLE_ACTION:
   Intent: act=android.net.thrott.THROTTLE_ACTION
     Bundle[{level=-1}]
 * Sticky action android.intent.action.NETWORK_SET_TIMEZONE:
   Intent: act=android.intent.action.NETWORK_SET_TIMEZONE flg=0x20000000
     Bundle[mParcelledData.dataSize=68]
 * Sticky action android.provider.Telephony.SPN_STRINGS_UPDATED:
   Intent: act=android.provider.Telephony.SPN_STRINGS_UPDATED flg=0x20000000
     Bundle[mParcelledData.dataSize=156]
 * Sticky action android.net.thrott.POLL_ACTION:
   Intent: act=android.net.thrott.POLL_ACTION
     Bundle[{cycleRead=0, cycleStart=1349893800000, cycleEnd=1352572200000, cycleWrite=0}]
 * Sticky action android.intent.action.SIM_STATE_CHANGED:
   Intent: act=android.intent.action.SIM_STATE_CHANGED flg=0x20000000
     Bundle[mParcelledData.dataSize=116]
 * Sticky action android.intent.action.SIG_STR:
   Intent: act=android.intent.action.SIG_STR flg=0x20000000
     Bundle[{EvdoSnr=-1, CdmaDbm=-1, GsmBitErrorRate=-1, CdmaEcio=-1, EvdoDbm=-1, GsmSignalStrength=7, EvdoEcio=-1, isGsm=true}]
 * Sticky action android.intent.action.SERVICE_STATE:
   Intent: act=android.intent.action.SERVICE_STATE flg=0x20000000
     Bundle[{cdmaRoamingIndicator=0, operator-numeric=310260, networkId=0, state=0, emergencyOnly=false, operator-alpha-short=Android, radioTechnology=3, manual=false, cssIndicator=false, operator-alpha-long=Android, systemId=0, roaming=false, cdmaDefaultRoamingIndicator=0}]
 * Sticky action android.net.conn.CONNECTIVITY_CHANGE:
   Intent: act=android.net.conn.CONNECTIVITY_CHANGE flg=0x30000000
     Bundle[{networkInfo=NetworkInfo: type: mobile[UMTS], state: CONNECTED/CONNECTED, reason: simLoaded, extra: internet, roaming: false, failover: false, isAvailable: true, reason=simLoaded, extraInfo=internet}]
 * Sticky action android.intent.action.NETWORK_SET_TIME:
   Intent: act=android.intent.action.NETWORK_SET_TIME flg=0x20000000
     Bundle[mParcelledData.dataSize=36]
 * Sticky action android.media.RINGER_MODE_CHANGED:
   Intent: act=android.media.RINGER_MODE_CHANGED flg=0x70000000
     Bundle[{android.media.EXTRA_RINGER_MODE=2}]
 * Sticky action android.intent.action.ANY_DATA_STATE:
   Intent: act=android.intent.action.ANY_DATA_STATE flg=0x20000000
     Bundle[{state=CONNECTED, apnType=*, iface=/dev/omap_csmi_tty1, apn=internet, reason=simLoaded}]

 Activity stack:
 * TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
   clearOnBackground=false numActivities=2 rootWasReset=false
   affinity=org.chanakyastocktipps.com
   intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.chanakyastocktipps.com/.ui.SplashScreen}
   realActivity=org.chanakyastocktipps.com/.ui.SplashScreen
   lastActiveTime=15107753 (inactive for 4879s)
   * Hist #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.Profile }
       frontOfTask=false task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.Profile
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       resultTo=HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen} resultWho=null resultCode=4
       launchFailed=false haveState=false icicle=null
       state=RESUMED stopped=false delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=true frozenBeforeDestroy=false thumbnailNeeded=false idle=true
       waitingVisible=false nowVisible=true
   * Hist #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.MainScreen }
       frontOfTask=true task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.MainScreen
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=1344]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true
 * TaskRecord{450615a0 #2 A com.android.launcher}
   clearOnBackground=true numActivities=1 rootWasReset=false
   affinity=com.android.launcher
   intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher}
   realActivity=com.android.launcher/com.android.launcher2.Launcher
   lastActiveTime=12263090 (inactive for 7724s)
   * Hist #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}
       packageName=com.android.launcher processName=com.android.launcher
       launchedFromUid=0 app=ProcessRecord{45062558 129:com.android.launcher/10025}
       Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher }
       frontOfTask=true task=TaskRecord{450615a0 #2 A com.android.launcher}
       taskAffinity=com.android.launcher
       realActivity=com.android.launcher/com.android.launcher2.Launcher
       base=/system/app/Launcher2.apk/system/app/Launcher2.apk data=/data/data/com.android.launcher
       labelRes=0x7f0c0002 icon=0x7f020044 theme=0x7f0d0000
       stateNotNeeded=true componentSpecified=false isHomeActivity=true
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=3608]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=2
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true

 Running activities (most recent first):
   TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
     Run #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
     Run #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
   TaskRecord{450615a0 #2 A com.android.launcher}
     Run #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}

 mPausingActivity: null
 mResumedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mFocusedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mLastPausedActivity: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}

 mCurTask: 22

 Running processes (most recent first):
   App  #13: adj=vis  /F 45052120 119:com.android.inputmethod.latin/10003 (service)
             com.android.inputmethod.latin.LatinIME<=ProcessRecord{44ec2698 59:system/1000}
   PERS #12: adj=sys  /F 44ec2698 59:system/1000 (fixed)
   App  #11: adj=fore /F 44fa3450 1065:org.chanakyastocktipps.com/10046 (top-activity)
   App  #10: adj=bak  /B 44e7c4c0 299:com.svox.pico/10028 (bg-empty)
   App  # 9: adj=bak+1/B 450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057 (bg-empty)
   App  # 8: adj=bak+2/B 4503cc38 201:com.android.defcontainer/10010 (bg-empty)
   App  # 7: adj=home /B 45062558 129:com.android.launcher/10025 (home)
   App  # 6: adj=bak+3/B 450244d8 276:android.process.media/10002 (bg-empty)
   App  # 5: adj=bak+4/B 44f2b9b8 263:com.android.quicksearchbox/10012 (bg-empty)
   App  # 4: adj=bak+5/B 450beec0 257:com.android.protips/10007 (bg-empty)
   App  # 3: adj=bak+6/B 44ff37b8 270:com.android.music/10022 (bg-empty)
   PERS # 2: adj=core /F 45056818 124:com.android.phone/1001 (fixed)
   App  # 1: adj=bak+7/B 45080c38 238:com.dreamreminder.org/10057 (bg-empty)
   App  # 0: adj=empty/B 4507d030 229:com.android.email/10030 (bg-empty)

 PID mappings:
   PID #59: ProcessRecord{44ec2698 59:system/1000}
   PID #119: ProcessRecord{45052120 119:com.android.inputmethod.latin/10003}
   PID #124: ProcessRecord{45056818 124:com.android.phone/1001}
   PID #129: ProcessRecord{45062558 129:com.android.launcher/10025}
   PID #201: ProcessRecord{4503cc38 201:com.android.defcontainer/10010}
   PID #229: ProcessRecord{4507d030 229:com.android.email/10030}
   PID #238: ProcessRecord{45080c38 238:com.dreamreminder.org/10057}
   PID #257: ProcessRecord{450beec0 257:com.android.protips/10007}
   PID #263: ProcessRecord{44f2b9b8 263:com.android.quicksearchbox/10012}
   PID #270: ProcessRecord{44ff37b8 270:com.android.music/10022}
   PID #276: ProcessRecord{450244d8 276:android.process.media/10002}
   PID #288: ProcessRecord{450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057}
   PID #299: ProcessRecord{44e7c4c0 299:com.svox.pico/10028}
   PID #1065: ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}

 mHomeProcess: ProcessRecord{45062558 129:com.android.launcher/10025}
 mConfiguration: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
 mConfigWillChange: false
 mSleeping=false mShuttingDown=false

Is there a CSS parent selector?

The CSS selector “General Sibling Combinator” could maybe used for what you want:

E ~ F {
    property: value;
}

This matches any F element that is preceded by an E element.

Select a Column in SQL not in Group By

The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.

So, you need an alternative approach.

1). Take you current query and join the base data back on it

SELECT
  cpe.*
FROM
  Filteredfmgcms_claimpaymentestimate cpe
INNER JOIN
  (yourQuery) AS lookup
    ON  lookup.MaxData           = cpe.createdOn
    AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid

2). Use a CTE to do it all in one go...

WITH
  sequenced_data AS
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
  FROM
    Filteredfmgcms_claimpaymentestimate
  WHERE
    createdon < 'reportstartdate'
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

NOTE: Using ROW_NUMBER() will ensure just one record per fmgcms_cpeclaimid. Even if multiple records are tied with the exact same createdon value. If you can have ties, and want all records with the same createdon value, use RANK() instead.

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

Clear data in MySQL table with PHP?

TRUNCATE TABLE tablename

or

DELETE FROM tablename

The first one is usually the better choice, as DELETE FROM is slow on InnoDB.

Actually, wasn't this already answered in your other question?

How to get back Lost phpMyAdmin Password, XAMPP

Unless you have changed your password the default setting dont require you to enter a password to connect to the MYSQL server, try:

mysql_connect('localhost','root','');

if not then you can export your databases to a external file, just follow these instructions.

http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html

if you are unable to access phpMyAdmin then try,

http://www.simplehelp.net/2008/11/26/how-to-reset-a-lost-mysql-root-password/

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

How do I obtain crash-data from my Android application?

Now a days Firebase Crash reports are very popular and easier to use. Please refer following link for more information: Firebase Crash Reporting

Hope it will help you.

Browser detection

if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
} 
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    { 
        DoSomething(); 
    }
    ...
}
else { }

How do I use FileSystemObject in VBA?

In excel 2013 the object creation string is:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

instead of the code in the answer above:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

How can I pull from remote Git repository and override the changes in my local repository?

As an addendum, if you want to reapply your changes on top of the remote, you can also try:

git pull --rebase origin master

If you then want to undo some of your changes (but perhaps not all of them) you can use:

git reset SHA_HASH

Then do some adjustment and recommit.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

In our case, the wrong version of the Sysdeo Tomcat plugin for Eclipse 3.5 was being used. The fix:

  • Use tomcatPluginV33 instead of tomcatPluginV321 (extract to C:\eclipse\dropins)
  • Ensure that DevloaderTomcat7.jar was placed in the tomcat lib folder
  • In Window > Preferences > Tomcat, set the Tomcat version to 7.x

This problem may have been unique to our environment; but, I'll record it here anyway, for posterity's sake.

Multiple try codes in one block

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

Android camera intent

try this code

Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

Which websocket library to use with Node.js?

Update: This answer is outdated as newer versions of libraries mentioned are released since then.

Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.

"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.

See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539

How to remove specific element from an array using python

If you want to delete the index of array:

Use array_name.pop(index_no.)

ex:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

If you want to delete a particular string/element from the array then

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']

What's the difference between a word and byte?

Whatever the terminology present in datasheets and compilers, a 'Byte' is eight bits. Let's not try to confuse enquirers and generalities with the more obscure exceptions, particularly as the word 'Byte' comes from the expression "By Eight". I've worked in the semiconductor/electronics industry for over thirty years and not once known 'Byte' used to express anything more than eight bits.

How to make a button redirect to another page using jQuery or just Javascript

This should work ..

$('#buttonID').click(function(){ window.location = 'new url'});

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

Best way to center a <div> on a page vertically and horizontally?

The best and most flexible way

My demo on dabblet.com

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).

This trick will work with any sizes of div.

_x000D_
_x000D_
div {_x000D_
 width: 100px;_x000D_
 height: 100px;_x000D_
 background-color: red;_x000D_
 _x000D_
 position: absolute;_x000D_
 top:0;_x000D_
 bottom: 0;_x000D_
 left: 0;_x000D_
 right: 0;_x000D_
   _x000D_
 margin: auto;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Reimport a module in python while interactive

Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

# Python >= 3.5
import importlib
import types


def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))
    importlib.reload(module)


walk_reload(my_module)

The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

After installing SQL Server 2014 Express can't find local db

I have noticed that after installation of SQL server 2012 express on Windows 10 you must install ENU\x64\SqlLocalDB.MSI from official Microsoft download site. After that, you could run SqlLocalDB.exe.

Checking if a variable is defined?

Try "unless" instead of "if"

a = "apple"
# Note that b is not declared
c = nil

unless defined? a
    puts "a is not defined"
end

unless defined? b
    puts "b is not defined"
end

unless defined? c
    puts "c is not defined"
end

Swift 3 - Comparing Date objects

SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.

func checkTimeStamp(date: String!) -> Bool {
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = Locale(identifier:"en_US_POSIX")
        let datecomponents = dateFormatter.date(from: date)

        let now = Date()

        if (datecomponents! >= now) {
            return true
        } else {
            return false
        }
    }

To use it:

if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
    // Do something
}

python max function using 'key' and lambda expression

How does the max function work?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

What is use of the keyword key in max function? I know it is also used in context of sort function

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Meaning of the lambda expression? How to read them? How do they work?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

Need to remove href values when printing in Chrome

_x000D_
_x000D_
@media print {_x000D_
   a[href]:after {_x000D_
      display: none;_x000D_
      visibility: hidden;_x000D_
   }_x000D_
}
_x000D_
_x000D_
_x000D_

Work's perfect.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Pythonic way to create a long multi-line string

This approach uses:

  • almost no internal punctuation by using a triple quoted string
  • strips away local indentation using the inspect module
  • uses Python 3.6 formatted string interpolation ('f') for the account_id and def_id variables.

This way looks the most Pythonic to me.

import inspect

query = inspect.cleandoc(f'''
    SELECT action.descr as "action",
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id={account_id} AND
    def_id={def_id}'''
)

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :

RewriteEngine on

RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]

The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .

To exclude all existent directries, you will need to use the following condition above your rule :

RewriteCond %{REQUEST_FILENAME} !-d

the following rule

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]

rewrites everything (except directries) to /index.php .

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library" - or whatever version is appropriate.

This code works for me:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}

Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!

Some other links that I found useful when looking into this question:

According to MSDN

To use COM interop, you must have administrator or Power User security permissions.

Hope that helps.

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

jQuery AJAX submit form

I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:

$('form#foo').submit(function () {
    $.ajax({
        url: 'http://foo.bar/some-ajax-script',
        type: 'POST',
        dataType: 'json',
        data: {
            'foo': 'some-foo-value',
            'bar': $('#bar').val()
        }
    }).always(function (response) {
        console.log(response);
    });

    return false;
});

Then, in the backend:

// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar

How to fill a Javascript object literal with many static key/value pairs efficiently?

It works fine with the object literal notation:

var map = { key : { "aaa", "rrr" }, 
            key2: { "bbb", "ppp" } // trailing comma leads to syntax error in IE!
          }

Btw, the common way to instantiate arrays

var array = [];
// directly with values:
var array = [ "val1", "val2", 3 /*numbers may be unquoted*/, 5, "val5" ];

and objects

var object = {};

Also you can do either:

obj.property     // this is prefered but you can also do
obj["property"]  // this is the way to go when you have the keyname stored in a var

var key = "property";
obj[key] // is the same like obj.property

How to configure CORS in a Spring Boot + Spring Security application?

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*").allowedMethods("*");
            }
        };
    }

How can I create an Asynchronous function in Javascript?

Function.prototype.applyAsync = function(params, cb){
      var function_context = this;
      setTimeout(function(){
          var val = function_context.apply(undefined, params); 
          if(cb) cb(val);
      }, 0);
}

// usage
var double = function(n){return 2*n;};
var display = function(){console.log(arguments); return undefined;};
double.applyAsync([3], display);

Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:

  • it allows for parameters to the functions
  • it passes the output of the function to the callback
  • it is added to Function.prototype allowing a nicer way to call it

Also, the similarity to the built-in function Function.prototype.apply seems appropriate to me.

How to bind Events on Ajax loaded Content?

If your ajax response are containing html form inputs for instance, than this would be great:

$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) { 
if (this.value == 'Yes') {
  // do something here
} else if (this.value == 'No') {
  // do something else here.
} else {
   console.log('The new input field from an ajax response has this value: '+ this.value);
}

});

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====          
Class<?>    reference           =   vector.get(0).getClass();
Object      obj                 =   reference.newInstance();
Field[]     objFields           =   obj.getClass().getFields(); 

Facebook Access Token for Pages

  1. Go to the Graph API Explorer
  2. Choose your app from the dropdown menu
  3. Click "Get Access Token"
  4. Choose the manage_pages permission (you may need the user_events permission too, not sure)
  5. Now access the me/accounts connection and copy your page's access_token
  6. Click on your page's id
  7. Add the page's access_token to the GET fields
  8. Call the connection you want (e.g.: PAGE_ID/events)

How can I create a simple index.html file which lists all files/directories?

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

tree

tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree, mac: brew install tree, windows: zip) and which can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 > index.html

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files. -L 1 limits the listing to the current directory only.

Generator script with recursive traversal

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html file in all the nested subdirectories.

Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified times and is more responsive in mobile viewports.

How to check if a json key exists?

just before read key check it like before read

JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
  //it's contain value to be read operation
}
else
{
  //it's not contain key club or isnull so do this operation here
}

isNull function definition

Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL. 

official documentation below link for isNull function

http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I know it's quite old questions and many persons has answered. but I am summarizing the things for understanding:

If the file extension is xls and OS is 32 bit then only you can use "Microsoft.Jet.OLEDB.4.0". Microsoft has not released 64 bit version of this driver.

If file extension is xlsx or OS is 64 bit then you must have to use "Microsoft.ACE.OLEDB.12.0". The application compiled in 32/64 bit mode does not impact the selection of driver.

Always install the 64 bit driver of Microsoft.ACE.OLEDB.12.0 on OS 64 bit. If you have already installed Office 32 bit then you need to run driver from cmd with /passive argument. This hack works till Office 2013 only, Microsoft stopped this workaround from Office 2016 for Microsoft.ACE.OLEDB.16.0 drivers.

AccessDatabaseEngine_x64.exe /passive

Download drivers Microsoft.ACE.OLEDB.12.0

private void ProcessFile(string path)
{
    string connString = string.Empty;

    if (Path.GetExtension(path).ToLower().Trim() == ".xls" && Environment.Is64BitOperatingSystem == false)
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
    else
        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}

If Application is compiled with AnyCPU flag, it will look for 64 bit Access drivers on 64 bit OS and 32 bit access drivers on 32 bit OS.

Entity Framework vs LINQ to SQL

I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables:

Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing.

How can I get the IP address from NIC in Python?

try below code, it works for me in Mac10.10.2:

import subprocess

if __name__ == "__main__":
    result = subprocess.check_output('ifconfig en0 |grep -w inet', shell=True) # you may need to use eth0 instead of en0 here!!!
    print 'output = %s' % result.strip()
    # result = None
    ip = ''
    if result:
        strs = result.split('\n')
        for line in strs:
            # remove \t, space...
            line = line.strip()
            if line.startswith('inet '):
                a = line.find(' ')
                ipStart = a+1
                ipEnd = line.find(' ', ipStart)
                if a != -1 and ipEnd != -1:
                    ip = line[ipStart:ipEnd]
                    break
    print 'ip = %s' % ip

Hex-encoded String to Byte Array

try this:

     String str = "9B7D2C34A366BF890C730641E6CECF6F";
     String[] temp = str.split(",");
     bytesArray = new byte[temp.length];
     int index = 0;
     for (String item: temp) {
     bytesArray[index] = Byte.parseByte(item);
     index++;
     }

Cross-browser window resize event - JavaScript / jQuery

jQuery provides $(window).resize() function by default:

<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
    $rightPanelData = $( '.rightPanelData' )
    $leftPanelData = $( '.leftPanelData' );

//jQuery window resize call/event
$window.resize(function resizeScreen() {
    // console.log('window is resizing');

    // here I am resizing my div class height
    $rightPanelData.css( 'height', $window.height() - 166 );
    $leftPanelData.css ( 'height', $window.height() - 236 );
});
</script> 

Set time to 00:00:00

If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".

Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));

//Result is: Current Date: 29-10-2018 00:00:00

CSS technique for a horizontal line with words in the middle

For me this solution works perfectly fine...

HTML

<h2 class="strikethough"><span>Testing Text</span></h2>

CSS

.strikethough {
 width:100%; 
 text-align:left; 
 border-bottom: 1px solid #bcbcbc; 
 overflow: inherit;
 margin:0px 0 30px;
 font-size: 16px;
 color:#757575;
 }
.strikethough span {
 background:#fff; 
 padding:0 20px 0px 0px;
 position: relative;
 top: 10px;
}

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

angular 2 ngIf and CSS transition/animation

According to the latest angular 2 documentation you can animate "Entering and Leaving" elements (like in angular 1).

Example of simple fade animation:

In relevant @Component add:

animations: [
  trigger('fadeInOut', [
    transition(':enter', [   // :enter is alias to 'void => *'
      style({opacity:0}),
      animate(500, style({opacity:1})) 
    ]),
    transition(':leave', [   // :leave is alias to '* => void'
      animate(500, style({opacity:0})) 
    ])
  ])
]

Do not forget to add imports

import {style, state, animate, transition, trigger} from '@angular/animations';

The relevant component's html's element should look like:

<div *ngIf="toggle" [@fadeInOut]>element</div>

I built example of slide and fade animation here.

Explanation on 'void' and '*':

  • void is the state when ngIf is set to false (it applies when the element is not attached to a view).
  • * - There can be many animation states (read more in docs). The * state takes precedence over all of them as a "wildcard" (in my example this is the state when ngIf is set to true).

Notice (taken from angular docs):

Extra declare inside the app module, import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it. For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

The server committed a protocol violation. Section=ResponseStatusLine ERROR

One way to debug this (and to make sure it is the protocol violation that is causing the problem), is to use Fiddler (Http Web Proxy) and see if the same error occurs. If it doesn't (i.e. Fiddler handled the issue for you) then you should be able to fix it using the UseUnsafeHeaderParsing flag.

If you are looking for a way to set this value programatically see the examples here: http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/

Change Bootstrap tooltip color

my jQuery fix:

HTML:

   <a href="#" data-toggle="tooltip" data-placement="right" data-original-title="some text">
       <span class="glyphicon glyphicon-question-sign"></span>
   </a>

jQuery:

$('[data-toggle="tooltip"]').hover(function(){
    $('.tooltip-inner').css('min-width', '400px');
    $('.tooltip-inner').css('color', 'red');
});

What are best practices for multi-language database design?

I'm using next approach:

Product

ProductID OrderID,...

ProductInfo

ProductID Title Name LanguageID

Language

LanguageID Name Culture,....

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

Tools to search for strings inside files without indexing

There is also a Windows built-in program called findstr.exe with which you can search within files.

>findstr /s "provider=sqloledb" *.cs

How to iterate over the file in python

You should learn about EAFP vs LBYL.

from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
    if isinstance(infile, basestring):
        infile=open(infile,'r')
    if isinstance(outfile, basestring):
        outfile=open(outfile,'w')
    for lineno, line in enumerate(infile, 1):
        line = line.strip()
         try:
             print >>outfile, int(line,16)
         except ValueError:
             return "Bad value at line %i: %r" % (lineno, line)

if __name__ == "__main__":
    from sys import argv, exit
    exit(main(*argv[1:]))

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

Git cli: get user info from username

While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:

To see a list of all users in a git repo using the git cli:

git log --format="%an %ae" | sort | uniq

To search for a specific user by name, e.g., "John":

git log --format="%an %ae" | sort | uniq | grep -i john

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

Pandas dataframe fillna() only some columns in place

using the top answer produces a warning about making changes to a copy of a df slice. Assuming that you have other columns, a better way to do this is to pass a dictionary:
df.fillna({'A': 'NA', 'B': 'NA'}, inplace=True)

Change the mouse cursor on mouse over to anchor-like style

Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):

CSS to Add

#myDiv
{
    cursor: pointer;
}

You can simply add the cursor style to your div's HTML like this:

<div style="cursor: pointer">

</div>

EDIT:

If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)

$('.myClass').css('cursor', 'pointer');

Change Row background color based on cell value DataTable

OK I was able to solve this myself:

$(document).ready(function() {
  $('#tid_css').DataTable({
    "iDisplayLength": 100,
    "bFilter": false,
    "aaSorting": [
      [2, "desc"]
    ],
    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
      if (aData[2] == "5") {
        $('td', nRow).css('background-color', 'Red');
      } else if (aData[2] == "4") {
        $('td', nRow).css('background-color', 'Orange');
      }
    }
  });
})

Prevent redirect after form is submitted

Instead of return false, you could try event.preventDefault(); like this:

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

How can I make SQL case sensitive string comparison on MySQL?

To make use of an index before using the BINARY, you could do something like this if you have large tables.

SELECT
   *
FROM
   (SELECT * FROM `table` WHERE `column` = 'value') as firstresult
WHERE
   BINARY `column` = 'value'

The subquery would result in a really small case-insensitive subset of which you then select the only case-sensitive match.

g++ undefined reference to typeinfo

One possible reason is because you are declaring a virtual function without defining it.

When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).

An example of defining the virtual function is:

virtual void fn() { /* insert code here */ }

In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.

The line

virtual void fn();

declares fn() without defining it and will cause the error message you asked about.

It's very similar to the code:

extern int i;
int *pi = &i;

which states that the integer i is declared in another compilation unit which must be resolved at link time (otherwise pi can't be set to it's address).

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

How to input matrix (2D list) in Python?

you can accept a 2D list in python this way ...

simply

arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows


for characters

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())
print(a)

or

n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
    a[i].append(list(input().strip()))
print(a)

for numbers

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]
print(a)

where n is no of elements in columns while m is no of elements in a row.

In pythonic way, this will create a list of list

Targeting .NET Framework 4.5 via Visual Studio 2010

There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).

  1. Backup your project file!!!

  2. Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.

  3. Open your project in VS2010.

  4. Create a text file in your project named Compile_4_5_CSharp.targets with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):

    <Project DefaultTargets="Build"
     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
        <!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
        <PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
            <DefineConstants Condition="'$(DefineConstants)'==''">
                TARGETTING_FX_4_5
            </DefineConstants>
            <DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
                $(DefineConstants);TARGETTING_FX_4_5
            </DefineConstants>
            <PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
            <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
        </PropertyGroup>
    
        <!-- Import the standard C# targets -->
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
    
        <!-- Add .NET 4.5 as an available platform -->
        <PropertyGroup>
           <AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
        </PropertyGroup>
    </Project>
    
  5. Unload your project (right click -> unload).

  6. Edit the project file (right click -> Edit *.csproj).

  7. Make the following changes in the project file:

    a. Replace the default Microsoft.CSharp.targets with the target file created in step 4

    <!-- Old Import Entry -->
    <!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
    
    <!-- New Import Entry -->
    <Import Project="Compile_4_5_CSharp.targets" />
    

    b. Change the default platform to .NET 4.5

    <!-- Old default platform entry -->
    <!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
    
    <!-- New default platform entry -->
    <Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
    

    c. Add AnyCPU platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup> tag in the file

    <PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
    
    .
    .
    .
    <ItemGroup>
    .
    .
    .
    
  8. Save your changes and close the *.csproj file.

  9. Reload your project (right click -> Reload Project).

  10. In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.

  11. Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.

  12. Build your project and check for errors.

  13. Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:

    using System;
    using System.Text;
    
    namespace testing
    {
        using net45check = System.Reflection.ReflectionContext;
    }
    
  14. When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:

    Error 6: The type or namespace name 'ReflectionContext' does not exist in
    the namespace 'System.Reflection' (are you missing an assembly reference?)
    

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Converting Swagger specification JSON to HTML documentation

Everything was too difficult or badly documented so I solved this with a simple script swagger-yaml-to-html.py, which works like this

python swagger-yaml-to-html.py < /path/to/api.yaml > doc.html

This is for YAML but modifying it to work with JSON is also trivial.

Responding with a JSON object in Node.js (converting object/array to JSON string)

Using res.json with Express:

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

Alternatively:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

MySQL Trigger after update only if row has changed

I cant comment, so just beware, that if your column supports NULL values, OLD.x<>NEW.x isnt enough, because

SELECT IF(1<>NULL,1,0)

returns 0 as same as

NULL<>NULL 1<>NULL 0<>NULL 'AAA'<>NULL

So it will not track changes FROM and TO NULL

The correct way in this scenario is

((OLD.x IS NULL AND NEW.x IS NOT NULL) OR (OLD.x IS NOT NULL AND NEW.x IS NULL) OR (OLD.x<>NEW.x))

The identity used to sign the executable is no longer valid

This may happen when your certificate expire in your Key Chain.

EDIT : I'd now recommand cert and sigh to generate your certificates and provisionning profiles. These are two commands part of the fastlane tools from KrauseFx.

Using cert & sigh:

  1. Open a terminal and type cert
  2. Answer the prompted questions to sect your user, password, team, app, etc.
  3. Open a terminal and type sigh
  4. Answer the prompted questions to sect your user, password, team, app, etc.
  5. Select the right profile in Code Signing Identity (iPhone Developer)

Conventional way:

  1. Just go to the new provisioning portal : Certificates, Identifier, Profiles
  2. Login with your developer account.
  3. Go to Certificates and click the Plus button.
  4. Then select iOS Apps Development and click Continue.
  5. Follow the whole process and download the newly generated certificate.
  6. Download it and put it in your keychain.
  7. Update your profiles from XCode Organizer devices window
  8. Select the right profile in Code Signing Identity (iPhone Developer)

Python Flask, how to set content type

As simple as this

x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}

Hope it helps

Update: Use this method because it will work with both python 2.x and python 3.x

and secondly it also eliminates multiple header problem.

from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads:

  • singleton
  • session (or request)
  • thread pool of jobs

The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request.

Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case).


I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore?

How can I develop for iPhone using a Windows development machine?

(accurate as of late 2014)

For access to the native tools (Xcode etc) there are two main options:

1. Virtual machine

Look around for the mavericks (10.9) vmware image that works with a modified Vmware Workstation/Player. Once the machine is able to boot, it can be updated to 10.9.5 with no apparent issues.

The good: relatively low learning curve (if you are somewhat familiar with vms)

The bad: reduced performance due to virtualized environment, no 3d acceleration (QE/CL)

2. Hackintosh

This is the sensible option if you are planning to procure new hardware (or at least partly), instead of retrofitting existing equipment (but you might be lucky to have one of the common OEM models (like Dell) that already have recipes written for it)

The good: no penalty on hardware performance, which might even surpass that of a real mac. The same hardware can also be used for other OSes if you are open to multibooting

The bad: higher learning curve, more hardware limitations (no drivers for certain Intel wifi etc) which may translate into higher investment if you had no intention to get new hardware originally

Needless to say, both options above are frown upon by the fruit company, so licensing compliance is not part of the discussion.

3. An actual mac (added in 2016)

This option is perfect for people who already have a mac and use it as a Windows development machine via Bootcamp etc. This also has the least support issues (apart from complications that may result from multi-booting), so it is recommended for those looking for a long-term solution (hardware that works not just for the current OSX version but future versions as well)

AngularJS ng-if with multiple conditions

OR operator:

<div ng-repeat="k in items">
    <div ng-if="k || 'a' or k == 'b'">
        <!-- SOME CONTENT -->
    </div>
</div>

Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..

For Example:

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin || group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Another OR example

<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>

AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin && group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

When to use self over $this?

Here is a small benchmark (7.2.24 on repl.it):

            Speed (in seconds)  Percentage
$this->     0.91760206222534    100
self::      1.0047659873962     109.49909865716
static::    0.98066782951355    106.87288857386

Results for 4 000 000 runs. Conclusion: it doesn't matter. And here is the code I used:

<?php

class Foo
{
  public function calling_this() { $this->called(); }
  public function calling_self() { self::called(); }
  public function calling_static() { static::called(); }
  public static function called() {}
}

$foo = new Foo();
$n = 4000000;
$times = [];

// warmup
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_this(); }
$times["this"] = microtime(true)-$start;

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_self(); }
$times["self"] = microtime(true)-$start;

$start = microtime(true);
for ($i = 0; $i < $n; $i++) { $foo->calling_static(); }
$times["static"] = microtime(true)-$start;

$min = min($times);
echo $times["this"] . "\t" . ($times["this"] / $min)*100 . "\n";
echo $times["self"] . "\t" . ($times["self"] / $min)*100 . "\n";
echo $times["static"] . "\t" . ($times["static"] / $min)*100 . "\n";

Setting up an MS-Access DB for multi-user access

The correct way of building client/server Microsoft Access applications where the data is stored in a RDBMS is to use the Linked Table method. This ensures Data Isolation and Concurrency is maintained between the Microsoft Access client application and the RDBMS data with no additional and unnecessary programming logic and code which makes maintenance more difficult, and adds to development time.

see: http://claysql.blogspot.com/2014/08/normal-0-false-false-false-en-us-x-none.html

Query-string encoding of a Javascript Object

A small amendment to the accepted solution by user187291:

serialize = function(obj) {
   var str = [];
   for(var p in obj){
       if (obj.hasOwnProperty(p)) {
           str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
       }
   }
   return str.join("&");
}

Checking for hasOwnProperty on the object makes JSLint/JSHint happy, and it prevents accidentally serializing methods of the object or other stuff if the object is anything but a simple dictionary. See the paragraph on for statements in this page: http://javascript.crockford.com/code.html

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

Generating an MD5 checksum of a file

In Python 3.8+ you can do

import hashlib
with open("your_filename.txt", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippet). It's cryptographically secure and faster than MD5.

Can't install Scipy through pip

For Windows 10

C:\directory> pip install scipy-0.19.0rc2-cp35-cp35m-win_amd64.whl

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

REMOTE_ADDR can not be trusted.

Anyway, try

$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
    $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}

Edit: Also, does your server's router have port forwarding enabled? It may be possible that it's messing with the packets.

Security warning: REMOTE_ADDR can be fully trusted! It comes from your own webserver and contains the IP that was used to access it. You don't even need to quote() it for SQL inserts.
But HTTP_X_FORWARDED_FOR is taken directly from the HTTP headers, it can contain the picture of a cat, malicious code, any content. Treat it like that, never trust it.

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I got this error, but mine was coming from the Toasts, not a Dialog.

I have Activity and Fragments in my layout. Code for the Toast was in the Activity class. Fragments gets loaded before the Activity.

I think the Toast code was hit before the Context/Activity finished initializing. I think it was the getApplicationContext() in the command Toast.makeText(getApplicationContext(), "onMenutItemActionCollapse called", Toast.LENGTH_SHORT).show();

MVVM Passing EventArgs As Command Parameter

It's not easily supported. Here's an article with instructions on how to pass EventArgs as command parameters.

You might want to look into using MVVMLight - it supports EventArgs in command directly; your situation would look something like this:

 <i:Interaction.Triggers>
    <i:EventTrigger EventName="Navigated">
        <cmd:EventToCommand Command="{Binding NavigatedEvent}"
            PassEventArgsToCommand="True" />
    </i:EventTrigger>
 </i:Interaction.Triggers>

Change Twitter Bootstrap Tooltip content on click

This works if the tooltip has been instantiated (possibly with javascript):

$("#tooltip_id").data('tooltip').options.title="New_value!";
$("#tooltip_id").tooltip('hide').tooltip('show');

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

Creating Dynamic button with click event in JavaScript

<!DOCTYPE html>
<html>
<body>

<p>Click the button to make a BUTTON element with text.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var btn = document.createElement("BUTTON");
    var t = document.createTextNode("CLICK ME");

    btn.setAttribute("style","color:red;font-size:23px");

    btn.appendChild(t);
    document.body.appendChild(btn);

    btn.setAttribute("onclick", alert("clicked"));

}
</script>

</body>
</html>

Angularjs - display current date

View

<div ng-app="myapp">
{{AssignedDate.now() | date:'yyyy-MM-dd HH:mm:ss'}}
</div>

Controller

var app = angular.module('myapp',[])

app.run(function($rootScope){
    $rootScope.AssignedDate = Date;
})

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

How to set env variable in Jupyter notebook

If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook with export VARIABLE=value in .bashrc.

In my case tensorflow needs the exported variable for successful importing it in a notebook.

Including .cpp files

This boils down to a difference between definitions and declarations.

  • You can declare functions and variables multiple times, in different translation units, or in the same translation unit. Once you declare a function or a variable, you can use it from that point on.
  • You can define a non-static function or a variable only once in all of your translation units. Defining non-static items more than once causes linker errors.

Headers generally contain declarations; cpp files contain definitions. When you include a file with definitions more than once, you get duplicates during linking.

In your situation one defintion comes from foo.cpp, and the other definition comes from main.cpp, which includes foo.cpp.

Note: if you change foo to be static, you would have no linking errors. Despite the lack of errors, this is not a good thing to do.

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

Why is Tkinter Entry's get function returning nothing?

you need to put a textvariable in it, so you can use set() and get() method :

var=StringVar()
x= Entry (root,textvariable=var)

intelliJ IDEA 13 error: please select Android SDK

there is a button by name android monitor on the left bottom of the screen. if u have an issue with sdk it will show u confugure link.Change the path to your sdk folder. things will work

When do we need curly braces around shell variables?

Variables are declared and assigned without $ and without {}. You have to use

var=10

to assign. In order to read from the variable (in other words, 'expand' the variable), you must use $.

$var      # use the variable
${var}    # same as above
${var}bar # expand var, and append "bar" too
$varbar   # same as ${varbar}, i.e expand a variable called varbar, if it exists.

This has confused me sometimes - in other languages we refer to the variable in the same way, regardless of whether it's on the left or right of an assignment. But shell-scripting is different, $var=10 doesn't do what you might think it does!

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

How do I set the maximum line length in PyCharm?

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Pycharm 4 Settings Screenshot

Sort matrix according to first column in R

Be aware that if you want to have values in the reverse order, you can easily do so:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

How to make overlay control above all other controls?

Put the control you want to bring to front at the end of your xaml code. I.e.

<Grid>
  <TabControl ...>
  </TabControl>
  <Button Content="ALways on top of TabControl Button"/>
</Grid>

Shortcut key for commenting out lines of Python code in Spyder

on Windows F9 to run single line

Select the lines which you want to run on console and press F9 button for multi line

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

Why is my Button text forced to ALL CAPS on Lollipop?

Add android:textAllCaps="false" in <Button> tag that's it.

What does "Error: object '<myvariable>' not found" mean?

I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.

Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!

Hope to help

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

PHP - Debugging Curl

Another (crude) option is to utilize netcat for dumping the full request:

nc -l -p 8000 -w 3 | tee curldbg.txt

And of course sending the failing request to it:

curl_setup(CURLOPT_URL, "http://localhost/testytest");

Notably that will always hang+fail, since netcat won't ever construct a valid HTTP response. It's really just for inspecting what really got sent. The better option, of course, is using a http request debugging service.

Implicit function declarations in C

C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.

In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.

Of course, when you try to link, and it can't find foo, then you will get an error.

In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.

What is a Question Mark "?" and Colon ":" Operator Used for?

Thats an if/else statement equilavent to

if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

How to display my application's errors in JSF?

FacesContext.addMessage(String, FacesMessage) requires the component's clientId, not it's id. If you're wondering why, think about having a control as a child of a dataTable, stamping out different values with the same control for each row - it would be possible to have a different message printed for each row. The id is always the same; the clientId is unique per row.

So "myform:mybutton" is the correct value, but hard-coding this is ill-advised. A lookup would create less coupling between the view and the business logic and would be an approach that works in more restrictive environments like portlets.

<f:view>
  <h:form>
    <h:commandButton id="mybutton" value="click"
      binding="#{showMessageAction.mybutton}"
      action="#{showMessageAction.validatePassword}" />
    <h:message for="mybutton" />
  </h:form>
</f:view>

Managed bean logic:

/** Must be request scope for binding */
public class ShowMessageAction {

    private UIComponent mybutton;

    private boolean isOK = false;

    public String validatePassword() {
        if (isOK) {
            return "ok";
        }
        else {
            // invalid
            FacesMessage message = new FacesMessage("Invalid password length");
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(mybutton.getClientId(context), message);
        }
        return null;
    }

    public void setMybutton(UIComponent mybutton) {
        this.mybutton = mybutton;
    }

    public UIComponent getMybutton() {
        return mybutton;
    }
}

ImportError: No module named dateutil.parser

I had the similar problem. This is the stack trace:

Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module> import awscli.clidriver
File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 17, in <module> import botocore.session
File "/usr/local/lib/python2.7/dist-packages/botocore/session.py", line 30, in <module> import botocore.credentials
File "/usr/local/lib/python2.7/dist-packages/botocore/credentials.py", line 27, in <module> from dateutil.parser import parse
ImportError: No module named dateutil.parser

I tried to (re-)install dateutil.parser through all possible ways. It was unsuccessful.

I solved it with

pip3 uninstall awscli
pip3 install awscli

Are parameters in strings.xml possible?

There is many ways to use it and i recomend you to see this documentation about String Format.

http://developer.android.com/intl/pt-br/reference/java/util/Formatter.html

But, if you need only one variable, you'll need to use %[type] where [type] could be any Flag (see Flag types inside site above). (i.e. "My name is %s" or to set my name UPPERCASE, use this "My name is %S")

<string name="welcome_messages">Hello, %1$S! You have %2$d new message(s) and your quote is %3$.2f%%.</string>

Hello, ANDROID! You have 1 new message(s) and your quote is 80,50%.

How to remove all line breaks from a string

The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Real escape string and PDO

You should use PDO Prepare

From the link:

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.

If you want to allow a user to upload a file via a form, you must use this enctype.

How do I change select2 box height

Lazy solution I found here https://github.com/panorama-ed/maximize-select2-height

maximize-select2-height

This package is short and simple. It magically expands your Select2 dropdowns to fill the height of the window.

It factors in the number of elements in the dropdown, the position of the Select2 on the page, the size and scroll position of the page, the visibility of scroll bars, and whether the dropdown is rendered upwards or downwards. And it resizes itself each time the dropdown is opened. And minified, it's ~800 bytes (including comments)!

(Note that this plugin is built for Select2 v4.x.x only.)

$("#my-dropdown").select2().maximizeSelect2Height();

Enjoy!

How to sort ArrayList<Long> in decreasing order?

You can use the following code which is given below;

Collections.sort(list, Collections.reverseOrder());

or if you are going to use custom comparator you can use as it is given below

Collections.sort(list, Collections.reverseOrder(new CustomComparator());

Where CustomComparator is a comparator class that compares the object which is present in the list.

How to implement the factory method pattern in C++ correctly

You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus

The best solution is on the "comments and discussions", see the "No need for static Create methods".

From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.

#ifndef FACTORY_H
#define FACTORY_H

#include <QMap>
#include <QString>

template <typename T>
class Factory
{
public:
    template <typename TDerived>
    void registerType(QString name)
    {
        static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
        _createFuncs[name] = &createFunc<TDerived>;
    }

    T* create(QString name) {
        typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
        if (it != _createFuncs.end()) {
            return it.value()();
        }
        return nullptr;
    }

private:
    template <typename TDerived>
    static T* createFunc()
    {
        return new TDerived();
    }

    typedef T* (*PCreateFunc)();
    QMap<QString,PCreateFunc> _createFuncs;
};

#endif // FACTORY_H

Sample usage:

Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");

What is lexical scope?

Lexical scope refers to the lexicon of identifiers (e.g., variables, functions, etc.) visible from the current position in the execution stack.

- global execution context
    - foo
    - bar
    - function1 execution context
        - foo2
        - bar2
        - function2 execution context
            - foo3
            - bar3

foo and bar are always within the lexicon of available identifiers because they are global.

When function1 is executed, it has access to a lexicon of foo2, bar2, foo, and bar.

When function2 is executed, it has access to a lexicon of foo3, bar3, foo2, bar2, foo, and bar.

The reason global and/or outer functions do not have access to an inner functions identifiers is because the execution of that function has not occurred yet and therefore, none of its identifiers have been allocated to memory. What’s more, once that inner context executes, it is removed from the execution stack, meaning that all of it’s identifiers have been garbage collected and are no longer available.

Finally, this is why a nested execution context can ALWAYS access it’s ancestors execution context and thus why it has access to a greater lexicon of identifiers.

See:

Special thanks to @robr3rd for help simplifying the above definition.

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

How to rename uploaded file before saving it into a directory?

/* create new name file */
$filename   = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension  = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename   = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg

$source       = $_FILES["file"]["tmp_name"];
$destination  = "../img/imageDirectory/{$basename}";

/* move the file */
move_uploaded_file( $source, $destination );

echo "Stored in: {$destination}";

Prevent flex items from overflowing a container

I know this is really late, but for me, I found that applying flex-basis: 0; to the element prevented it from overflowing.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

Microsoft.ReportViewer.Common Version=12.0.0.0

Issue

Parser Error Message: Could not load file or assembly 'Microsoft.ReportViewer.WebForms / Winforms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Cause

Microsoft ReportViewer runtime and SQL CLR Types for SQL Server 2014 is required to run and is missing from the server hosting Internet Information Services (IIS) or your application.

Resolution

Install the following packages on the IIS server and then restart the system:

Download Microsoft ReportViewer runtime

Download Microsoft SQL CLR types for SQL Server 2014

Once restarted connect to Web service / Your app again and verify that the error has been resolved.

Or you cant follow this link to read more.

How can I create a progress bar in Excel VBA?

Sub ShowProgress()
' Author    : Marecki
  Const x As Long = 150000
  Dim i&, PB$

  For i = 1 To x
    PB = Format(i / x, "00 %")
    Application.StatusBar = "Progress: " & PB & "  >>" & String(Val(PB), Chr(183)) & String(100 - Val(PB), Chr(32)) & "<<"
    Application.StatusBar = "Progress: " & PB & "  " & ChrW$(10111 - Val(PB) / 11)
    Application.StatusBar = "Progress: " & PB & "  " & String(100 - Val(PB), ChrW$(9608))
  Next i

  Application.StatusBar = ""
End SubShowProgress

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.

enter image description here

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

How to call python script on excel vba?

There are a couple of ways to solve this problem

Pyinx - a pretty lightweight tool that allows you to call Python from withing the excel process space http://code.google.com/p/pyinex/

I've used this one a few years ago (back when it was being actively developed) and it worked quite well

If you don't mind paying, this looks pretty good

https://datanitro.com/product.html

I've never used it though


Though if you are already writting in Python, maybe you could drop excel entirely and do everything in pure python? It's a lot easier to maintain one code base (python) rather than 2 (python + whatever excel overlay you have).

If you really have to output your data into excel there are even some pretty good tools for that in Python. If that may work better let me know and I'll get the links.

jQuery click event not working after adding class

Since the class is added dynamically, you need to use event delegation to register the event handler

$(document).on('click', "a.tabclick", function() {
    var liId = $(this).parent("li").attr("id");
    alert(liId);        
});

How to remove foreign key constraint in sql server?

ALTER TABLE [TableName] DROP CONSTRAINT [CONSTRAINT_NAME]

But, be careful man, once you do that, you may never get a chance back, and you should read some basic database book see why we need foreign key

How to add content to html body using JS?

You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

Git commit in terminal opens VIM, but can't get back to terminal

Simply doing the vim "save and quit" command :wq should do the trick.

In order to have Git open it in another editor, you need to change the Git core.editor setting to a command which runs the editor you want.

git config --global core.editor "command to start sublime text 2"

Grunt watch error - Waiting...Fatal error: watch ENOSPC

To find out who's making inotify instances, try this command (source):

for foo in /proc/*/fd/*; do readlink -f $foo; done | grep inotify | sort | uniq -c | sort -nr

Mine looked like this:

 25 /proc/2857/fd/anon_inode:inotify
  9 /proc/2880/fd/anon_inode:inotify
  4 /proc/1375/fd/anon_inode:inotify
  3 /proc/1851/fd/anon_inode:inotify
  2 /proc/2611/fd/anon_inode:inotify
  2 /proc/2414/fd/anon_inode:inotify
  1 /proc/2992/fd/anon_inode:inotify

Using ps -p 2857, I was able to identify process 2857 as sublime_text. Only after closing all sublime windows was I able to run my node script.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

You can't use a condition to change the structure of your query, just the data involved. You could do this:

update table set
    columnx = (case when condition then 25 else columnx end),
    columny = (case when condition then columny else 25 end)

This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.

The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.

Javascript switch vs. if...else if...else

  1. If there is a difference, it'll never be large enough to be noticed.
  2. N/A
  3. No, they all function identically.

Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.

Centering a canvas

Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

Center canvas to middle of the screen or parent element. No wrapping.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}

Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}

Works like a charm - tested: firefox, chrome

fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

if statements matching multiple values

Generally, no.

Yes, there are cases where the list is in an Array or List, but that's not the general case.

How do I center a Bootstrap div with a 'spanX' class?

Define the width as 960px, or whatever you prefer, and you're good to go!

#main {
 margin: 0 auto !important;
 float: none !important;
 text-align: center;
 width: 960px;
}

(I couldn't figure this out until I fixed the width, nothing else worked.)

How to Git stash pop specific stash in 1.8.3?

If none of the above work, quotation marks around the stash itself might work for you:

git stash pop "stash@{0}"

Swipe ListView item From right to left show delete button

I used to have the same problem finding a good library to do that. Eventually, I created a library which can do that: SwipeRevealLayout

In gradle file:

dependencies {
    compile 'com.chauthai.swipereveallayout:swipe-reveal-layout:1.4.0'
}

In your xml file:

<com.chauthai.swipereveallayout.SwipeRevealLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:mode="same_level"
    app:dragEdge="left">

    <!-- Your secondary layout here -->
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

    <!-- Your main layout here -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.chauthai.swipereveallayout.SwipeRevealLayout>

Then in your adapter file:

public class Adapter extends RecyclerView.Adapter {
  // This object helps you save/restore the open/close state of each view
  private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();

  @Override
  public void onBindViewHolder(ViewHolder holder, int position) {
    // get your data object first.
    YourDataObject dataObject = mDataSet.get(position); 

    // Save/restore the open/close state.
    // You need to provide a String id which uniquely defines the data object.
    viewBinderHelper.bind(holder.swipeRevealLayout, dataObject.getId()); 

    // do your regular binding stuff here
  }
}

Pandas - How to flatten a hierarchical index in columns

I'll share a straight-forward way that worked for me.

[" ".join([str(elem) for elem in tup]) for tup in df.columns.tolist()]
#df = df.reset_index() if needed

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

Change Text Color of Selected Option in a Select Box

Try this:

_x000D_
_x000D_
.greenText{ background-color:green; }_x000D_
_x000D_
.blueText{ background-color:blue; }_x000D_
_x000D_
.redText{ background-color:red; }
_x000D_
<select_x000D_
    onchange="this.className=this.options[this.selectedIndex].className"_x000D_
    class="greenText">_x000D_
     <option class="greenText" value="apple" >Apple</option>_x000D_
    <option class="redText"   value="banana" >Banana</option>_x000D_
    <option class="blueText" value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

Bind event to right mouse click

.contextmenu method :-

Try as follows

<div id="wrap">Right click</div>

<script>
$('#wrap').contextmenu(function() {
  alert("Right click");
});
</script>

.mousedown method:-

$('#wrap').mousedown(function(event) {

        if(event.which == 3){
            alert('Right Mouse button pressed.');
        }  
});

How to check if an integer is within a range of numbers in PHP?

$ranges = [
    1 => [
        'min_range' => 0.01,
        'max_range' => 199.99
    ],
    2 => [
        'min_range' => 200.00,
    ],
];

   foreach( $ranges as $value => $range ){
        if( filter_var( $cartTotal, FILTER_VALIDATE_FLOAT, [ 'options' => $range ] ) ){
            return $value;
        }
    }

How to exit an if clause

(This method works for ifs, multiple nested loops and other constructs that you can't break from easily.)

Wrap the code in its own function. Instead of break, use return.

Example:

def some_function():
    if condition_a:
        # do something and return early
        ...
        return
    ...
    if condition_b:
        # do something else and return early
        ...
        return
    ...
    return

if outer_condition:
    ...
    some_function()
    ...

Installing Python library from WHL file

First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.

If pip is not installed, and you are using Windows: How to install pip on Windows?

How to search for a string inside an array of strings

It's faster to avoid using regular expressions, if you're just trying to find the first substring match within an array of string values. You can add your own array searching function:

Code:

Array.prototype.findFirstSubstring = function(s) {
            for(var i = 0; i < this.length;i++)
            {
                if(this[i].indexOf(s) !== -1)
                    return i;
            }
            return -1;
        };

Usage:

i.findFirstSubstring('height');

Returns:

-1 if not found or the array index of the first substring occurrence if it is found (in your case would be 2)

MySQL vs MongoDB 1000 reads

https://github.com/reoxey/benchmark

benchmark

speed comparison of MySQL & MongoDB in GOLANG1.6 & PHP5

system used for benchmark: DELL cpu i5 4th gen 1.70Ghz * 4 ram 4GB GPU ram 2GB

Speed comparison of RDBMS vs NoSQL for INSERT, SELECT, UPDATE, DELETE executing different number of rows 10,100,1000,10000,100000,1000000

Language used to execute is: PHP5 & Google fastest language GO 1.6

________________________________________________
GOLANG with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            INSERT
------------------------------------------------
num of rows             time taken
------------------------------------------------
10                      1.195444ms
100                     6.075053ms
1000                    47.439699ms
10000                   483.999809ms
100000                  4.707089053s
1000000                 49.067407174s


            SELECT
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 872.709µs


        SELECT & DISPLAY
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 20.717354746s


            UPDATE
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 2.309209968s
100000                  257.411502ms
10000                   26.73954ms
1000                    3.483926ms
100                     915.17µs
10                      650.166µs


            DELETE
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 6.065949ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


________________________________________________
GOLANG with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            INSERT
------------------------------------------------
num of rows             time taken
------------------------------------------------
10                      2.067094ms
100                     8.841597ms
1000                    106.491732ms
10000                   998.225023ms
100000                  8.98172825s
1000000                 1m 29.63203158s


            SELECT
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 5.251337439s


        FIND & DISPLAY (with index declared)
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 21.540603252s


            UPDATE
------------------------------------------------
num of rows             time taken
------------------------------------------------
1                       1.330954ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

________________________________________________
PHP5 with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            INSERT
------------------------------------------------
num of rows             time taken
------------------------------------------------
 10                     0.0040680000000001s
 100                    0.011595s
 1000                   0.049718s
 10000                  0.457164s
 100000                 4s
 1000000                42s


            SELECT
------------------------------------------------
num of rows             time taken
------------------------------------------------
 1000000                <1s


            SELECT & DISPLAY
------------------------------------------------
num of rows             time taken
------------------------------------------------
  1000000               20s
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

________________________________________________
PHP5 with MongoDB 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            INSERT
------------------------------------------------
num of rows             time taken
------------------------------------------------
10                      0.065744s
100                     0.190966s
1000                    0.2163s
10000                   1s
100000                  8s
1000000                 78s


            FIND
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 <1s


            FIND & DISPLAY
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 7s


            UPDATE
------------------------------------------------
num of rows             time taken
------------------------------------------------
1000000                 9s

ORA-28000: the account is locked error getting frequently

I have faced this similar issue and resolved it by using following steps :

  1. Open windows command prompt.
  2. Login using the command sqlplus "/ as sysdba"
  3. Then executed the command alter user HR identified by password account unlock

    Please note, the password is the password that I have used.

    By using above steps you can connect to Oracle Database as user HR with the password password.

System.IO.IOException: file used by another process

After creating a file you must force the stream to release the resources:

//FSm is stream for creating file on a path//
System.IO.FileStream FS = new System.IO.FileStream(path + fname,
                                                   System.IO.FileMode.Create);
pro.CopyTo(FS);
FS.Dispose();

Better way to sort array in descending order

Use LINQ OrderByDescending method. It returns IOrderedIEnumerable<int>, which you can convert back to Array if you need so. Generally, List<>s are more functional then Arrays.

array = array.OrderByDescending(c => c).ToArray();

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

Injecting Mockito mocks into a Spring bean

Update - new answer here: https://stackoverflow.com/a/19454282/411229. This answer only applies to those on Spring versions before 3.2.

I've looked for a while for a more definitive solution to this. This blog post seems to cover all my needs and doesn't rely on ordering of bean declarations. All credit to Mattias Severson. http://www.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/

Basically, implement a FactoryBean

package com.jayway.springmock;

import org.mockito.Mockito;
import org.springframework.beans.factory.FactoryBean;

/**
 * A {@link FactoryBean} for creating mocked beans based on Mockito so that they 
 * can be {@link @Autowired} into Spring test configurations.
 *
 * @author Mattias Severson, Jayway
 *
 * @see FactoryBean
 * @see org.mockito.Mockito
 */
public class MockitoFactoryBean<T> implements FactoryBean<T> {

    private Class<T> classToBeMocked;

    /**
     * Creates a Mockito mock instance of the provided class.
     * @param classToBeMocked The class to be mocked.
     */
    public MockitoFactoryBean(Class<T> classToBeMocked) {
        this.classToBeMocked = classToBeMocked;
    }

    @Override
    public T getObject() throws Exception {
        return Mockito.mock(classToBeMocked);
    }

    @Override
    public Class<?> getObjectType() {
        return classToBeMocked;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

Next update your spring config with the following:

<beans...>
    <context:component-scan base-package="com.jayway.example"/>

    <bean id="someDependencyMock" class="com.jayway.springmock.MockitoFactoryBean">
        <constructor-arg name="classToBeMocked" value="com.jayway.example.SomeDependency" />
    </bean>
</beans>

How to draw checkbox or tick mark in GitHub Markdown table?

|checked|unchecked|crossed|
|---|---|---|
|&check;|_|&cross;|

Where

? via HTML Entity Code
? via HTML Entity Code
_ via underscore character
and table via markdown table syntax.

What characters are valid for JavaScript variable names?

From the ECMAScript specification in section 7.6 Identifier Names and Identifiers, a valid identifier is defined as:

Identifier :: 
    IdentifierName but not ReservedWord

IdentifierName :: 
    IdentifierStart 
    IdentifierName IdentifierPart 

IdentifierStart :: 
    UnicodeLetter 
    $ 
    _ 
    \ UnicodeEscapeSequence 

IdentifierPart :: 
    IdentifierStart 
    UnicodeCombiningMark 
    UnicodeDigit 
    UnicodeConnectorPunctuation 
    \ UnicodeEscapeSequence 

UnicodeLetter 
    any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, 
    “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”. 

UnicodeCombiningMark 
    any character in the Unicode categories “Non-spacing mark (Mn)” or “Combining spacing mark (Mc)” 

UnicodeDigit 
    any character in the Unicode category “Decimal number (Nd)” 

UnicodeConnectorPunctuation 
    any character in the Unicode category “Connector punctuation (Pc)” 

UnicodeEscapeSequence 
    see 7.8.4. 

HexDigit :: one of 
    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

which creates a lot of opportunities for naming variables and also in golfing. Let's try some examples.

A valid identifier could start with either a UnicodeLetter, $, _, or \ UnicodeEscapeSequence. A unicode letter is any character from these categories (see all categories):

  • Uppercase letter (Lu)
  • Lowercase letter (Ll)
  • Titlecase letter (Lt)
  • Modifier letter (Lm)
  • Other letter (Lo)
  • Letter number (Nl)

This alone accounts for some crazy possibilities - working examples. If it doesn't work in all browsers, then call it a bug, cause it should.

var ? = "something";
var HELLO = "hello";
var ???? = "less than? wtf";
var ????????????? = "javascript"; // ok that's JavaScript in hindi
var KingGeorge? = "Roman numerals, awesome!";

How to getText on an input in protractor

You can try something like this

var access_token = driver.findElement(webdriver.By.name("AccToken"))

        var access_token_getTextFunction = function() {
            access_token.getText().then(function(value) {
                console.log(value);
                return value;
            });
        }

Than you can call this function where you want to get the value..

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

on Kate

Ctrl + Shift + B also allows you to add more columns by simply clicking anywhere and paste it.

I used this when saving text files I copied from Google Translate as a side-by-side view.

Force browser to clear cache

Do you want to clear the cache, or just make sure your current (changed?) page is not cached?

If the latter, it should be as simple as

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

When setting the curl options for CURLOPT_CAINFO please remember to use single quotes, using double quotes will only cause another error. So your option should look like:

curl_setopt ($ch, CURLOPT_CAINFO, 'c:\wamp\www\mywebfolder\cacert.pem');

Additionally, in your php.ini file setting should be written as:(notice my double quotes)

curl.cainfo = "C:\wamp\www\mywebfolder"

I put it directly below the line that says this: extension=php_curl.dll

(For organizing purposes only, you could put it anywhere within your php.ini, i just put it close to another curl reference so when I search using keyword curl I caan find both curl references in one area.)

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Linux supports capabilities to support more fine-grained permissions than just "this application is run as root". One of those capabilities is CAP_NET_BIND_SERVICE which is about binding to a privileged port (<1024).

Unfortunately I don't know how to exploit that to run an application as non-root while still giving it CAP_NET_BIND_SERVICE (probably using setcap, but there's bound to be an existing solution for this).

Get java.nio.file.Path object from java.io.File

From the documentation:

Paths associated with the default provider are generally interoperable with the java.io.File class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by java.io.File. The toPath method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the java.io.File object. In addition, the toFile method is useful to construct a File from the String representation of a Path.

(emphasis mine)

So, for toFile:

Returns a File object representing this path.

And toPath:

Returns a java.nio.file.Path object constructed from the this abstract path.

How to get index using LINQ?

I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:

public static class Extensions
{
    public static int IndexOf<T>(
            this IEnumerable<T> list, 
            Predicate<T> condition) {               
        int i = -1;
        return list.Any(x => { i++; return condition(x); }) ? i : -1;
    }
}

void Main()
{
    TestGetsFirstItem();
    TestGetsLastItem();
    TestGetsMinusOneOnNotFound();
    TestGetsMiddleItem();   
    TestGetsMinusOneOnEmptyList();
}

void TestGetsFirstItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("a"));

    // Assert
    if(index != 0)
    {
        throw new Exception("Index should be 0 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsLastItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("d"));

    // Assert
    if(index != 3)
    {
        throw new Exception("Index should be 3 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnNotFound()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnEmptyList()
{
    // Arrange
    var list = new string[] {  };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMiddleItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d", "e" };

    // Act
    int index = list.IndexOf(item => item.Equals("c"));

    // Assert
    if(index != 2)
    {
        throw new Exception("Index should be 2 but is: " + index);
    }

    "Test Successful".Dump();
}        

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

How do I get a PHP class constructor to call its parent's parent's constructor?

I agree with "too much php", try this:

class Grandpa 
{
    public function __construct()
    {
        echo 'Grandpa<br/>';
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        echo 'Papa<br/>';
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        // THIS IS WHERE I NEED TO CALL GRANDPA'S
        // CONSTRUCTOR AND NOT PAPA'S
        echo 'Kiddo<br/>';
        Grandpa::__construct();
    }
}

$instance = new Kiddo;

I got the result as expected:

Kiddo

Grandpa

This is a feature not a bug, check this for your reference:

https://bugs.php.net/bug.php?id=42016

It is just the way it works. If it sees it is coming from the right context this call version does not enforce a static call.

Instead it will simply keep $this and be happy with it.

parent::method() works in the same way, you don't have to define the method as static but it can be called in the same context. Try this out for more interesting:

class Grandpa 
{
    public function __construct()
    {
        echo 'Grandpa<br/>';
        Kiddo::hello();
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        echo 'Papa<br/>';
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        // THIS IS WHERE I NEED TO CALL GRANDPA'S
        // CONSTRUCTOR AND NOT PAPA'S
        echo 'Kiddo<br/>';
        Grandpa::__construct();
    }

    public function hello()
    {
        echo 'Hello<br/>';
    }
}

$instance = new Kiddo;

It also works as expected:

Kiddo

Grandpa

Hello

But if you try to initialize a new Papa, you will get an E_STRICT error:

$papa = new Papa;

Strict standards: Non-static method Kiddo::hello() should not be called statically, assuming $this from incompatible context

You can use instanceof to determine if you can call a Children::method() in a parent method:

if ($this instanceof Kiddo) Kiddo::hello();

Fastest way to convert JavaScript NodeList to Array?

faster and shorter :

// nl is the nodelist
var a=[], l=nl.length>>>0;
for( ; l--; a[l]=nl[l] );

How to change an application icon programmatically in Android?

Try this solution

<activity android:name=".SplashActivity"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity-alias android:label="ShortCut"
        android:icon="@drawable/ic_short_cut"
        android:name=".SplashActivityAlias"
        android:enabled="false"
        android:targetActivity=".SplashActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Add the following code when you want to change your app icon

PackageManager pm = getPackageManager();
                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivity"),
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

                    pm.setComponentEnabledSetting(
                            new ComponentName(YourActivity.this,
                                    "your_package_name.SplashActivityAlias"),
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP);

linq query to return distinct field values from a list of objects

I wanted to bind a particular data to dropdown and it should be distinct. I did the following:

List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

Change header background color of modal of twitter bootstrap

So, I tried these other ways, but there was a VERY slight irritant and that was if you keep the modal-content border radius, in FF and Chrome, there is a slight bit of white trim showing along the borders, even if you use 5px on the modal-header border radius. (standard modal-content border radius is 6px, so 5px on the modal-header border top radius covers some white).

My solution:

.modal-body
{
    background-color: #FFFFFF;
}

.modal-content
{
    border-radius: 6px;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    background-color: transparent;
}

.modal-footer
{
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    -webkit-border-bottom-left-radius: 6px;
    -webkit-border-bottom-right-radius: 6px;
    -moz-border-radius-bottomleft: 6px;
    -moz-border-radius-bottomright: 6px;
}

.modal-header
{
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
}

!! CAVEAT !!

You must then set the background colors of the modal-header, modal-content, and modal-footer. This is not bad trade-off, because it allows you to do this:

<div class="modal-header bg-primary">

<div class="modal-body bgColorWhite">

<div class="modal-footer bg-info">

EDIT

Or even better:

<div class="modal-header alert-primary">

What's the proper way to "go get" a private repository?

If you've already got git using SSH, this answer by Ammar Bandukwala is a simple workaround:


$ go get uses git internally. The following one liners will make git and consequently $ go get clone your package via SSH.

Github:

$ git config --global url."[email protected]:".insteadOf "https://github.com/"

BitBucket:

$ git config --global url."[email protected]:".insteadOf "https://bitbucket.org/"

Push existing project into Github

Create a new repository

git clone <url>
cd "repositoryName"
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

Existing folder

cd existing_folder
git init
git remote add origin <url>
git add .
git commit -m "Initial commit"
git push -u origin master

Existing Git repository

cd existing_repo
git remote rename origin old-origin
git remote add origin <url>
git push -u origin --all
git push -u origin --tags

Laravel: How to Get Current Route Name? (v5 ... v7)

I have used for getting route name in larvel 5.3

Request::path()

Extract first item of each sublist

lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
    outputlist.append(values[0])

print(outputlist) 

Output: ['a', 1, 'x']

Best way to find the intersection of multiple sets?

Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

Guido might dislike reduce, but I'm kind of fond of it :)

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Are HTTPS headers encrypted?

With SSL the encryption is at the transport level, so it takes place before a request is sent.

So everything in the request is encrypted.