Programs & Examples On #C# 2.0

For issues unique to development in C#, version 2.0

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

How to use LogonUser properly to impersonate domain user from workgroup client

I have been successfull at impersonating users in another domain, but only with a trust set up between the 2 domains.

var token = IntPtr.Zero;
var result = LogonUser(userID, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (result)
{
    return WindowsIdentity.Impersonate(token);
}

Get Max value from List<myType>

Simplest is actually just Age.Max(), you don't need any more code.

Changing the row height of a datagridview

You can set the row height by code

dataGridView.RowTemplate.Height = 35;

or by property panel

enter image description here

How to filter keys of an object with lodash?

Just change filter to omitBy

_x000D_
_x000D_
const data = { aaa: 111, abb: 222, bbb: 333 };_x000D_
const result = _.omitBy(data, (value, key) => !key.startsWith("a"));_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Get current date in milliseconds

As mentioned before, [[NSDate date] timeIntervalSince1970] returns an NSTimeInterval, which is a duration in seconds, not milli-seconds.

You can visit https://currentmillis.com/ to see how you can get in the language you desire. Here is the list -

ActionScript    (new Date()).time
C++ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()
C#.NET  DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
Clojure (System/currentTimeMillis)
Excel / Google Sheets*  = (NOW() - CELL_WITH_TIMEZONE_OFFSET_IN_HOURS/24 - DATE(1970,1,1)) * 86400000
Go / Golang time.Now().UnixNano() / 1000000
Hive*   unix_timestamp() * 1000
Java / Groovy / Kotlin  System.currentTimeMillis()
Javascript  new Date().getTime()
MySQL*  UNIX_TIMESTAMP() * 1000
Objective-C (long long)([[NSDate date] timeIntervalSince1970] * 1000.0)
OCaml   (1000.0 *. Unix.gettimeofday ())
Oracle PL/SQL*  SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) * 24 * 60 * 60 * 1000 FROM DUAL
Perl    use Time::HiRes qw(gettimeofday); print gettimeofday;
PHP round(microtime(true) * 1000)
PostgreSQL  extract(epoch FROM now()) * 1000
Python  int(round(time.time() * 1000))
Qt  QDateTime::currentMSecsSinceEpoch()
R*  as.numeric(Sys.time()) * 1000
Ruby    (Time.now.to_f * 1000).floor
Scala   val timestamp: Long = System.currentTimeMillis
SQL Server  DATEDIFF(ms, '1970-01-01 00:00:00', GETUTCDATE())
SQLite* STRFTIME('%s', 'now') * 1000
Swift*  let currentTime = NSDate().timeIntervalSince1970 * 1000
VBScript / ASP  offsetInMillis = 60000 * GetTimeZoneOffset()
WScript.Echo DateDiff("s", "01/01/1970 00:00:00", Now()) * 1000 - offsetInMillis + Timer * 1000 mod 1000

For objective C I did something like below to print it -

long long mills = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);
 NSLog(@"Current date %lld", mills);

Hopw this helps.

How to test that a registered variable is not empty?

when: myvar | default('', true) | trim != ''

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

How to prevent ENTER keypress to submit a web form?

If none of those answers are working for you, try this. Add a submit button before the one that actually submits the form and just do nothing with the event.

HTML

<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>

JavaScript

$('#EnterKeyIntercepter').click((event) => {
    event.preventDefault(); //The buck stops here.
    /*If you don't know what this if statement does, just delete it.*/
    if (process.env.NODE_ENV !== 'production') {
        console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (¬¦_¦)");
    }
});

How to make sure docker's time syncs with that of the host?

I was facing a time offset of -1hour and 4min

Restarting Docker itself fixed the issue for me.

To set the timezone in general:

  1. ssh into your container: docker exec -it my_website_name bash

  2. run dpkg-reconfigure tzdata

  3. run date

How can I print each command before executing?

set -x is fine, but if you do something like:

set -x;
command;
set +x;

it would result in printing

+ command
+ set +x;

You can use a subshell to prevent that such as:

(set -x; command)

which would just print the command.

Find most frequent value in SQL column

Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.

Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;

How do I call paint event?

The Invalidate() Method will cause a repaint.

MSDN Link

How to use SharedPreferences in Android to store, fetch and edit values

Use used this example simple and clear and checked

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>
public class MainActivity extends AppCompatActivity {
   EditText ed1,ed2,ed3;
   Button b1;

   public static final String MyPREFERENCES = "MyPrefs" ;
   public static final String Name = "nameKey";
   public static final String Phone = "phoneKey";
   public static final String Email = "emailKey";

   SharedPreferences sharedpreferences;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      ed1=(EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      ed3=(EditText)findViewById(R.id.editText3);

      b1=(Button)findViewById(R.id.button);
      sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String n  = ed1.getText().toString();
            String ph  = ed2.getText().toString();
            String e  = ed3.getText().toString();

            SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(Name, n);
            editor.putString(Phone, ph);
            editor.putString(Email, e);
            editor.commit();
            Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
         }
      });
   }

}

Get the value in an input text box

For those who just like me are newbies in JS and getting undefined instead of text value make sure that your id doesn't contain invalid characters.

Return array in a function

In this case, your array variable arr can actually also be treated as a pointer to the beginning of your array's block in memory, by an implicit conversion. This syntax that you're using:

int fillarr(int arr[])

Is kind of just syntactic sugar. You could really replace it with this and it would still work:

int fillarr(int* arr)

So in the same sense, what you want to return from your function is actually a pointer to the first element in the array:

int* fillarr(int arr[])

And you'll still be able to use it just like you would a normal array:

int main()
{
  int y[10];
  int *a = fillarr(y);
  cout << a[0] << endl;
}

Perl - Multiple condition if statement without duplicating code?

I don't recommend storing passwords in a script, but this is a way to what you indicate:

use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );

say ( $user_table{ $name } eq $password ? 'You have gained access.'
    :                                     'Access denied!'
    );

Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.

Shortest way to print current year in a website

The Accepted Answer Does Not Always Work

A recent update has caused all of my WordPress footer copyright dates to get pushed down to then end of the page instead of writing it inline like it used to. I'm sure there are other cases where this may happen as well, but this is just where I've noticed it.

enter image description here

If this happens, you can fix it by creating an empty span tag and injecting your date into it like this:

<span id="cdate"></span><script>document.getElementById("cdate").innerHTML = (new Date().getFullYear());</script> 

or if you have jquery enabled on your site, you can go a bit more simple like this:

<span id="cdate"></span><script>$("#cdate").html(new Date().getFullYear());</script> 

This is similar to Adam Milecki's answer but much shorter

TypeError: 'str' object is not callable (Python)

In my case, I had a Class with a method in it. The method did not have 'self' as the first parameter and the error was being thrown when I made a call to the method. Once I added 'self,' to the method's parameter list, it was fine.

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

And if you have this problem in slider or slideshow you must use jquery.easing.1.3:

<script src="http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js"></script>

Getting the index of the returned max or min item using max()/min() on a list

Say you have a list such as:

a = [9,8,7]

The following two methods are pretty compact ways to get a tuple with the minimum element and its index. Both take a similar time to process. I better like the zip method, but that is my taste.

zip method

element, index = min(list(zip(a, range(len(a)))))

min(list(zip(a, range(len(a)))))
(7, 2)

timeit min(list(zip(a, range(len(a)))))
1.36 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

enumerate method

index, element = min(list(enumerate(a)), key=lambda x:x[1])

min(list(enumerate(a)), key=lambda x:x[1])
(2, 7)

timeit min(list(enumerate(a)), key=lambda x:x[1])
1.45 µs ± 78.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Random strings in Python

Since this question is fairly, uh, random, this may work for you:

>>> import uuid
>>> print uuid.uuid4()
58fe9784-f60a-42bc-aa94-eb8f1a7e5c17

Custom sort function in ng-repeat

To include the direction along with the orderBy function:

ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"

where

defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

here-document gives 'unexpected end of file' error

Along with the other answers mentioned by Barmar and Joni, I've noticed that I sometimes have to leave a blank line before and after my EOF when using <<-EOF.

How to wait till the response comes from the $http request, in angularjs?

for people new to this you can also use a callback for example:

In your service:

.factory('DataHandler',function ($http){

   var GetRandomArtists = function(data, callback){
     $http.post(URL, data).success(function (response) {
         callback(response);
      });
   } 
})

In your controller:

    DataHandler.GetRandomArtists(3, function(response){
      $scope.data.random_artists = response;
   });

super() in Java

For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

public class DeveloperSteps extends ScenarioSteps {

public DeveloperSteps(Pages pages) {
    super(pages);
}........

Excel: Creating a dropdown using a list in another sheet?

Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

You can get this type of error if your class' .m file is not listed under the "Compile Sources" step of the "Build Phases" tab of your target. Normally Xcode does this for you, but sometimes it loses the plot and you need to add the .m file manually.

To do this:

TargetSettings -> Build Phases -> Compile Sources -> add your .m class ->Build and Run

How to manually set REFERER header in Javascript?

This works in Chrome, Firefox, doesn't work in Safari :(, haven't tested in other browsers

        delete window.document.referrer;
        window.document.__defineGetter__('referrer', function () {
            return "yoururl.com";
        });

Saw that here https://gist.github.com/papoms/3481673

Regards

test case: https://jsfiddle.net/bez3w4ko/ (so you can easily test several browsers) and here is a test with iframes https://jsfiddle.net/2vbfpjp1/1/

JSON to string variable dump

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

How do I Search/Find and Replace in a standard string?

Why not return a modified string?

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

You shouldn't change the npm registry using .bat files. Instead try to use modify the .npmrc file which is the configuration for npm. The correct command for changing registry is

npm config set registry <registry url>

you can find more information with npm help config command, also check for privileges when and if you are running .bat files this way.

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

List all sequences in a Postgres db 8.1 with SQL

Improvement of the previous answer:

select string_agg('select sequence_name, last_value from ' || relname, chr(13) || 'union' || chr(13) order by relname) 
from pg_class where relkind ='S'

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

When you click on the image you'll get the alert:

<img src="logo1.jpg" onClick='alert("Hello World!")'/>

if this is what you want.

Selecting specific rows and columns from NumPy array

USE:

 >>> a[[0,1,3]][:,[0,2]]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

OR:

>>> a[[0,1,3],::2]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

What are all possible pos tags of NLTK?

To save some folks some time, here is a list I extracted from a small corpus. I do not know if it is complete, but it should have most (if not all) of the help definitions from upenn_tagset...

CC: conjunction, coordinating

& 'n and both but either et for less minus neither nor or plus so
therefore times v. versus vs. whether yet

CD: numeral, cardinal

mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
fifteen 271,124 dozen quintillion DM2,000 ...

DT: determiner

all an another any both del each either every half la many much nary
neither no some such that the them these this those

EX: existential there

there

IN: preposition or conjunction, subordinating

astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...

JJ: adjective or numeral, ordinal

third ill-mannered pre-war regrettable oiled calamitous first separable
ectoplasmic battery-powered participatory fourth still-to-be-named
multilingual multi-disciplinary ...

JJR: adjective, comparative

bleaker braver breezier briefer brighter brisker broader bumper busier
calmer cheaper choosier cleaner clearer closer colder commoner costlier
cozier creamier crunchier cuter ...

JJS: adjective, superlative

calmest cheapest choicest classiest cleanest clearest closest commonest
corniest costliest crassest creepiest crudest cutest darkest deadliest
dearest deepest densest dinkiest ...

LS: list item marker

A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
SP-44007 Second Third Three Two * a b c d first five four one six three
two

MD: modal auxiliary

can cannot could couldn't dare may might must need ought shall should
shouldn't will would

NN: noun, common, singular or mass

common-carrier cabbage knuckle-duster Casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...

NNP: noun, proper, singular

Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
Shannon A.K.C. Meltex Liverpool ...

NNS: noun, common, plural

undergraduates scotches bric-a-brac products bodyguards facets coasts
divestitures storehouses designs clubs fragrances averages
subjectivists apprehensions muses factory-jobs ...

PDT: pre-determiner

all both half many quite such sure this

POS: genitive marker

' 's

PRP: pronoun, personal

hers herself him himself hisself it itself me myself one oneself ours
ourselves ownself self she thee theirs them themselves they thou thy us

PRP$: pronoun, possessive

her his mine my our ours their thy your

RB: adverb

occasionally unabatingly maddeningly adventurously professedly
stirringly prominently technologically magisterially predominately
swiftly fiscally pitilessly ...

RBR: adverb, comparative

further gloomier grander graver greater grimmer harder harsher
healthier heavier higher however larger later leaner lengthier less-
perfectly lesser lonelier longer louder lower more ...

RBS: adverb, superlative

best biggest bluntest earliest farthest first furthest hardest
heartiest highest largest least less most nearest second tightest worst

RP: particle

aboard about across along apart around aside at away back before behind
by crop down ever fast for forth from go high i.e. in into just later
low more off on open out over per pie raising start teeth that through
under unto up up-pp upon whole with you

TO: "to" as preposition or infinitive marker

to

UH: interjection

Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
man baby diddle hush sonuvabitch ...

VB: verb, base form

ask assemble assess assign assume atone attention avoid bake balkanize
bank begin behold believe bend benefit bevel beware bless boil bomb
boost brace break bring broil brush build ...

VBD: verb, past tense

dipped pleaded swiped regummed soaked tidied convened halted registered
cushioned exacted snubbed strode aimed adopted belied figgered
speculated wore appreciated contemplated ...

VBG: verb, present participle or gerund

telegraphing stirring focusing angering judging stalling lactating
hankerin' alleging veering capping approaching traveling besieging
encrypting interrupting erasing wincing ...

VBN: verb, past participle

multihulled dilapidated aerosolized chaired languished panelized used
experimented flourished imitated reunifed factored condensed sheared
unsettled primed dubbed desired ...

VBP: verb, present tense, not 3rd person singular

predominate wrap resort sue twist spill cure lengthen brush terminate
appear tend stray glisten obtain comprise detest tease attract
emphasize mold postpone sever return wag ...

VBZ: verb, present tense, 3rd person singular

bases reconstructs marks mixes displeases seals carps weaves snatches
slumps stretches authorizes smolders pictures emerges stockpiles
seduces fizzes uses bolsters slaps speaks pleads ...

WDT: WH-determiner

that what whatever which whichever

WP: WH-pronoun

that what whatever whatsoever which who whom whosoever

WRB: Wh-adverb

how however whence whenever where whereby whereever wherein whereof why

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

The jar file may be corrupt. Try removing the content of the following folder:

 C:\Users\[username]\.m2\repository

Then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.

Creating runnable JAR with Gradle

Thank you Konstantin, it worked like a charm with few nuances. For some reason, specifying main class as part of jar manifest did not quite work and it wanted the mainClassName attribute instead. Here is a snippet from build.gradle that includes everything to make it work:

plugins {
  id 'java' 
  id 'com.github.johnrengelman.shadow' version '1.2.2'
}
...
...
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
...
...
mainClassName = 'com.acme.myapp.MyClassMain'
...
...
...
shadowJar {
    baseName = 'myapp'
}

After running gradle shadowJar you get myapp-{version}-all.jar in your build folder which can be run as java -jar myapp-{version}-all.jar.

How can I select all children of an element except the last child?

Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:

const styles = {
  yourClass: {
    /* Styles for all elements with this class */
    '&:not(:last-child)': {
      /* Styles for all EXCEPT the last element with this class */
    },
  },
};

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

jQuery - how to check if an element exists?

Mostly, I prefer to use this syntax :

if ($('#MyId')!= null) {
    // dostuff
}

Even if this code is not commented, the functionality is obvious.

How to restart a node.js server

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

Using Python, find anagrams for a list of words

def findanagranfromlistofwords(li):
    dict = {}
    index=0
    for i in range(0,len(li)):
        originalfirst = li[index]
        sortedfirst = ''.join(sorted(str(li[index])))
        for j in range(index+1,len(li)):
            next = ''.join(sorted(str(li[j])))
            print next
            if sortedfirst == next:
                dict.update({originalfirst:li[j]})
                print "dict = ",dict
        index+=1

    print dict

findanagranfromlistofwords(["car", "tree", "boy", "girl", "arc"])

What does the following Oracle error mean: invalid column index

I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:

<security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"

It turns out that I needed to add: "1 as enabled" to the query:

<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"

Everything worked after that. I believe this could be a bug in the Spring JDBC core package...

How to get AM/PM from a datetime in PHP

Just simply right A

{{ date('h:i A', strtotime($varname->created_at))}}

The correct way to read a data file into an array

Just reading the file into an array, one line per element, is trivial:

open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;

Now the lines of the file are in the array @lines.

If you want to make sure there is error handling for open and close, do something like this (in the snipped below, we open the file in UTF-8 mode, too):

my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
   print STDERR "Could not open file '$path_to_file': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '$path_to_file': $!\n";
} 

Casting an int to a string in Python

For Python versions prior to 2.6, use the string formatting operator %:

filename = "ME%d.txt" % i

For 2.6 and later, use the str.format() method:

filename = "ME{0}.txt".format(i)

Though the first example still works in 2.6, the second one is preferred.

If you have more than 10 files to name this way, you might want to add leading zeros so that the files are ordered correctly in directory listings:

filename = "ME%02d.txt" % i
filename = "ME{0:02d}.txt".format(i)

This will produce file names like ME00.txt to ME99.txt. For more digits, replace the 2 in the examples with a higher number (eg, ME{0:03d}.txt).

How to wrap text around an image using HTML/CSS

Addition to BeNdErR's answer:
The "other TEXT" element should have float:none, like:

_x000D_
_x000D_
    <div style="width:100%;">_x000D_
        <div style="float:left;width:30%; background:red;">...something something something  random text</div>_x000D_
        <div style="float:none; background:yellow;"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text  </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

What is the difference between rb and r+b modes in file objects

r opens for reading, whereas r+ opens for reading and writing. The b is for binary.

This is spelled out in the documentation:

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

Why I can't change directories using "cd"?

To make a bash script that will cd to a select directory :

Create the script file

#!/bin/sh
# file : /scripts/cdjava
#
cd /home/askgelal/projects/java

Then create an alias in your startup file.

#!/bin/sh
# file /scripts/mastercode.sh
#
alias cdjava='. /scripts/cdjava'

  • I created a startup file where I dump all my aliases and custom functions.
  • Then I source this file into my .bashrc to have it set on each boot.

For example, create a master aliases/functions file: /scripts/mastercode.sh
(Put the alias in this file.)

Then at the end of your .bashrc file:

source /scripts/mastercode.sh



Now its easy to cd to your java directory, just type cdjava and you are there.

How often should Oracle database statistics be run?

What Oracle version are you using? Check this page which refers to Oracle 10:

http://www.acs.ilstu.edu/docs/Oracle/server.101/b10752/stats.htm

It says:

The recommended approach to gathering statistics is to allow Oracle to automatically gather the statistics. Oracle gathers statistics on all database objects automatically and maintains those statistics in a regularly-scheduled maintenance job.

Difference of two date time in sql server

Internally in SQL Server dates are stored as 2 integers. The first integer is the number of dates before or after the base date (1900/01/01). The second integer stores the number of clock ticks after midnight, each tick is 1/300 of a second.

More info here

Because of this, I often find the simplest way to compare dates is to simply substract them. This handles 90% of my use cases. E.g.,

select date1, date2, date2 - date1 as DifferenceInDays
from MyTable
...

When I need an answer in units other than days, I will use DateDiff.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I have similar issue, check header if it's not match then run below command

CentOS: sudo yum update && sudo yum -y install kernel-headers kernel-devel

How to change the default browser to debug with in Visual Studio 2008?

If you use ASP-NET MVC, you need to right-click on Default.ASPX which will have a Browse With menu.

Counting inversions in an array

I've found it in O(n * log n) time by the following method.

  1. Merge sort array A and create a copy (array B)
  2. Take A[1] and find its position in sorted array B via a binary search. The number of inversions for this element will be one less than the index number of its position in B since every lower number that appears after the first element of A will be an inversion.

    2a. accumulate the number of inversions to counter variable num_inversions.

    2b. remove A[1] from array A and also from its corresponding position in array B

  3. rerun from step 2 until there are no more elements in A.

Here’s an example run of this algorithm. Original array A = (6, 9, 1, 14, 8, 12, 3, 2)

1: Merge sort and copy to array B

B = (1, 2, 3, 6, 8, 9, 12, 14)

2: Take A[1] and binary search to find it in array B

A[1] = 6

B = (1, 2, 3, 6, 8, 9, 12, 14)

6 is in the 4th position of array B, thus there are 3 inversions. We know this because 6 was in the first position in array A, thus any lower value element that subsequently appears in array A would have an index of j > i (since i in this case is 1).

2.b: Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed).

A = (6, 9, 1, 14, 8, 12, 3, 2) = (9, 1, 14, 8, 12, 3, 2)

B = (1, 2, 3, 6, 8, 9, 12, 14) = (1, 2, 3, 8, 9, 12, 14)

3: Rerun from step 2 on the new A and B arrays.

A[1] = 9

B = (1, 2, 3, 8, 9, 12, 14)

9 is now in the 5th position of array B, thus there are 4 inversions. We know this because 9 was in the first position in array A, thus any lower value element that subsequently appears would have an index of j > i (since i in this case is again 1). Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed)

A = (9, 1, 14, 8, 12, 3, 2) = (1, 14, 8, 12, 3, 2)

B = (1, 2, 3, 8, 9, 12, 14) = (1, 2, 3, 8, 12, 14)

Continuing in this vein will give us the total number of inversions for array A once the loop is complete.

Step 1 (merge sort) would take O(n * log n) to execute. Step 2 would execute n times and at each execution would perform a binary search that takes O(log n) to run for a total of O(n * log n). Total running time would thus be O(n * log n) + O(n * log n) = O(n * log n).

Thanks for your help. Writing out the sample arrays on a piece of paper really helped to visualize the problem.

Error in <my code> : object of type 'closure' is not subsettable

I think you meant to do url[i] <- paste(...

instead of url[i] = paste(.... If so replace = with <-.

Object array initialization without default constructor

No, there isn't. New-expression only allows default initialization or no initialization at all.

The workaround would be to allocate raw memory buffer using operator new[] and then construct objects in that buffer using placement-new with non-default constructor.

Git pull - Please move or remove them before you can merge

I just faced the same issue and solved it using the following.First clear tracked files by using :

git clean -d -f

then try git pull origin master

You can view other git clean options by typing git clean -help

Can we locate a user via user's phone number in Android?

The answer is: you can't only through sms, i have tried that approach before.

You could fetch the base station IDs, but this won't help you a lot without the location of the base station itself and this informations are really hard to retrieve from the providers.

I have looked through the 3 apps you have listed in your question:

  1. The App uses WiFi and GPRS location service, quite the same approach as Google uses on the phone. phonesavvy maybe has a base station location database or uses a database retrieved e.g. from OpenStreetMap or some similar crowd-based project.
  2. The app analyzes just the number for country code and city code. No location there.
  3. Dito.

How to increment a datetime by one day?

Incrementing dates can be accomplished using timedelta objects:

import datetime

datetime.datetime.now() + datetime.timedelta(days=1)

Look up timedelta objects in the Python docs: http://docs.python.org/library/datetime.html

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

moment.js 24h format

HH used 24 hour format while hh used for 12 format

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

how to get file path from sd card in android

You can get the path of sdcard from this code:

File extStore = Environment.getExternalStorageDirectory();

Then specify the foldername and file name

for e.g:

"/LazyList/"+serialno.get(position).trim()+".jpg"

ES6 class variable alternatives

Still you can't declare any classes like in another programming languages. But you can create as many class variables. But problem is scope of class object. So According to me, Best way OOP Programming in ES6 Javascript:-

class foo{
   constructor(){
     //decalre your all variables
     this.MY_CONST = 3.14;
     this.x = 5;
     this.y = 7;
     // or call another method to declare more variables outside from constructor.
     // now create method level object reference and public level property
     this.MySelf = this;
     // you can also use var modifier rather than property but that is not working good
     let self = this.MySelf;
     //code ......... 
   }
   set MySelf(v){
      this.mySelf = v;
   }
   get MySelf(v){
      return this.mySelf;
   }
   myMethod(cd){
      // now use as object reference it in any method of class
      let self = this.MySelf;
      // now use self as object reference in code
   }
}

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

use DIRECTORY option.

Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907

  DIRECTORY

  Default: DATA_PUMP_DIR

  Purpose

  Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.

  Syntax and Description

  DIRECTORY=directory_object
  The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.

  A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.

  Example

  The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".

  > impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp 
  LOGFILE=dpump_dir2:expfull.log
  This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.

e.printStackTrace equivalent in python

Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

What is Scala's yield?

Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

from ... select ??? 

in Scala you have instead

for ... yield ???

It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

  • If your type defines just map, it allows for-expressions consisting of a single generator.
  • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
  • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
  • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

Are duplicate keys allowed in the definition of binary search trees?

1.) left <= root < right

2.) left < root <= right

3.) left < root < right, such that no duplicate keys exist.

I might have to go and dig out my algorithm books, but off the top of my head (3) is the canonical form.

(1) or (2) only come about when you start to allow duplicates nodes and you put duplicate nodes in the tree itself (rather than the node containing a list).

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

Is there a Python caching library?

Try redis, it is one of the cleanest and easiest solutions for applications to share data in a atomic way or if you have got some web server platform. Its very easy to setup, you will need a python redis client http://pypi.python.org/pypi/redis

How to determine the current shell I'm working on

My solution:

ps -o command | grep -v -e "\<ps\>" -e grep -e tail | tail -1

This should be portable across different platforms and shells. It uses ps like other solutions, but it doesn't rely on sed or awk and filters out junk from piping and ps itself so that the shell should always be the last entry. This way we don't need to rely on non-portable PID variables or picking out the right lines and columns.

I've tested on Debian and macOS with Bash, Z shell (zsh), and fish (which doesn't work with most of these solutions without changing the expression specifically for fish, because it uses a different PID variable).

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Send form data using ajax

you can use serialize method of jquery to get form values. Try like this

<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form) " >
</form>

function f( form ){
    var formData = $(form).serialize();
    att=form.attr("action") ;
    $.post(att, formData).done(function(data){
        alert(data);
    });
    return true;
}

Loop through all nested dictionary values?

Iterative solution as an alternative:

def traverse_nested_dict(d):
    iters = [d.iteritems()]

    while iters:
        it = iters.pop()
        try:
            k, v = it.next()
        except StopIteration:
            continue

        iters.append(it)

        if isinstance(v, dict):
            iters.append(v.iteritems())
        else:
            yield k, v


d = {"a": 1, "b": 2, "c": {"d": 3, "e": {"f": 4}}}
for k, v in traverse_nested_dict(d):
    print k, v

Python in Xcode 4+?

Try Editra It's free, has a lot of cool features and plug-ins, it runs on most platforms, and it is written in Python. I use it for all my non-XCode development at home and on Windows/Linux at work.

Is there an alternative sleep function in C to milliseconds?

Yes - older POSIX standards defined usleep(), so this is available on Linux:

int usleep(useconds_t usec);

DESCRIPTION

The usleep() function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.

usleep() takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.


usleep() has since been deprecated and subsequently removed from POSIX; for new code, nanosleep() is preferred:

#include <time.h>

int nanosleep(const struct timespec *req, struct timespec *rem);

DESCRIPTION

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.

The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

An example msleep() function implemented using nanosleep(), continuing the sleep if it is interrupted by a signal:

#include <time.h>
#include <errno.h>    

/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
    struct timespec ts;
    int res;

    if (msec < 0)
    {
        errno = EINVAL;
        return -1;
    }

    ts.tv_sec = msec / 1000;
    ts.tv_nsec = (msec % 1000) * 1000000;

    do {
        res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}

Are there any style options for the HTML5 Date picker?

The following eight pseudo-elements are made available by WebKit for customizing a date input’s textbox:

::-webkit-datetime-edit
::-webkit-datetime-edit-fields-wrapper
::-webkit-datetime-edit-text
::-webkit-datetime-edit-month-field
::-webkit-datetime-edit-day-field
::-webkit-datetime-edit-year-field
::-webkit-inner-spin-button
::-webkit-calendar-picker-indicator

So if you thought the date input could use more spacing and a ridiculous color scheme you could add the following:

_x000D_
_x000D_
::-webkit-datetime-edit { padding: 1em; }_x000D_
::-webkit-datetime-edit-fields-wrapper { background: silver; }_x000D_
::-webkit-datetime-edit-text { color: red; padding: 0 0.3em; }_x000D_
::-webkit-datetime-edit-month-field { color: blue; }_x000D_
::-webkit-datetime-edit-day-field { color: green; }_x000D_
::-webkit-datetime-edit-year-field { color: purple; }_x000D_
::-webkit-inner-spin-button { display: none; }_x000D_
::-webkit-calendar-picker-indicator { background: orange; }
_x000D_
<input type="date">
_x000D_
_x000D_
_x000D_

Screenshot

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

I had

runtime('mysql:mysql-connector-java')

Changed to

compile('mysql:mysql-connector-java')

Fixed my problem

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".

Iterating over arrays in Python 3

When you loop in an array like you did, your for variable(in this example i) is current element of your array.

For example if your ar is [1,5,10], the i value in each iteration is 1, 5, and 10. And because your array length is 3, the maximum index you can use is 2. so when i = 5 you get IndexError. You should change your code into something like this:

for i in ar:
    theSum = theSum + i

Or if you want to use indexes, you should create a range from 0 ro array length - 1.

for i in range(len(ar)):
    theSum = theSum + ar[i]

Angular: conditional class with *ngClass

to extend MostafaMashayekhi his answer for option two> you can also chain multiple options with a ','

[ngClass]="{'my-class': step=='step1', 'my-class2':step=='step2' }"

Also *ngIf can be used in some of these situations usually combined with a *ngFor

class="mats p" *ngIf="mat=='painted'"

Can a PDF file's print dialog be opened with Javascript?

I use named action instead of javascript because javascript often is disabled, and if it isn't it gives a warning.

My web application creates a postscript file that then is converted with ghostscript to a pdf. I want it to print automatically because the user has already clicked on print inside my application. With the information about named actions from @DSimon above, I researched how to solve this. It all boils down to insert the string /Type /Action /S /Named /N /Print at the right place in the pdf.

I was thinking of writing a small utility, but it has to parse the pdf to find the root node, insert /OpenAction with a reference an object with the action, and recalculate the byte-offsets in xref.

But then I found out about pdfmark which is an extension to postscript to express, in postscript syntax, idioms that are converted to pdf by Adobes distiller or by ghostscript.

Since I'm already using ghostscript, all I have to do is append the following to the end of my postscript file:

%AUTOPRINT
[ /_objdef {PrintAction} /type /dict /OBJ pdfmark
[ {PrintAction} << /Type /Action /S /Named /N /Print >> /PUT pdfmark
[ {Catalog} << /OpenAction {PrintAction} >> /PUT pdfmark

and ghostscript will create the action, link it, and calculate the xref offsets. (In postscript % is a comment and PrintAction is my name for the object)

By looking at the PDF I see that it has created this:

1 0 obj
<</Type /Catalog /Pages 3 0 R
/OpenAction  9 0 R
/Metadata 10 0 R
>>
endobj

9 0 obj
<</S/Named
/Type/Action
/N/Print>>endobj

1 0 is object 1, revision 0, and 9 0 is object 9, revision 0. In the pdf-trailer is says that it is object 1 that is the root node. As you can see there is a reference from object 1, /OpenAction to run object 9 revision 0.

With ghostscript it's possible to convert a pdf to postscript (pdf2ps), append the text above, and convert it back to pdf with ps2pdf. It should be noted that meta-information about the pdf is lost in this conversion. I haven't searched more into this.

Ruby: Easiest Way to Filter Hash Keys?

With Hash::select:

params = params.select { |key, value| /^choice\d+$/.match(key.to_s) }

Updates were rejected because the tip of your current branch is behind its remote counterpart

the tip of your current branch is behind its remote counterpart means that there have been changes on the remote branch that you don’t have locally. and git tells you import new changes from REMOTE and merge it with your code and then push it to remote.

You can use this command to force changes to server with local repo ().

git push -f origin master

with -f tag you will override Remote Brach code with your code.

"FATAL: Module not found error" using modprobe

i think there should be entry of your your_module.ko in /lib/modules/uname -r/modules.dep and in /lib/modules/uname -r/modules.dep.bin for "modprobe your_module" command to work

Could not load file or assembly 'System.Web.Mvc'

Simple fix. In VS2010, right click on your MVC project, select "Add Deployable Dependencies...", select the the options you want and click ok

HttpClient won't import in Android Studio

I think depending on which Android Studio version you have, it's important you update your android studio as well, i was becoming frustrated too following everyone's advice but no luck, until i had to upgrade my android version from 1.3 to 1.5, the errors disappeared like magic.

Adding new column to existing DataFrame in Python pandas

Doing this directly via NumPy will be the most efficient:

df1['e'] = np.random.randn(sLength)

Note my original (very old) suggestion was to use map (which is much slower):

df1['e'] = df1['a'].map(lambda x: np.random.random())

How is CountDownLatch used in Java Multithreading?

NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...

 import java.util.concurrent.*;


  public class CountDownLatchExample {

  public static class ProcessThread implements Runnable {

    CountDownLatch latch;
    long workDuration;
    String name;

    public ProcessThread(String name, CountDownLatch latch, long duration){
        this.name= name;
        this.latch = latch;
        this.workDuration = duration;
    }


    public void run() {
        try {
            System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
            Thread.sleep(workDuration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name+ "completed its works");
        //when task finished.. count down the latch count...

        // basically this is same as calling lock object notify(), and object here is latch
        latch.countDown();
    }
}


public static void main(String[] args) {
    // Parent thread creating a latch object
    CountDownLatch latch = new CountDownLatch(3);

    new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
    new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
    new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs


    System.out.println("waiting for Children processes to complete....");
    try {
        //current thread will get notified if all chidren's are done 
        // and thread will resume from wait() mode.
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("All Process Completed....");

    System.out.println("Parent Thread Resuming work....");



     }
  }

How can I save application settings in a Windows Forms application?

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

This technique is applicable both for console, Windows Forms, and other project types.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.

Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs

MySQL: Get column name or alias from query

Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I wrote this in HLSL for our rendering engine, it has no conditions in it:

    float3  HSV2RGB( float3 _HSV )
    {
        _HSV.x = fmod( 100.0 + _HSV.x, 1.0 );                                       // Ensure [0,1[

        float   HueSlice = 6.0 * _HSV.x;                                            // In [0,6[
        float   HueSliceInteger = floor( HueSlice );
        float   HueSliceInterpolant = HueSlice - HueSliceInteger;                   // In [0,1[ for each hue slice

        float3  TempRGB = float3(   _HSV.z * (1.0 - _HSV.y),
                                    _HSV.z * (1.0 - _HSV.y * HueSliceInterpolant),
                                    _HSV.z * (1.0 - _HSV.y * (1.0 - HueSliceInterpolant)) );

        // The idea here to avoid conditions is to notice that the conversion code can be rewritten:
        //    if      ( var_i == 0 ) { R = V         ; G = TempRGB.z ; B = TempRGB.x }
        //    else if ( var_i == 2 ) { R = TempRGB.x ; G = V         ; B = TempRGB.z }
        //    else if ( var_i == 4 ) { R = TempRGB.z ; G = TempRGB.x ; B = V     }
        // 
        //    else if ( var_i == 1 ) { R = TempRGB.y ; G = V         ; B = TempRGB.x }
        //    else if ( var_i == 3 ) { R = TempRGB.x ; G = TempRGB.y ; B = V     }
        //    else if ( var_i == 5 ) { R = V         ; G = TempRGB.x ; B = TempRGB.y }
        //
        // This shows several things:
        //  . A separation between even and odd slices
        //  . If slices (0,2,4) and (1,3,5) can be rewritten as basically being slices (0,1,2) then
        //      the operation simply amounts to performing a "rotate right" on the RGB components
        //  . The base value to rotate is either (V, B, R) for even slices or (G, V, R) for odd slices
        //
        float   IsOddSlice = fmod( HueSliceInteger, 2.0 );                          // 0 if even (slices 0, 2, 4), 1 if odd (slices 1, 3, 5)
        float   ThreeSliceSelector = 0.5 * (HueSliceInteger - IsOddSlice);          // (0, 1, 2) corresponding to slices (0, 2, 4) and (1, 3, 5)

        float3  ScrollingRGBForEvenSlices = float3( _HSV.z, TempRGB.zx );           // (V, Temp Blue, Temp Red) for even slices (0, 2, 4)
        float3  ScrollingRGBForOddSlices = float3( TempRGB.y, _HSV.z, TempRGB.x );  // (Temp Green, V, Temp Red) for odd slices (1, 3, 5)
        float3  ScrollingRGB = lerp( ScrollingRGBForEvenSlices, ScrollingRGBForOddSlices, IsOddSlice );

        float   IsNotFirstSlice = saturate( ThreeSliceSelector );                   // 1 if NOT the first slice (true for slices 1 and 2)
        float   IsNotSecondSlice = saturate( ThreeSliceSelector-1.0 );              // 1 if NOT the first or second slice (true only for slice 2)

        return  lerp( ScrollingRGB.xyz, lerp( ScrollingRGB.zxy, ScrollingRGB.yzx, IsNotSecondSlice ), IsNotFirstSlice );    // Make the RGB rotate right depending on final slice index
    }

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

Why can a function modify some arguments as perceived by the caller, but not others?

You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:

Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

Any time you see varname.foo() you're calling a method on varname. The method may alter varname (e.g. list.append). varname (or, rather, the object that varname names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.

[note that the global keyword creates an exception to the first case]

How to get the 'height' of the screen using jquery

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

As documented here: http://api.jquery.com/height/

Java - How to convert type collection into ArrayList?

More information needed for a definitive answer, but this code

myNodeList = (ArrayList<MyNode>)this.getVertices();

will only work if this.getVertices() returns a (subtype of) List<MyNode>. If it is a different collection (like your Exception seems to indicate), you want to use

new ArrayList<MyNode>(this.getVertices())

This will work as long as a Collection type is returned by getVertices.

Programmatic equivalent of default(Type)

Slight adjustments to @Rob Fonseca-Ensor's solution: The following extension method also works on .Net Standard since I use GetRuntimeMethod instead of GetMethod.

public static class TypeExtensions
{
    public static object GetDefault(this Type t)
    {
        var defaultValue = typeof(TypeExtensions)
            .GetRuntimeMethod(nameof(GetDefaultGeneric), new Type[] { })
            .MakeGenericMethod(t).Invoke(null, null);
        return defaultValue;
    }

    public static T GetDefaultGeneric<T>()
    {
        return default(T);
    }
}

...and the according unit test for those who care about quality:

[Fact]
public void GetDefaultTest()
{
    // Arrange
    var type = typeof(DateTime);

    // Act
    var defaultValue = type.GetDefault();

    // Assert
    defaultValue.Should().Be(default(DateTime));
}

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

same problem happened to me, From this

I have faced the same issue, to solve it:

1- delete (or move) the projects folder (AndroidStudioProjects).

2- Run the Android-Studio (a WELCOME screen will started).

3- From Welcome Screen choose, "Configure -> Project Defaults -> Project Structure)

4- Under Platform Settings choose SDKs.

5- Select Android SDK -> right_click delete.

6- Right_click -> New Sdk -> Android SDK -> choose your SDK dir -> then OK.

7- Choose the Build target -> apply -> OK. enjoy

Printing string variable in Java

This is more likely to get you what you want:

Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

How to make git mark a deleted and a new file as a file move?

Or you coud try the answer to this question here by Amber! To quote it again:

First, cancel your staged add for the manually moved file:

$ git reset path/to/newfile
$ mv path/to/newfile path/to/oldfile

Then, use Git to move the file:

$ git mv path/to/oldfile path/to/newfile

Of course, if you already committed the manual move, you may want to reset to the revision before the move instead, and then simply git mv from there.

Iterate over object in Angular

Adding to SimonHawesome's excellent answer. I've made an succinct version which utilizes some of the new typescript features. I realize that SimonHawesome's version is intentionally verbose as to explain the underlying details. I've also added an early-out check so that the pipe works for falsy values. E.g., if the map is null.

Note that using a iterator transform (as done here) can be more efficient since we do not need to allocate memory for a temporary array (as done in some of the other answers).

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'mapToIterable'
})
export class MapToIterable implements PipeTransform {
    transform(map: { [key: string]: any }, ...parameters: any[]) {
        if (!map)
            return undefined;
        return Object.keys(map)
            .map((key) => ({ 'key': key, 'value': map[key] }));
    }
}

How to enable bulk permission in SQL Server

Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

Change background color of edittext in android

I create color.xml file, for naming my color name (black, white...)

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
 </resources>

And in your EditText, set color

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        android:textColor="@color/black"
        android:background="@color/white"
        />

or use style in you style.xml:

<style name="EditTextStyleWhite" parent="android:style/Widget.EditText">
    <item name="android:textColor">@color/black</item>
    <item name="android:background">@color/white</item>
</style>

and add ctreated style to EditText:

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdsadasdasd"
        style="@style/EditTextStyleWhite"
        />

Get the client IP address using PHP

In PHP 5.3 or greater, you can get it like this:

$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');

What is the meaning of curly braces?

In languages like C curly braces ({}) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

Video streaming over websockets using JavaScript

The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.

Java: splitting the filename into a base and extension

File extensions are a broken concept

And there exists no reliable function for it. Consider for example this filename:

archive.tar.gz

What is the extension? DOS users would have preferred the name archive.tgz. Sometimes you see stupid Windows applications that first decompress the file (yielding a .tar file), then you have to open it again to see the archive contents.

In this case, a more reasonable notion of file extension would have been .tar.gz. There are also .tar.bz2, .tar.xz, .tar.lz and .tar.lzma file "extensions" in use. But how would you decide, whether to split at the last dot, or the second-to-last dot?

Use mime-types instead.

The Java 7 function Files.probeContentType will likely be much more reliable to detect file types than trusting the file extension. Pretty much all the Unix/Linux world as well as your Webbrowser and Smartphone already does it this way.

How to use jQuery in AngularJS

Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/

  angular.module('App', [])
    .controller('AppCtrl', function ($scope) {

      $scope.model = 0;

      $scope.initSlider = function () {
          $(function () {
            // wait till load event fires so all resources are available
              $scope.$slider = $('#slider').slider({
                  slide: $scope.onSlide
              });
          });

          $scope.onSlide = function (e, ui) {
             $scope.model = ui.value;
             $scope.$digest();
          };
      };

      $scope.initSlider();
  });

The directive approach:

HTML

<div slider></div>

JS

  angular.module('App', [])
    .directive('slider', function (DataModel) {
      return {
         restrict: 'A',
         scope: true,
         controller: function ($scope, $element, $attrs) {
            $scope.onSlide = function (e, ui) {
              $scope.model = ui.value;
              // or set it on the model
              // DataModel.model = ui.value;
              // add to angular digest cycle
              $scope.$digest();
            };
         },
         link: function (scope, el, attrs) {

            var options = {
              slide: scope.onSlide  
            };

            // set up slider on load
            angular.element(document).ready(function () {
              scope.$slider = $(el).slider(options);
            });
         }
      }
  });

I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js

You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

std::string + const char* results in another std::string. system does not take a std::string, and you cannot concatenate char*'s with the + operator. If you want to use the code this way you will need:

std::string name = "john";
std::string tmp = 
    "quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '" + 
    name + ".jpg'";
system(tmp.c_str());

See std::string operator+(const char*)

Java ArrayList clear() function

ArrayList.clear(From Java Doc):

Removes all of the elements from this list. The list will be empty after this call returns

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

Is there any boolean type in Oracle databases?

A common space-saving trick is storing boolean values as an Oracle CHAR, rather than NUMBER:

How to fix SSL certificate error when running Npm on Windows?

This is what you can do to avoid npm and use yarn in window machine.

yarn config set "strict-ssl" false

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Another simple example using ImageView to toggle visibility with less code, because of single InputType assign we need only equality operator:

EditText inputPassword = (EditText) findViewById(R.id.loginPassword);
ImageView inputPasswordShow = (ImageView) findViewById(R.id.imagePasswordShow);
inputPasswordShow.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         if(inputPassword.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
              inputPassword.setInputType( InputType.TYPE_CLASS_TEXT |
                                        InputType.TYPE_TEXT_VARIATION_PASSWORD);
         }else {
              inputPassword.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
         }
         inputPassword.setSelection(inputPassword.getText().length());
    }
});

Replacing :

InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

With :

InputType.TYPE_CLASS_TEXT

Will give the same result but shorter word.

How to get the current time in milliseconds from C in Linux?

C11 timespec_get

It returns up to nanoseconds, rounded to the resolution of the implementation.

It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

More details here: https://stackoverflow.com/a/36095407/895245

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

How do I prevent the padding property from changing width or height in CSS?

Put a div in your newdiv with width: auto and margin-left: 20px

Remove the padding from newdiv.

The W3 Box model page has good info.

Visual Studio "Could not copy" .... during build

I was able to fix this issue (VS 2010) through supplying following pre build action;

if exist "$(TargetPath).locked" del "$(TargetPath).locked"

if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"

How can I make a thumbnail <img> show a full size image when clicked?

The

<a href="image2.gif" ><img src="image1.gif"/></a>

technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.

How to execute command stored in a variable?

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz

Regex pattern to match at least 1 number and 1 character in a string

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)

How to create an infinite loop in Windows batch file?

read help GOTO

and try

:again
do it
goto again

XmlWriter to Write to a String Instead of to a File

Well I think the simplest and fastest solution here would be just to:

StringBuilder sb = new StringBuilder();

using (var writer = XmlWriter.Create(sb, settings))
{
    ... // Whatever code you have/need :)

    sb = sb.Replace("encoding=\"utf-16\"", "encoding=\"utf-8\""); //Or whatever uft you want/use.
    //Before you finally save it:
    File.WriteAllText("path\\dataName.xml", sb.ToString());
}

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

Why is this program erroneously rejected by three C++ compilers?

Is your compiler set in expert mode?! If yes, it shouldn't compile. Modern compilers are tired of "Hello World!"

VSCode single to double quote automatic replace

For projects that use .editorconfig file by default. The formatter will ignore the rules in the settings and use the rules in .editorconfig, then you can either:

  • Remove .editorconfig file, and use your VSCode settings.
  • Add quote_type = single to the .editorconfig file regarding your file type. You can also set quote_type value to double or auto.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

Angular 2 declaring an array of objects

I assume you're using typescript.

To be extra cautious you can define your type as an array of objects that need to match certain interface:

type MyArrayType = Array<{id: number, text: string}>;

const arr: MyArrayType = [
    {id: 1, text: 'Sentence 1'},
    {id: 2, text: 'Sentence 2'},
    {id: 3, text: 'Sentence 3'},
    {id: 4, text: 'Sentenc4 '},
];

Or short syntax without defining a custom type:

const arr: Array<{id: number, text: string}> = [...];

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

How do I count a JavaScript object's attributes?

Use underscore library, very useful: _.keys(obj).length.

How to use cookies in Python Requests

Summary (@Freek Wiekmeijer, @gtalarico) other's answer:

Logic of Login

  • Many resource(pages, api) need authentication, then can access, otherwise 405 Not Allowed
  • Common authentication=grant access method are:
    • cookie
    • auth header
      • Basic xxx
      • Authorization xxx

How use cookie in requests to auth

  1. first get/generate cookie
  2. send cookie for following request
  • manual set cookie in headers
  • auto process cookie by requests's
    • session to auto manage cookies
    • response.cookies to manually set cookies

use requests's session auto manage cookies

curSession = requests.Session() 
# all cookies received will be stored in the session object

payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth

# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)

curSession.get(thirdUrl)

manually control requests's response.cookies

payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)

# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)

resp3 = requests.get(thirdUrl, cookies= resp2.cookies)

Radio button checked event handling

The HTML code:

<input type="radio" name="theName" value="1" id="option-1">
<input type="radio" name="theName" value="2">
<input type="radio" name="theName" value="3">

The Javascript code:

$(document).ready(function(){
    $('input[name="theName"]').change(function(){
        if($('#option-1').prop('checked')){
            alert('Option 1 is checked!');
        }else{
            alert('Option 1 is unchecked!');
        }
    });
});

In multiple radio with name "theName", detect when option 1 is checked or unchecked. Works in all situations: on click control, use the keyboard, use joystick, automatic change the values from other dinamicaly function, etc.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

I have used the following procedure.

Procedure to install the apk files in Android Emulator(AVD):

Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder

Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.

Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools

  • Go to Start -> Run -> cmd

  • Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”

  • Type adb install example.apk

  • After getting success command

  • Go to Application icon in Android emulator, we can see the your application

SQL Error: ORA-00936: missing expression

You did two mistakes . I think you misplace FROM and WHERE keywords.

SELECT DISTINCT Description, Date as treatmentDate
     FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL,  doothey.Item.I --Here you use "." operator to "I" alias 
  WHERE  -- WHERE should be located here. 
   P.PatientID = A.PatientID
    AND A.AccountNo = AL.AccountNo
    AND AL.ItemNo = I.ItemNo
    AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

JQuery How to extract value from href tag?

Here's a method that works by transforming the querystring into JSON...

var link = $('a').attr('href');

if (link.indexOf("?") != -1) {
    var query = link.split("?")[1];

    eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");

    if (query.page)
        alert(unescape(query.page));
    else
        alert('No page parameter');

} else {
    alert('No querystring');
}

I'd go with a library like the others suggest though... =)

Why I've got no crontab entry on OS X when using vim?

NOTE: the answer that says to use the ZZ command doesn't work for me on my Mavericks system, but this is probably due to something in my vim configuration because if I start with a pristine .vimrc, the accepted answer works. My answer might work for you if the other solution doesn't.

On MacOS X, according to the crontab manpage, the crontab temporary file that gets created with crontab -e needs to be edited in-place. Vim doesn't edit in-place by default (but it might do some special case to support crontab -e), so if your $EDITOR environment variable is set to vi (the default) or vim, editing the crontab will always fail.

To get Vim to edit the file in-place, you need to do:

:setlocal nowritebackup

That should enable you to update the crontab when you do crontab -e with the :wq or ZZ commands.

You can add an autocommand in your .vimrc to make this automatically work when editing crontabs:

autocmd FileType crontab setlocal nowritebackup

Another way is to add the setlocal nowritebackup to ~/.vim/after/ftplugin/crontab.vim, which will be loaded by Vim automatically when you're editing a crontab file if you have the Filetype plugin enabled. You can also check for the OS if you're using your vim files across multiple platforms:

""In ~/.vim/after/ftplugin/crontab.vim
if has("mac")
  setlocal nowritebackup
endif

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

Comparing two input values in a form validation with AngularJS

use ng-pattern, so that ng-valid and ng-dirty can act correctly

Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg">

<span ng-show="registerForm.email2.$error.pattern">Emails have to match!</span>

How to get current date in jquery?

You can achieve this with moment.js as well. Include moment.js in your html.

<script src="moment.js"></script>

And use below code in script file to get formatted date.

moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();

MySQL Workbench: How to keep the connection alive

In 5.2.47 (at least on mac), go the location of the preferences is: MySQLWorkbench->Preferences->SQL Editor

Then you'll see both:

DBMS connection keep-alive interval (in seconds): DBMS connection read time out (in seconds):

The latter is where you'll want to up the limit from 600 to something a bit more.

What is the best way to seed a database in Rails?

The best way is to use fixtures.

Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.

What does hash do in python?

You can use the Dictionary data type in python. It's very very similar to the hash—and it also supports nesting, similar to the to nested hash.

Example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

For more information, please reference this tutorial on the dictionary data type.

git error: failed to push some refs to remote

In my case closing of editor (visual studio code) solved a problem.

Unable to import a module that is definitely installed

If you are using a virtual environment use pipenv install <module name> instead of pip install <module name>

Worked for me.

java.lang.IllegalAccessError: tried to access method

If getData is protected then try making it public. The problem could exist in JAVA 1.6 and be absent in 1.5x

I got this for your problem. Illegal access error

UICollectionView - Horizontal scroll, horizontal layout?

You can write a custom UICollectionView layout to achieve this, here is demo image of my implementation:

demo image

Here's code repository: KSTCollectionViewPageHorizontalLayout

@iPhoneDev (this maybe help you too)

Bootstrap visible and hidden classes not working properly

As of today November 2017
Bootstrap v4 - beta

Responsive utilities

All @screen- variables have been removed in v4.0.0. Use the media-breakpoint-up(), media-breakpoint-down(), or media-breakpoint-only() Sass mixins or the $grid-breakpoints Sass map instead.

Removed from v3: .hidden-xs .hidden-sm .hidden-md .hidden-lg .visible-xs-block .visible-xs-inline .visible-xs-inline-block .visible-sm-block .visible-sm-inline .visible-sm-inline-block .visible-md-block .visible-md-inline .visible-md-inline-block .visible-lg-block .visible-lg-inline .visible-lg-inline-block

Removed from v4 alphas: .hidden-xs-up .hidden-xs-down .hidden-sm-up .hidden-sm-down .hidden-md-up .hidden-md-down .hidden-lg-up .hidden-lg-down

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

Simple way to understand Encapsulation and Abstraction

Data Abstraction: DA is simply filtering the concrete item. By the class we can achieve the pure abstraction, because before creating the class we can think only about concerned information about the class.

Encapsulation: It is a mechanism, by which we protect our data from outside.

rsync - mkstemp failed: Permission denied (13)

Rsync daemon by default uses nobody/nogroup for all modules if it is running under root user. So you either need to define params uid and gid to the user you want, or set them to root/root.

Difference between break and continue statement

The break statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue starts the loop over at the next iteration.

How to restart a rails server on Heroku?

The answer was:

heroku restart -a app_name

# The -a is the same as --app

Easily aliased with alias hra='heroku restart --app '
Which you can make a permanent alias by adding it to your .bashrc or .bash_aliases file as described at: https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias and
Creating permanent executable aliases
Then you can just type hra app_name

You can restart a specific remote, e.g. "staging" with:

heroku restart -a app_name -r remote_name

Alternatively if you are in the root directory of your rails application you can just type

heroku restart

to restart that app and and you can create an easy alias for that with

alias hr='heroku restart'`

You can place these aliases in your .bashrc file or (preferred) in a .bash_aliases file which is called from .bashrc

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

C - The %x format specifier

That specifies the how many digits you want it to show.

integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width.

String.equals versus ==

Use the string.equals(Object other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

if (usuario.equals(datos[0])) {
    ...
}

NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

Setting background images in JFrame

You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.

413 Request Entity Too Large - File Upload Issue

First edit the Nginx configuration file (nginx.conf)

Location: sudo nano /etc/nginx/nginx.conf

Add following codes:

http {
        client_max_body_size 100M;
}

Then Add the following lines in PHP configuration file(php.ini)

Location: sudo gedit /etc/php5/fpm/php.ini

Add following codes:

memory_limit = 128M 
post_max_size = 20M  
upload_max_filesize = 10M

Replace single quotes in SQL Server

I think this is the shortest SQL statement for that:

CREATE FUNCTION [dbo].[fn_stripsingleQuote] (@strStrip varchar(Max))
    RETURNS varchar(Max)
AS
BEGIN    
    RETURN (Replace(@strStrip ,'''',''))
END

I hope this helps!

document.getElementById('btnid').disabled is not working in firefox and chrome

Another alternative :

document.formname.elementname.disabled=true

Work on FF and IE ! :)

When is the finalize() method called in Java?

The finalize method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.

Note that it's entirely possible that an object never gets garbage collected (and thus finalize is never called). This can happen when the object never becomes eligible for gc (because it's reachable through the entire lifetime of the JVM) or when no garbage collection actually runs between the time the object become eligible and the time the JVM stops running (this often occurs with simple test programs).

There are ways to tell the JVM to run finalize on objects that it wasn't called on yet, but using them isn't a good idea either (the guarantees of that method aren't very strong either).

If you rely on finalize for the correct operation of your application, then you're doing something wrong. finalize should only be used for cleanup of (usually non-Java) resources. And that's exactly because the JVM doesn't guarantee that finalize is ever called on any object.

How do I download the Android SDK without downloading Android Studio?

You can find the command line tools at the downloads page under the "Command line tools only" section.

enter image description here

These are the links provided in the page as of now (version 26.1.1):

Be sure to have read and agreed with the terms of service before downloading any of the command line tools.

The installer version for windows doesn't seem to be available any longer, this is the link for version 24.4.1:

How do I initialize an empty array in C#?

As I know you can't make array without size, but you can use

List<string> l = new List<string>() 

and then l.ToArray().

How to Sign an Already Compiled Apk

fastest way is by signing with the debug keystore:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ~/.android/debug.keystore app.apk androiddebugkey -storepass android

or on Windows:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore %USERPROFILE%/.android/debug.keystore test.apk androiddebugkey -storepass android

Hide scroll bar, but while still being able to scroll

Use this to hide the scrollbar but keep functionality:

.example::-webkit-scrollbar {
  display: none;
}

Hide scrollbar for IE, Edge and Firefox

.example {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

How to get a MemoryStream from a Stream in .NET?

In .NET 4, you can use Stream.CopyTo to copy a stream, instead of the home-brew methods listed in the other answers.

MemoryStream _ms;

public MyClass(Stream sourceStream)

    _ms = new MemoryStream();
    sourceStream.CopyTo(_ms);
}

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Moment.js - tomorrow, today and yesterday

You can use .add() and .subtract() method to get yesterday and tomorrow date. Then use format method to get only date .format("D/M/Y"), D stand for Day, M for Month, Y for Year. Check in Moment Docs

 let currentMilli = Date.now()
 let today = Moment(currentMilli).format("D/M/Y");
 let tomorrow = Moment(currentMilli).add(1, 'days').format("D/M/Y");
 let yesterday = Moment(currentMilli).subtract(1, 'days').format("D/M/Y");

Result will be:

Current Milli - 1576693800000
today - 19/12/2019
tomorrow - 18/12/2019
yesterday - 18/12/2019

Doing a cleanup action just before Node.js exits

function fnAsyncTest(callback) {
    require('fs').writeFile('async.txt', 'bye!', callback);
}

function fnSyncTest() {
    for (var i = 0; i < 10; i++) {}
}

function killProcess() {

    if (process.exitTimeoutId) {
        return;
    }

    process.exitTimeoutId = setTimeout(() => process.exit, 5000);
    console.log('process will exit in 5 seconds');

    fnAsyncTest(function() {
        console.log('async op. done', arguments);
    });

    if (!fnSyncTest()) {
        console.log('sync op. done');
    }
}

// https://nodejs.org/api/process.html#process_signal_events
process.on('SIGTERM', killProcess);
process.on('SIGINT', killProcess);

process.on('uncaughtException', function(e) {

    console.log('[uncaughtException] app will be terminated: ', e.stack);

    killProcess();
    /**
     * @https://nodejs.org/api/process.html#process_event_uncaughtexception
     *  
     * 'uncaughtException' should be used to perform synchronous cleanup before shutting down the process. 
     * It is not safe to resume normal operation after 'uncaughtException'. 
     * If you do use it, restart your application after every unhandled exception!
     * 
     * You have been warned.
     */
});

console.log('App is running...');
console.log('Try to press CTRL+C or SIGNAL the process with PID: ', process.pid);

process.stdin.resume();
// just for testing

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

On the model set $incrementing to false

public $incrementing = false;

This will stop it from thinking it is an auto increment field.

Laravel Docs - Eloquent - Defining Models

how to run two commands in sudo?

If you know the root password, you can try

su -c "<command1> ; <command2>"  

how to make a div to wrap two float divs inside?

Instead of using overflow:hidden, which is a kind of hack, why not simply setting a fixed height, e.g. height:500px, to the parent division?

How to convert a string with comma-delimited items to a list in Python?

Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:

>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'

But what you're dealing with right now, go with @Cameron's answer.

>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

Calling JavaScript Function From CodeBehind

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

Does Java have a complete enum for HTTP response codes?

1) To get the reason text if you only have the code, you can use:

org.apache.http.impl.EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode,null)

Where httpCode would be the reason code that you got from the HTTP response.

See https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/impl/EnglishReasonPhraseCatalog.html for details

2) To get the reason code if you only have the text, you can use BasicHttpResponse.

See here for details: https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/message/BasicHttpResponse.html

strcpy() error in Visual studio 2012

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

IMHO & for the most part this is a good approach.

How to reverse an std::string?

Try

string reversed(temp.rbegin(), temp.rend());

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

Better way of getting time in milliseconds in javascript?

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now() functionality to get finer grain timing in javascript.

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

What is Ad Hoc Query?

In Sql Server "Ad Hoc Query" is also used for Ad Hoc Distributed Queries. These are ad hoc queries on an other server via OpenRowset or OpenDatasource. Ad Hoc Distributed Queries are only allowed after configuring so. This is a Server configuration option.

How can I dynamically switch web service addresses in .NET without a recompile?

Definitely using the Url property is the way to go. Whether to set it in the app.config, the database, or a third location sort of depends on your configuration needs. Sometimes you don't want the app to restart when you change the web service location. You might not have a load balancer scaling the backend. You might be hot-patching a web service bug. Your implementation might have security configuration issues as well. Whether it's production db usernames and passwords or even the ws security auth info. The proper separation of duties can get you into some more involved configuration setups.

If you add a wrapper class around the proxy generated classes, you can set the Url property in some unified fashion every time you create the wrapper class to call a web method.

What are the differences between a HashMap and a Hashtable in Java?

This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.

  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms:

  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke set method since it doesn't modify the collection "structurally". However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.

The Map Interface

Exception of type 'System.OutOfMemoryException' was thrown. Why?

It runs successfully the first time, but if I run it again, I keep getting a System.OutOfMemoryException. What are some reasons this could be happening?

Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.

The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.

You can remedy this problem in a few ways:

  • Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:

    • Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.

    • If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.

  • If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.

If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:

  • Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.

  • If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.

I don't believe you'll need to call GC.Collect() to force a gen cycle. Not only is it generally a bad idea to call GC.Collect(), because sufficient memory pressure will cause .NET invoke the garbage collector on its own.

Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.

How to change JDK version for an Eclipse project

Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.

Changing JRE

Enter image description here

You don't have permission to access / on this server

Set required all granted in /etc/httpd/conf/httpd.conf

react-router scroll to top on every transition

For smaller apps, with 1-4 routes, you could try to hack it with redirect to the top DOM element with #id instead just a route. Then there is no need to wrap Routes in ScrollToTop or using lifecycle methods.

Maximum number of threads per process in Linux?

Depends on your system, just write a sample program [ by creating processes in a loop ] and check using ps axo pid,ppid,rss,vsz,nlwp,cmd. When it can no more create threads check nlwp count [ nlwp is the number threads ] voila you got your fool proof answer instead of going thru books

How can I use UserDefaults in Swift?

Swift 5 and above:

let defaults = UserDefaults.standard

defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")

defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")

defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")


let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")


let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()

let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")

let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()

:)

How can I display just a portion of an image in HTML/CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.

Set size on background image with CSS?

If you want to set background-size in the same background property you can use use:

background:url(my-bg.png) no-repeat top center / 50px 50px;

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

How to convert a byte to its binary string representation

Get each bit of byte and convert to string. Say byte has 8 bits, and we can get them one by one via bit move. For example, we move the second bit of the byte 6 bits to right, the second bit at last of bit of 8 bits, then and(&) with 0x0001 to clean the front bits.

public static String getByteBinaryString(byte b) {
    StringBuilder sb = new StringBuilder();
    for (int i = 7; i >= 0; --i) {
        sb.append(b >>> i & 1);
    }
    return sb.toString();
}

SVN Commit specific files

You basically put the files you want to commit on the command line

svn ci file1 file2 dir1/file3