Programs & Examples On #Anycpu

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

MSBUILD : error MSB1008: Only one project can be specified

For me I had forgot to add closing quote

/p:DeployOnBuild=true;OutDir="$(build.artifactstagingdirectory)

to

/p:DeployOnBuild=true;OutDir="$(build.artifactstagingdirectory)"

Edit and Continue: "Changes are not allowed when..."

For me, it was happening after I had hit a breakpoint, had done some edits, then continued on stepping through the code, then finally hit F5 or "Continue" to get to the end and out of my code block.

After trying the "delete all breakpoints" option (Ctrl+Shift+PrtScn and OK on the prompt) and doing a Rebuild All, I still had an error in my Error Log with regard to my DLL for my project not loading... "Can't apply changes, x.DLL not loaded". After restarting Visual Studio, all was fine again. For me, it turned out to be just this simple.

Other things here did not work for me, like "Require source files to exactly match the original version" was checked before and after things started working again just fine, and targeting "Any CPU" on my x64 machine is just fine, too (did not need to specify x86 or x64). I had "Enable Edit and Continue" enabled in my Tools > Options > Debugging and in my Project Properties > "Web" tab settings.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).

Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".

Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.

Not able to launch IE browser using Selenium2 (Webdriver) with Java

I was not able to modify the protected mode settings manually on my system since they were disabled. But the below VBA snippet for updating the registry values did the trick for me.(Please be cautious about any restrictions on your organization on modifying registry, before trying this)

Const HKEY_CURRENT_USER = &H80000001
strComputer = "."

Set ScriptMe=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\default:StdRegProv")

'Disable protected mode for local intranet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for trusted pages'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for internet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

'Disable protected mode for restricted sites'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue

msgbox "Protected Mode Settings are updated"

Just copy paste the above code into notepad and save it with .vbs extension and double click it!

Now try running your automation script again

Rendering an array.map() in React

Gosha Arinich is right, you should return your <li> element. But, nevertheless, you should get nasty red warning in the browser console in this case

Each child in an array or iterator should have a unique "key" prop.

so, you need to add "key" to your list:

this.state.data.map(function(item, i){
  console.log('test');
  return <li key={i}>Test</li>
})

or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:

this.state.data.map((item,i) => <li key={i}>Test</li>)

IMPORTANT UPDATE:

The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id if id already there, or just generate unique ids for it.

How to get just the parent directory name of a specific file

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"

if you need to append folder "ddd" by another path use;

String currentFolder= "/" + currentPath.getName().toString();

How can I change the value of the elements in a vector?

int main() {
  using namespace std;

  fstream input ("input.txt");
  if (!input) return 1;

  vector<double> v;
  for (double d; input >> d;) {
    v.push_back(d);
  }
  if (v.empty()) return 1;

  double total = std::accumulate(v.begin(), v.end(), 0.0);
  double mean = total / v.size();

  cout << "The values in the file input.txt are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x << '\n';
  }
  cout << "The sum of the values is: " << total << '\n';
  cout << "The mean value is: " << mean << '\n';
  cout << "After subtracting the mean, The values are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x - mean << '\n';  // outputs without changing
    *x -= mean;  // changes the values in the vector
  }

  return 0;
}

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

Print all day-dates between two dates

I came up with this:

from datetime import date, timedelta

sdate = date(2008, 8, 15)   # start date
edate = date(2008, 9, 15)   # end date

delta = edate - sdate       # as timedelta

for i in range(delta.days + 1):
    day = sdate + timedelta(days=i)
    print(day)

The output:

2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15

Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

SQL SERVER: Get total days between two dates

Another date format

select datediff(day,'20110101','20110301')

How to check if user input is not an int value

try this code [updated]:

Scanner scan = null;
       int range, smallest = 0, input;

     for(;;){
         boolean error=false;
        scan = new Scanner(System.in);
        System.out.print("Enter an integer between 1-100:  ");


            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!");                      
                continue;
            }
         range = scan.nextInt();
            if(range < 1) {
                System.out.println("Invalid input!");
                error=true;
            }
        if(error)
        {
        //do nothing
        }
        else
        {
       break;
        }

        }
             for(int ii = 1; ii <= range; ii++) {
            scan = new Scanner(System.in);
            System.out.print("Enter value " + ii + ": ");

            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!"); 
               ii--;
                continue;
            } 
        }

How to convert int to date in SQL Server 2008

Reading through this helps solve a similar problem. The data is in decimal datatype - [DOB] [decimal](8, 0) NOT NULL - eg - 19700109. I want to get at the month. The solution is to combine SUBSTRING with CONVERT to VARCHAR.

    SELECT [NUM]
       ,SUBSTRING(CONVERT(VARCHAR, DOB),5,2) AS mob
    FROM [Dbname].[dbo].[Tablename] 

How to enable curl in xampp?

In XAMPP installation directory, open %XAMPP_HOME%/php/php.ini file. Uncomment the following line: extension=php_curl.dll

PS: If that doesn't work then check whether %XAMPP_HOME%/php/ext/php_curl.dll file exist or not.

Server cannot set status after HTTP headers have been sent IIS7.5

I remember the part from this exception : "Cannot modify header information - headers already sent by" occurring in PHP. It occurred when the headers were already sent in the redirection phase and any other output was generated e.g.:

echo "hello"; header("Location:http://stackoverflow.com");

Pardon me and do correct me if I am wrong but I am still learning MS Technologies and I was trying to help.

How can I install Python's pip3 on my Mac?

For me brew postinstall python3 didn't work. I found this solution on the GitHub Homebrew issues page:

$ brew rm python
$ rm -rf /usr/local/opt/python
$ brew cleanup
$ brew install python3

How to split strings into text and number?

without using regex, using isdigit() built-in function, only works if starting part is text and latter part is number

def text_num_split(item):
    for index, letter in enumerate(item, 0):
        if letter.isdigit():
            return [item[:index],item[index:]]

print(text_num_split("foobar12345"))

OUTPUT :

['foobar', '12345']

Favicon dimensions?

The simplest solution in 2021 is to use one(!) PNG image

Simply add this to the head of your document:

<link rel="shortcut icon" type="image/png" href="/img/icon-192x192.png">
<link rel="shortcut icon" sizes="192x192" href="/img/icon-192x192.png">
<link rel="apple-touch-icon" href="/img/icon-192x192.png">

The last link is for Apple (home screen), the second one for Android (home screen) and the first one for the rest.

Note that this solution does not support "tiles" in Windows 8/10. It does, however, support images in shortcuts, bookmarks and browser-tabs.

The size is exactly the size the Android home screen uses. The Apple home screen icon size is 60px (3x), so 180px and will be scaled down. Other platforms use the default shortcut icon, which will be scaled down too.

How to install pip with Python 3?

Please follow below steps to install python 3 with pip:

Step 1 : Install Python from download here

Step 2 : you’ll need to download get-pip.py

Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .

Step 4 : Enter command python get-pip.py in cmd.

Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version

How do I find Waldo with Mathematica?

My guess at a "bulletproof way to do this" (think CIA finding Waldo in any satellite image any time, not just a single image without competing elements, like striped shirts)... I would train a Boltzmann machine on many images of Waldo - all variations of him sitting, standing, occluded, etc.; shirt, hat, camera, and all the works. You don't need a large corpus of Waldos (maybe 3-5 will be enough), but the more the better.

This will assign clouds of probabilities to various elements occurring in whatever the correct arrangement, and then establish (via segmentation) what an average object size is, fragment the source image into cells of objects which most resemble individual people (considering possible occlusions and pose changes), but since Waldo pictures usually include a LOT of people at about the same scale, this should be a very easy task, then feed these segments of the pre-trained Boltzmann machine. It will give you probability of each one being Waldo. Take one with the highest probability.

This is how OCR, ZIP code readers, and strokeless handwriting recognition work today. Basically you know the answer is there, you know more or less what it should look like, and everything else may have common elements, but is definitely "not it", so you don't bother with the "not it"s, you just look of the likelihood of "it" among all possible "it"s you've seen before" (in ZIP codes for example, you'd train BM for just 1s, just 2s, just 3s, etc., then feed each digit to each machine, and pick one that has most confidence). This works a lot better than a single neural network learning features of all numbers.

Check if record exists from controller in Rails

ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

Swift Bridging Header import issue

Amongst the other fixes, I had the error come up when I tried to do Product->Archive. Turns out I had this :

Objective-C Bridging Header
  Debug (had the value)
  Release (had the value)
    Any architecture | Any SDK (this was blank - problem here!)

After setting it in that last line, it worked.

How to insert double and float values to sqlite?

SQL Supports following types of affinities:

  • TEXT
  • NUMERIC
  • INTEGER
  • REAL
  • BLOB

If the declared type for a column contains any of these "REAL", "FLOAT", or "DOUBLE" then the column has 'REAL' affinity.

Dynamic SELECT TOP @var In SQL Server

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

http://msdn.microsoft.com/en-us/library/ms188774.aspx

Customizing Bootstrap CSS template

I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.

The post goes more in depth with examples, but the basic idea is:

  • Keep a pristine copy of bootstrap and overwrite it externally.
  • Modify one file (bootstrap's variables.less) to include your own variables.
  • Make your site file @include bootstrap.less and then your overrides.

This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.

Using this solution, your example problem would look like:

  • Change the nav bar color with @navbar-inverse-bg in your variables.less (not bootstrap's)
  • Add your own nav bar styles to your bootstrap_overrides.less, overwriting anything you need to as you go.
  • Happiness.

When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)

Blog post with walk-through is here.

Code example on github is here.

Centering the pagination in bootstrap

It works for me:

<div class="text-center">
<ul class="pagination pagination-lg">
   <li>
  <a href="#" aria-label="Previous">
    <span aria-hidden="true">&laquo;</span>
  </a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
  <a href="#" aria-label="Next">
    <span aria-hidden="true">&raquo;</span>
  </a>
</li>
</ul>

dyld: Library not loaded ... Reason: Image not found

If you are using Conda environment in the terminal, update the samtools to solve it.

conda install -c bioconda samtools

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

Good way to encapsulate Integer.parseInt()

You shouldn't use Exceptions to validate your values.

For single character there is a simple solution:

Character.isDigit()

For longer values it's better to use some utils. NumberUtils provided by Apache would work perfectly here:

NumberUtils.isNumber()

Please check https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

Comparing two columns, and returning a specific adjacent cell in Excel

I would advise you to swap B and C columns for the reason that I will explain. Then in D2 type: =VLOOKUP(A2, B2:C4, 2, FALSE)

Finally, copy the formula for the remaining cells.

Explanation: VLOOKUP will first find the value of A2 in the range B2 to C4 (second argument). NOTE: VLOOKUP always searches the first column in this range. This is the reason why you have to swap the two columns before doing anything.

Once the exact match is found, it will return the value in the adjacent cell (third argument).

This means that, if you put 1 as the third argument, the function will return the value in the first column of the range (which will be the same value you were looking for). If you put 2, it will return the value from the second column in the range (the value in the adjacent cell-RIGHT SIDE of the found value).

FALSE indicates that you are finding the exact match. If you put TRUE, you will be searching for the approximate match.

How do you subtract Dates in Java?

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

Android Service needs to run always (Never pause or stop)

If you already have a service and want it to work all the time, you need to add 2 things:

  1. in the service itself:

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. In the manifest:

    android:launchMode="singleTop"
    

No need to add bind unless you need it in the service.

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

How to retrieve the first word of the output of a command in bash?

Awk is a good option if you have to deal with trailing whitespace because it'll take care of it for you:

echo "   word1  word2 " | awk '{print $1;}' # Prints "word1"

Cut won't take care of this though:

echo "  word1  word2 " | cut -f 1 -d " " # Prints nothing/whitespace

'cut' here prints nothing/whitespace, because the first thing before a space was another space.

How do you replace all the occurrences of a certain character in a string?

I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.

def remove_chars(line):
    line7=line[7].translate(None,'abcd')
    return line[:7]+[line7]+line[8:]

line= ['ad','da','sdf','asd',
        '3424','342sfas','asdfaf','sdfa',
        'afase']
print line[7]
line = remove_chars(line)
print line[7]

SQL: Group by minimum value in one field while selecting distinct rows

If record_date has no duplicates within a group:

think of it as of filtering. Simpliy get (WHERE) one (MIN(record_date)) row from the current group:

SELECT * FROM t t1 WHERE record_date = (
                                 select MIN(record_date)
                                 from t t2 where t2.group_id = t1.group_id)

If there could be 2+ min record_date within a group:

  1. filter out non-min rows (see above)

  2. then (AND) pick only one from the 2+ min record_date rows, within the given group_id. E.g. pick the one with the min unique key:

                    AND key_id = (select MIN(key_id)
                                  from t t3 where t3.record_date = t1.record_date
                                              and t3.group_id    = t1.group_id)
    

so

key_id | group_id | record_date | other_cols
1      | 18       | 2011-04-03  | x
4      | 19       | 2009-06-01  | a
8      | 19       | 2009-06-01  | e

will select key_ids: #1 and #4

pythonic way to do something N times without an index variable?

The _ is the same thing as x. However it's a python idiom that's used to indicate an identifier that you don't intend to use. In python these identifiers don't takes memor or allocate space like variables do in other languages. It's easy to forget that. They're just names that point to objects, in this case an integer on each iteration.

How do you initialise a dynamic array in C++?

C++ has no specific feature to do that. However, if you use a std::vector instead of an array (as you probably should do) then you can specify a value to initialise the vector with.

std::vector <char> v( 100, 42 );

creates a vector of size 100 with all values initialised to 42.

How to use sbt from behind proxy?

sbt works in a fairly standard way comparing to the way other JVM-based projects are usually configured.

sbt is in fact two "subsystems" - the launcher and the core. It's usually xsbt.boot.Boot that gets executed before the core starts up with the features we all know (and some even like).

It's therefore a matter of how you execute sbt that says how you could set up a proxy for HTTP, HTTPS and FTP network traffic.

The following is the entire list of the available properties that can be set for any Java application, sbt including, that instruct the Java API to route communication through a proxy:

  • http_proxy
  • http_proxy_user
  • http_proxy_pass
  • http.proxyHost
  • http.proxyPort
  • http.proxyUser
  • http.proxyPassword

Replace http above with https and ftp to get the list of the properties for the services.

Some sbt scripts use JAVA_OPTS to set up the proxy settings with -Dhttp.proxyHost and -Dhttp.proxyPort amongst the others (listed above). See Java Networking and Proxies.

Some scripts come with their own way of setting up proxy configuration using the SBT_OPTS property, .sbtopts or (only on Windows) %SBT_HOME%\conf\sbtconfig.txt. You can use them to specifically set sbt to use proxies while the other JVM-based applications are not affected at all.

From the sbt command line tool:

# jvm options and output control
JAVA_OPTS          environment variable, if unset uses "$java_opts"
SBT_OPTS           environment variable, if unset uses "$default_sbt_opts"
.sbtopts           if this file exists in the current directory, it is
                   prepended to the runner args
/etc/sbt/sbtopts   if this file exists, it is prepended to the runner args
-Dkey=val          pass -Dkey=val directly to the java runtime
-J-X               pass option -X directly to the java runtime 
                   (-J is stripped)
-S-X               add -X to sbt's scalacOptions (-S is stripped)

And here comes an excerpt from sbt.bat:

@REM Envioronment:
@REM JAVA_HOME - location of a JDK home dir (mandatory)
@REM SBT_OPTS  - JVM options (optional)
@REM Configuration:
@REM sbtconfig.txt found in the SBT_HOME.

Be careful with sbtconfig.txt that just works on Windows only. When you use cygwin the file is not consulted and you will have to resort to using the other approaches.

I'm using sbt with the following script:

$JAVA_HOME/bin/java $SBT_OPTS -jar /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar "$@"

The point of the script is to use the latest version of sbt built from the sources (that's why I'm using /Users/jacek/.ivy2/local/org.scala-sbt/sbt-launch/$SBT_LAUNCHER_VERSION-SNAPSHOT/jars/sbt-launch.jar) with $SBT_OPTS property as a means of passing JVM properties to the JVM sbt uses.

The script above lets me to set proxy on command line on MacOS X as follows:

SBT_OPTS="-Dhttp.proxyHost=proxyhost -Dhttp.proxyPort=9999" sbt

As you can see, there are many approaches to set proxy for sbt that all pretty much boil down to set a proxy for the JVM sbt uses.

Given URL is not allowed by the Application configuration Facebook application error

Michael Blackburn's answer helped me resolve my issue, but I want to give more detail on my fix.

I have a php app that posts to a user's FB page.

I own two domains:

I built my site off the first domain because it read better IMHO (at least it did at the time).

Some users typoed the url so I bought the second one with no dashes for that reason.

So, one of my users was having the "Given URL" error.

Turns out he was going to http://app.mywebapp.com and the rest of them were going to http://app.my-web-app.com

I fixed everyone by adding all possible redirect URIs: enter image description here

Granted, there are 100 better ways to implement this, but here is the workaround for now.

How to add facebook share button on my website?

For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem today. If after you delete all of the connections, the connection properties still live on. I clicked on properties, deleted the name by selecting the name window and deleting it.

A warning came up to verify I really wanted to do it. After selecting yes, it got rid of the connection. Save the workbook.

I am a hack at Excel but this seemed to work.

React Native fetch() Network Request Failed

For android, add android:networkSecurityConfig="@xml/network_security_config" to application tag in AndroidManifest.xml, like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>

network_security_config.xml file content:

<?xml version='1.0' encoding='utf-8'?>
<network-security-config>
<debug-overrides>
    <trust-anchors>
        <!-- Trust user added CAs while debuggable only -->
        <certificates src="user" />
    </trust-anchors>
</debug-overrides>

<!-- let application to use http request -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>

How can I delay a method call for 1 second?

NOTE: this will pause your whole thread, not just the one method.
Make a call to sleep/wait/halt for 1000 ms just before calling your method?

Sleep(1000); // does nothing the next 1000 mSek

Methodcall(params); // now do the real thing

Edit: The above answer applies to the general question "How can I delay a method call for 1 second?", which was the question asked at the time of the answer (infact the answer was given within 7 minutes of the original question :-)). No Info was given about the language at that time, so kindly stop bitching about the proper way of using sleep i XCode og the lack of classes...

Count length of array and return 1 if it only contains one element

declare you array as:

$car = array("bmw")

EDIT

now with powershell syntax:)

$car = [array]"bmw"

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

The column of the first matrix and the row of the second matrix should be equal and the order should be like this only

column of first matrix = row of second matrix

and do not follow the below step

row of first matrix  = column of second matrix

it will throw an error

How can I remove leading and trailing quotes in SQL Server?

I use this:

UPDATE DataImport
SET PRIO = 
        CASE WHEN LEN(PRIO) < 2 
        THEN 
            (CASE PRIO WHEN '""' THEN '' ELSE PRIO END) 
        ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"', 
            SUBSTRING(PRIO, 2, LEN(PRIO) - 2)) 
        END

Difference between ApiController and Controller in ASP.NET MVC

Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.

here is the link

Quote:

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.

You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.

It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.

To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

I had a quite similar problem in a "test-utils" project (adding features, rules and assertions to JUnit) child of a parent project injecting dependencies. The class depending on the org.junit.rules package was in src/main/java.

So I added a dependency on junit without test scope and it solved the problem :

pom.xml of the test-util project :

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
</dependency>

pom.xml of the parent project :

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <scope>test</scope>
</dependency>

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

What characters are valid for JavaScript variable names?

I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX as it's harder to break out of.

    function isValidVarName( name ) {
    try {
        return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
    } catch( e ) {
        return false;
    }
    return true;
}

// so we can see the test code
var _eval = eval;
window.eval = function(s) {
    console.log(s);
    return _eval(s);
}

console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));

console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));

console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

jQuery(document).ready(function ($) {

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

Android Reading from an Input stream efficiently

Possibly somewhat faster than Jaime Soriano's answer, and without the multi-byte encoding problems of Adrian's answer, I suggest:

File file = new File("/tmp/myfile");
try {
    FileInputStream stream = new FileInputStream(file);

    int count;
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream byteStream =
        new ByteArrayOutputStream(stream.available());

    while (true) {
        count = stream.read(buffer);
        if (count <= 0)
            break;
        byteStream.write(buffer, 0, count);
    }

    String string = byteStream.toString();
    System.out.format("%d bytes: \"%s\"%n", string.length(), string);
} catch (IOException e) {
    e.printStackTrace();
}

How to export a Hive table into a CSV file?

If you're using Hive 11 or better you can use the INSERT statement with the LOCAL keyword.

Example:

insert overwrite local directory '/home/carter/staging' row format delimited fields terminated by ',' select * from hugetable;

Note that this may create multiple files and you may want to concatenate them on the client side after it's done exporting.

Using this approach means you don't need to worry about the format of the source tables, can export based on arbitrary SQL query, and can select your own delimiters and output formats.

Currency format for display

If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.

public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
    NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
    localFormat.CurrencySymbol = currencySymbol;
    localFormat.CurrencyDecimalDigits = decPlaces;
    return currency.ToString("c", localFormat);
}

Web colors in an Android color xml resource file

I change all code to lower case for mono android

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <color name="white">#FFFFFF</color>
    <color name="ivory">#FFFFF0</color>
    <color name="lightyellow">#FFFFE0</color>
    <color name="yellow">#FFFF00</color>
    <color name="snow">#FFFAFA</color>
    <color name="floralwhite">#FFFAF0</color>
    <color name="lemonchiffon">#FFFACD</color>
    <color name="cornsilk">#FFF8DC</color>
    <color name="seashell">#FFF5EE</color>
    <color name="lavenderblush">#FFF0F5</color>
    <color name="papayawhip">#FFEFD5</color>
    <color name="blanchedalmond">#FFEBCD</color>
    <color name="mistyrose">#FFE4E1</color>
    <color name="bisque">#FFE4C4</color>
    <color name="moccasin">#FFE4B5</color>
    <color name="navajowhite">#FFDEAD</color>
    <color name="peachpuff">#FFDAB9</color>
    <color name="gold">#FFD700</color>
    <color name="pink">#FFC0CB</color>
    <color name="lightpink">#FFB6C1</color>
    <color name="orange">#FFA500</color>
    <color name="lightsalmon">#FFA07A</color>
    <color name="darkorange">#FF8C00</color>
    <color name="coral">#FF7F50</color>
    <color name="hotpink">#FF69B4</color>
    <color name="tomato">#FF6347</color>
    <color name="orangered">#FF4500</color>
    <color name="deeppink">#FF1493</color>
    <color name="fuchsia">#FF00FF</color>
    <color name="magenta">#FF00FF</color>
    <color name="red">#FF0000</color>
    <color name="oldlace">#FDF5E6</color>
    <color name="lightgoldenrodyellow">#FAFAD2</color>
    <color name="linen">#FAF0E6</color>
    <color name="antiquewhite">#FAEBD7</color>
    <color name="salmon">#FA8072</color>
    <color name="ghostwhite">#F8F8FF</color>
    <color name="mintcream">#F5FFFA</color>
    <color name="whitesmoke">#F5F5F5</color>
    <color name="beige">#F5F5DC</color>
    <color name="wheat">#F5DEB3</color>
    <color name="sandybrown">#F4A460</color>
    <color name="azure">#F0FFFF</color>
    <color name="honeydew">#F0FFF0</color>
    <color name="aliceblue">#F0F8FF</color>
    <color name="khaki">#F0E68C</color>
    <color name="lightcoral">#F08080</color>
    <color name="palegoldenrod">#EEE8AA</color>
    <color name="violet">#EE82EE</color>
    <color name="darksalmon">#E9967A</color>
    <color name="lavender">#E6E6FA</color>
    <color name="lightcyan">#E0FFFF</color>
    <color name="burlywood">#DEB887</color>
    <color name="plum">#DDA0DD</color>
    <color name="gainsboro">#DCDCDC</color>
    <color name="crimson">#DC143C</color>
    <color name="palevioletred">#DB7093</color>
    <color name="goldenrod">#DAA520</color>
    <color name="orchid">#DA70D6</color>
    <color name="thistle">#D8BFD8</color>
    <color name="lightgrey">#D3D3D3</color>
    <color name="tan">#D2B48C</color>
    <color name="chocolate">#D2691E</color>
    <color name="peru">#CD853F</color>
    <color name="indianred">#CD5C5C</color>
    <color name="mediumvioletred">#C71585</color>
    <color name="silver">#C0C0C0</color>
    <color name="darkkhaki">#BDB76B</color>
    <color name="rosybrown">#BC8F8F</color>
    <color name="mediumorchid">#BA55D3</color>
    <color name="darkgoldenrod">#B8860B</color>
    <color name="firebrick">#B22222</color>
    <color name="powderblue">#B0E0E6</color>
    <color name="lightsteelblue">#B0C4DE</color>
    <color name="paleturquoise">#AFEEEE</color>
    <color name="greenyellow">#ADFF2F</color>
    <color name="lightblue">#ADD8E6</color>
    <color name="darkgray">#A9A9A9</color>
    <color name="brown">#A52A2A</color>
    <color name="sienna">#A0522D</color>
    <color name="yellowgreen">#9ACD32</color>
    <color name="darkorchid">#9932CC</color>
    <color name="palegreen">#98FB98</color>
    <color name="darkviolet">#9400D3</color>
    <color name="mediumpurple">#9370DB</color>
    <color name="lightgreen">#90EE90</color>
    <color name="darkseagreen">#8FBC8F</color>
    <color name="saddlebrown">#8B4513</color>
    <color name="darkmagenta">#8B008B</color>
    <color name="darkred">#8B0000</color>
    <color name="blueviolet">#8A2BE2</color>
    <color name="lightskyblue">#87CEFA</color>
    <color name="skyblue">#87CEEB</color>
    <color name="gray">#808080</color>
    <color name="olive">#808000</color>
    <color name="purple">#800080</color>
    <color name="maroon">#800000</color>
    <color name="aquamarine">#7FFFD4</color>
    <color name="chartreuse">#7FFF00</color>
    <color name="lawngreen">#7CFC00</color>
    <color name="mediumslateblue">#7B68EE</color>
    <color name="lightslategray">#778899</color>
    <color name="slategray">#708090</color>
    <color name="olivedrab">#6B8E23</color>
    <color name="slateblue">#6A5ACD</color>
    <color name="dimgray">#696969</color>
    <color name="mediumaquamarine">#66CDAA</color>
    <color name="cornflowerblue">#6495ED</color>
    <color name="cadetblue">#5F9EA0</color>
    <color name="darkolivegreen">#556B2F</color>
    <color name="indigo">#4B0082</color>
    <color name="mediumturquoise">#48D1CC</color>
    <color name="darkslateblue">#483D8B</color>
    <color name="steelblue">#4682B4</color>
    <color name="royalblue">#4169E1</color>
    <color name="turquoise">#40E0D0</color>
    <color name="mediumseagreen">#3CB371</color>
    <color name="limegreen">#32CD32</color>
    <color name="darkslategray">#2F4F4F</color>
    <color name="seagreen">#2E8B57</color>
    <color name="forestgreen">#228B22</color>
    <color name="lightseagreen">#20B2AA</color>
    <color name="dodgerblue">#1E90FF</color>
    <color name="midnightblue">#191970</color>
    <color name="aqua">#00FFFF</color>
    <color name="cyan">#00FFFF</color>
    <color name="springgreen">#00FF7F</color>
    <color name="lime">#00FF00</color>
    <color name="mediumspringgreen">#00FA9A</color>
    <color name="darkturquoise">#00CED1</color>
    <color name="deepskyblue">#00BFFF</color>
    <color name="darkcyan">#008B8B</color>
    <color name="teal">#008080</color>
    <color name="green">#008000</color>
    <color name="darkgreen">#006400</color>
    <color name="blue">#0000FF</color>
    <color name="mediumblue">#0000CD</color>
    <color name="darkblue">#00008B</color>
    <color name="navy">#000080</color>
    <color name="black">#000000</color>
    </resources>

Datatables - Search Box outside datatable

I want to add one more thing to the @netbrain's answer relevant in case you use server-side processing (see serverSide option).

Query throttling performed by default by datatables (see searchDelay option) does not apply to the .search() API call. You can get it back by using $.fn.dataTable.util.throttle() in the following way:

var table = $('#myTable').DataTable();
var search = $.fn.dataTable.util.throttle(
    function(val) {
        table.search(val).draw();
    },
    400  // Search delay in ms
);

$('#mySearchBox').keyup(function() {
    search(this.value);
});

No Android SDK found - Android Studio

i have just discovered, android studio 3.0.1 has no sdk during the installation. because during the installation, it doesn't give sdk as part of install able unlike in recent versions of android studio.

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

How to rename JSON key

If you want to rename all occurrences of some key you can use a regex with the g option. For example:

var json = [{"_id":"1","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"2","email":"[email protected]","image":"some_image_url","name":"Name 2"}];

str = JSON.stringify(json);

now we have the json in string format in str.

Replace all occurrences of "_id" to "id" using regex with the g option:

str = str.replace(/\"_id\":/g, "\"id\":");

and return to json format:

json = JSON.parse(str);

now we have our json with the wanted key name.

Laravel: Get base url

For Laravel 5 I normally use:

<a href="{{ url('/path/uri') }}">Link Text</a>

I'm of the understanding that using the url() function is calling the same Facade as URL::to()

PHPExcel - creating multiple sheets by iteration

When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one you've just added... this is your title "0".

You're also using the createSheet() method, which both creates a new worksheet and adds it to the workbook... but you're also adding it again yourself which is effectively adding the sheet in two position.

So first iteration, you already have sheet0, add a new sheet at both indexes 1 and 2, and edit/title sheet 0. Second iteration, you add a new sheet at both indexes 3 and 4, and edit/title sheet 1, but because you have the same sheet at indexes 1 and 2 this effectively writes to the sheet at index 2. Third iteration, you add a new sheet at indexes 5 and 6, and edit/title sheet 2, overwriting your earlier editing/titleing of sheet 1 which acted against sheet 2 instead.... and so on

Select single item from a list

List<string> items = new List<string>();

items.Find(p => p == "blah");

or

items.Find(p => p.Contains("b"));

but this allows you to define what you are looking for via a match predicate...

I guess if you are talking linqToSql then:

example looking for Account...

DataContext dc = new DataContext();

Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);

If you need to make sure that there is only 1 item (throws exception when more than 1)

DataContext dc = new DataContext();

Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

Keep a line of text as a single line - wrap the whole line or none at all

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

Find Facebook user (url to profile page) by known email address

Andreas, I've also been looking for an "email-to-id" ellegant solution and couldn't find one. However, as you said, screen scraping is not such a bad idea in this case, because emails are unique and you either get a single match or none. As long as Facebook don't change their search page drastically, the following will do the trick:

final static String USER_SEARCH_QUERY = "http://www.facebook.com/search.php?init=s:email&q=%s&type=users";
final static String USER_URL_PREFIX = "http://www.facebook.com/profile.php?id=";

public static String emailToID(String email)
{
    try
    {
        String html = getHTML(String.format(USER_SEARCH_QUERY, email));
        if (html != null)
        {
            int i = html.indexOf(USER_URL_PREFIX) + USER_URL_PREFIX.length();
            if (i > 0)
            {
                StringBuilder sb = new StringBuilder();
                char c;
                while (Character.isDigit(c = html.charAt(i++)))
                    sb.append(c);
                if (sb.length() > 0)
                    return sb.toString();
            }
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}

private static String getHTML(String htmlUrl) throws MalformedURLException, IOException
{
    StringBuilder response = new StringBuilder();
    URL url = new URL(htmlUrl);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
        String strLine = null;
        while ((strLine = input.readLine()) != null)
            response.append(strLine);
        input.close();
    }
    return (response.length() == 0) ? null : response.toString();
}

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

After trying many solutions, seems like the one that finally did the trick was to connect by IP. No longer file sockets getting deleted randomly.

Just update your MySQL client config (e.g. /usr/local/etc/my.cnf) with:

[client]
port = 3306
host=127.0.0.1
protocol=tcp

How to install SQL Server Management Studio 2012 (SSMS) Express?

When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe

I had to choose the following options to get the management Tools:

  1. "New SQL Server stand-alone installation or add features to an existing installation."
  2. "Add features to an existing instance of SQL Server 2012"
  3. Accept the license.
  4. Check the box for "Management Tools - Basic".
  5. Wait a long time as it installs.

When I was done I had an option "SQL Server Management Studio" within my Start Menu.

Searching for "Management" pulled it up faster within the Start Menu.

How to set Meld as git mergetool

For windows add the path for meld is like below:

 git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe

Passing arguments forward to another javascript function

try this

function global_func(...args){
  for(let i of args){
    console.log(i)
  }
}


global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)




//task_name
//action
//(2) [{...},
//    {...}]
//    {
//        x:"x"
//    }
//(2) [
//        "x1",
//        "x2"
//    ]
//1
//null
//undefined
//false
//true
//func

How can I let a user download multiple files when a button is clicked?

This works in all browsers (IE11, Firefox, Microsoft Edge, Chrome and Chrome Mobile) My documents are in multiple select elements. The browsers seem to have issues when you try to do it too fast... So I used a timeout.

<select class="document">
    <option val="word.docx">some word document</option>
</select>

//user clicks a download button to download all selected documents
    $('#downloadDocumentsButton').click(function () {
        var interval = 1000;
        //select elements have class name of "document"
        $('.document').each(function (index, element) {
            var doc = $(element).val();
            if (doc) {
                setTimeout(function () {
                    window.location = doc;
                }, interval * (index + 1));
            }
        });
    });

This solution uses promises:

function downloadDocs(docs) {
    docs[0].then(function (result) {
        if (result.web) {
            window.open(result.doc);
        }
        else {
            window.location = result.doc;
        }
        if (docs.length > 1) {
            setTimeout(function () { return downloadDocs(docs.slice(1)); }, 2000);
        }
    });
}

 $('#downloadDocumentsButton').click(function () {
    var files = [];
    $('.document').each(function (index, element) {
        var doc = $(element).val();
        var ext = doc.split('.')[doc.split('.').length - 1];

        if (doc && $.inArray(ext, docTypes) > -1) {
            files.unshift(Promise.resolve({ doc: doc, web: false }));
        }
        else if (doc && ($.inArray(ext, webTypes) > -1 || ext.includes('?'))) {
            files.push(Promise.resolve({ doc: doc, web: true }));
        }
    });

    downloadDocs(files);
});

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

How to use RecyclerView inside NestedScrollView?

I have used this awesome extension (written in kotlin but can be also used in Java)

https://github.com/Widgetlabs/expedition-nestedscrollview

Basically you get the NestedRecyclerView inside any package lets say utils in your project, then just create your recyclerview like

 <com.your_package.utils.NestedRecyclerView
      android:id="@+id/rv_test"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

Check this awesome article by Marc Knaup

https://medium.com/widgetlabs-engineering/scrollable-nestedscrollviews-inside-recyclerview-ca65050d828a

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

Maven: Non-resolvable parent POM

Replace 1.0_A0 with ${project.version}

Run mvn once. This will download all the required repositories. You may switch back to 1.0_A0 after this step.

How to squash commits in git after they have been pushed?

On a branch I was able to do it like this (for the last 4 commits)

git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch

In Python, how do I split a string and keep the separators?

  1. replace all seperator: (\W) with seperator + new_seperator: (\W;)

  2. split by the new_seperator: (;)

def split_and_keep(seperator, s):
  return re.split(';', re.sub(seperator, lambda match: match.group() + ';', s))

print('\W', 'foo/bar spam\neggs')

How to script FTP upload and download?

Try manually:

$ ftp www.domainhere.com 
> useridhere
> passwordhere
> put test.txt
> bye
> pause

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Go to Eclipse folder, locate eclipse.ini file, add following entry (before -vmargs if present):

-vm
C:\Program Files\Java\jdk1.7.0_10\bin\javaw.exe

Save file and execute eclipse.exe.

How to combine two or more querysets in a Django view?

You can use Union

qs = qs1.union(qs2, qs3)

But if you want to apply order_by on the foreign models of the combined queryset.. then you need to Select them before hand this way.. otherwise it won't work

Example

qs = qs1.union(qs2.select_related("foreignModel"), qs3.select_related("foreignModel"))
qs.order_by("foreignModel__prop1")

where prop1 is a property in the foreign model

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

Safari 3rd party cookie iframe trick no longer working?

I decided to get rid of the $_SESSION variable all together & wrote a wrapper around memcache to mimic the session.

Check https://github.com/manpreetssethi/utils/blob/master/Session_manager.php

Use-case: The moment a user lands on the app, store the signed request using the Session_manager and since it's in the cache, you may access it on any page henceforth.

Note: This will not work when browsing privately in Safari since the session_id resets every time the page reloads. (Stupid Safari)

std::enable_if to conditionally compile a member function

For those late-comers that are looking for a solution that "just works":

#include <utility>
#include <iostream>

template< typename T >
class Y {

    template< bool cond, typename U >
    using resolvedType  = typename std::enable_if< cond, U >::type; 

    public:
        template< typename U = T > 
        resolvedType< true, U > foo() {
            return 11;
        }
        template< typename U = T >
        resolvedType< false, U > foo() {
            return 12;
        }

};


int main() {
    Y< double > y;

    std::cout << y.foo() << std::endl;
}

Compile with:

g++ -std=gnu++14 test.cpp 

Running gives:

./a.out 
11

How to delete all data from solr and hbase

I made a JavaScript bookmark which adds the delete link in Solr Admin UI

_x000D_
_x000D_
javascript: (function() {_x000D_
    var str, $a, new_href, href, upd_str = 'update?stream.body=<delete><query>*:*</query></delete>&commit=true';_x000D_
    $a = $('#result a#url');_x000D_
    href = $a.attr('href');_x000D_
    str = href.match('.+solr\/.+\/(.*)')[1];_x000D_
    new_href = href.replace(str, upd_str);_x000D_
    $('#result').prepend('<a id="url_upd" class="address-bar" href="' + new_href + '"><strong>DELETE ALL</strong>   ' + new_href + '</a>');_x000D_
})();
_x000D_
_x000D_
_x000D_

enter image description here

How to use SQL LIKE condition with multiple values in PostgreSQL?

Following query helped me. Instead of using LIKE, you can use ~*.

select id, name from hosts where name ~* 'julia|lena|jack';

Python wildcard search in string

Same idea as Yuushi in using regular expressions, but this uses the findall method within the re library instead of a list comprehension:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)

makefiles - compile all c files at once

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

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

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

Powershell: count members of a AD group

Try:

$group = Get-ADGroup -Identity your-group-name -Properties *

$group.members | count

This worked for me for a group with over 17000 members.

Capture key press without placing an input element on the page?

Code & detects ctrl+z

document.onkeyup = function(e) {
  if(e.ctrlKey && e.keyCode == 90) {
    // ctrl+z pressed
  }
}

Node Version Manager install - nvm command not found

For my case, it because I use fish. if I not start fish, just type nvm will no error now.

How to validate a file upload field using Javascript/jquery

Simple and powerful way(dynamic validation)

place formats in array like "image/*"

_x000D_
_x000D_
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{

console.log(upload.value)
})
_x000D_
<input type="file" id="upload" >
_x000D_
_x000D_
_x000D_

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

How do I set a textbox's value using an anchor with jQuery?

Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.

Getting the SQL from a Django QuerySet

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

Aggregate a dataframe on a given column and display another column

A base R solution is to combine the output of aggregate() with a merge() step. I find the formula interface to aggregate() a little more useful than the standard interface, partly because the names on the output are nicer, so I'll use that:

The aggregate() step is

maxs <- aggregate(Score ~ Group, data = dat, FUN = max)

and the merge() step is simply

merge(maxs, dat)

This gives us the desired output:

R> maxs <- aggregate(Score ~ Group, data = dat, FUN = max)
R> merge(maxs, dat)
  Group Score Info
1     1     3    c
2     2     4    d

You could, of course, stick this into a one-liner (the intermediary step was more for exposition):

merge(aggregate(Score ~ Group, data = dat, FUN = max), dat)

The main reason I used the formula interface is that it returns a data frame with the correct names for the merge step; these are the names of the columns from the original data set dat. We need to have the output of aggregate() have the correct names so that merge() knows which columns in the original and aggregated data frames match.

The standard interface gives odd names, whichever way you call it:

R> aggregate(dat$Score, list(dat$Group), max)
  Group.1 x
1       1 3
2       2 4
R> with(dat, aggregate(Score, list(Group), max))
  Group.1 x
1       1 3
2       2 4

We can use merge() on those outputs, but we need to do more work telling R which columns match up.

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

How do I echo and send console output to a file in a bat script?

My option was this:

Create a subroutine that takes in the message and automates the process of sending it to both console and log file.

setlocal
set logfile=logfile.log

call :screenandlog "%DATE% %TIME% This message goes to the screen and to the log"    

goto :eof

:screenandlog
set message=%~1
echo %message% & echo %message% >> %logfile%
exit /b

If you add a variable to the message, be sure to remove the quotes in it before sending it to the subroutine or it can screw your batch. Of course this only works for echoing.

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

How do I get the entity that represents the current user in Symfony2?

$this->container->get('security.token_storage')->getToken()->getUser();

Can't find file executable in your configured search path for gnc gcc compiler

For that you need to install binary of GNU GCC compiler, which comes with MinGW package. You can download MinGW( and put it under C:/ ) and later you have to download gnu -c, c++ related Binaries, so select required package and install them(in the MinGW ). Then in the Code::Blocks, go to Setting, Compiler, ToolChain Executable. In that you will find Path, there set C:/MinGW. Then mentioned error will be vanished.

Use of Finalize/Dispose method in C#

I agree with pm100 (and should have explicitly said this in my earlier post).

You should never implement IDisposable in a class unless you need it. To be very specific, there are about 5 times when you would ever need/should implement IDisposable:

  1. Your class explicitly contains (i.e. not via inheritance) any managed resources which implement IDisposable and should be cleaned up once your class is no longer used. For example, if your class contains an instance of a Stream, DbCommand, DataTable, etc.

  2. Your class explicitly contains any managed resources which implement a Close() method - e.g. IDataReader, IDbConnection, etc. Note that some of these classes do implement IDisposable by having Dispose() as well as a Close() method.

  3. Your class explicitly contains an unmanaged resource - e.g. a COM object, pointers (yes, you can use pointers in managed C# but they must be declared in 'unsafe' blocks, etc. In the case of unmanaged resources, you should also make sure to call System.Runtime.InteropServices.Marshal.ReleaseComObject() on the RCW. Even though the RCW is, in theory, a managed wrapper, there is still reference counting going on under the covers.

  4. If your class subscribes to events using strong references. You need to unregister/detach yourself from the events. Always to make sure these are not null first before trying to unregister/detach them!.

  5. Your class contains any combination of the above...

A recommended alternative to working with COM objects and having to use Marshal.ReleaseComObject() is to use the System.Runtime.InteropServices.SafeHandle class.

The BCL (Base Class Library Team) has a good blog post about it here http://blogs.msdn.com/bclteam/archive/2005/03/16/396900.aspx

One very important note to make is that if you are working with WCF and cleaning up resources, you should ALMOST ALWAYS avoid the 'using' block. There are plenty of blog posts out there and some on MSDN about why this is a bad idea. I have also posted about it here - Don't use 'using()' with a WCF proxy

How to send a PUT/DELETE request in jQuery?

If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".

$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...

Must works for others Frameworks

Note: Tested with Laravel 5.6 and jQuery 3

Eclipse internal error while initializing Java tooling

I was facing the same issue in eclipse so I am telling you the same step that I did you just need to go eclipse installed folder where you will find the file named eclipse.ini in my case the location was

C:\Users\comp\eclipse\jee-2018-12\eclipse

you can find your location.

in that location, open eclipse.ini in text mode and there you will find some below text
-Xms256m -Xmx1024m

change it to

-Xms512m -Xmx1024m

I hope that will help you 100% as checked in my System ;-)

A python class that acts like dict

Here is an alternative solution:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

a = AttrDict()
a.a = 1
a.b = 2

How can I override inline styles with external CSS?

used !important in CSS property

<div style="color: red;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
        color: blue !important;
    }

How to read/write from/to file using Go?

New Way

Starting with Go 1.16, use os.ReadFile to load the file to memory, use os.WriteFile to write to a file from memory.

Be careful with the os.ReadFile because it reads the whole file into memory.

package main

import "os"

func main() {
    b, err := os.ReadFile("input.txt")
    if err != nil {
        log.Fatal(err)
    }

    // `data` contains everything your file does
    // This writes it to the Standard Out
    os.Stdout.Write(data)

    // You can also write it to a file as a whole
    err = os.WriteFile("destination.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

Why should text files end with a newline?

Why should (text) files end with a newline?

As well expressed by many, because:

  1. Many programs do not behave well, or fail without it.

  2. Even programs that well handle a file lack an ending '\n', the tool's functionality may not meet the user's expectations - which can be unclear in this corner case.

  3. Programs rarely disallow final '\n' (I do not know of any).


Yet this begs the next question:

What should code do about text files without a newline?

  1. Most important - Do not write code that assumes a text file ends with a newline. Assuming a file conforms to a format leads to data corruption, hacker attacks and crashes. Example:

    // Bad code
    while (fgets(buf, sizeof buf, instream)) {
      // What happens if there is no \n, buf[] is truncated leading to who knows what
      buf[strlen(buf) - 1] = '\0';  // attempt to rid trailing \n
      ...
    }
    
  2. If the final trailing '\n' is needed, alert the user to its absence and the action taken. IOWs, validate the file's format. Note: This may include a limit to the maximum line length, character encoding, etc.

  3. Define clearly, document, the code's handling of a missing final '\n'.

  4. Do not, as possible, generate a file the lacks the ending '\n'.

Go to particular revision

Using a commit's SHA1 key, you could do the following:

  • First, find the commit you want for a specific file:

    git log -n <# commits> <file-name>

    This, based on your <# commits>, will generate a list of commits for a specific file.

    TIP: if you aren't sure what commit you are looking for, a good way to find out is using the following command: git diff <commit-SHA1>..HEAD <file-name>. This command will show the difference between the current version of a commit, and a previous version of a commit for a specific file.

    NOTE: a commit's SHA1 key is formatted in the git log -n's list as:

commit <SHA1 id>

  • Second, checkout the desired version:

    If you have found the desired commit/version you want, simply use the command: git checkout <desired-SHA1> <file-name>

    This will place the version of the file you specified in the staging area. To take it out of the staging area simply use the command: reset HEAD <file-name>

To revert back to where the remote repository is pointed to, simply use the command: git checkout HEAD <file-name>

Python style - line continuation with strings?

I've gotten around this with

mystr = ' '.join(
        ["Why, hello there",
         "wonderful stackoverflow people!"])

in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to merge two PDF files into one in Java?

Multiple pdf merged method using org.apache.pdfbox:

public void mergePDFFiles(List<File> files,
                          String mergedFileName) {
    try {
        PDFMergerUtility pdfmerger = new PDFMergerUtility();
        for (File file : files) {
            PDDocument document = PDDocument.load(file);
            pdfmerger.setDestinationFileName(mergedFileName);
            pdfmerger.addSource(file);
            pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
            document.close();
        }
    } catch (IOException e) {
        logger.error("Error to merge files. Error: " + e.getMessage());
    }
}

From main program, call mergePDFFiles method using list of files and target file name.

        String mergedFileName = "Merged.pdf";
        mergePDFFiles(files, mergedFileName);

After calling mergePDFFiles, load merged file

        File mergedFile = new File(mergedFileName);

What is the difference between atan and atan2 in C++?

Another thing to mention is that atan2 is more stable when computing tangents using an expression like atan(y / x) and x is 0 or close to 0.

How to solve "Fatal error: Class 'MySQLi' not found"?

I'm using xampp and my problem was fixed once i rename:

extension_dir = "ext"

to

extension_dir = "C:\xampp\php\ext"

PS: Don't forget to restart apache after making this change!

How to SHUTDOWN Tomcat in Ubuntu?

if you are run this command

 debian@debian:~$  /usr/share/tomcat7/bin/shutdown.sh
 then your server will not stop and you will get o/p like that you provided if you use in 
 super user mode then effect will appear o/p will come like this

 debian@debian:~$ sudo /usr/share/tomcat7/bin/shutdown.sh
 [sudo] password for debian: 
 Using CATALINA_BASE:   /var/lib/tomcat
 Using CATALINA_HOME:   /var/lib/tomcat
 Using CATALINA_TMPDIR: /var/lib/tomcat/temp
 Using JRE_HOME:        /usr/lib/jvm/java-1.6.0-openjdk
 Using CLASSPATH:   /var/lib/tomcat/bin/bootstrap.jar:/var/lib/tomcat/bin/tomcat-juli.jar

Getting the docstring from a function

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Dynamic classname inside ngClass in angular 2

  <div *ngFor="let celeb of singers">
  <p [ngClass]="{
    'text-success':celeb.country === 'USA',
    'text-secondary':celeb.country === 'Canada',
    'text-danger':celeb.country === 'Puorto Rico',
    'text-info':celeb.country === 'India'
  }">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

Example:

@Component({
    selector: 'widget-three',
    template: `<input #input1 type="text">`
})
export class WidgetThree{
    @ViewChild('input1') input1;

    constructor(private renderer:Renderer){}

    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input1.nativeElement,
            'focus',
            []
        )
    }
}

Assignment makes pointer from integer without cast

strToLower's return type should be char* not char (or it should return nothing at all, since it doesn't re-allocate the string)

Convert String to double in Java

Using Double.parseDouble() without surrounding try/catch block can cause potential NumberFormatException had the input double string not conforming to a valid format.

Guava offers a utility method for this which returns null in case your String can't be parsed.

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Doubles.html#tryParse(java.lang.String)

Double valueDouble = Doubles.tryParse(aPotentiallyCorruptedDoubleString);

In runtime, a malformed String input yields null assigned to valueDouble

How do I declare an array variable in VBA?

As pointed out by others, your problem is that you have not declared an array

Below I've tried to recreate your program so that it works as you intended. I tried to leave as much as possible as it was (such as leaving your array as a variant)

Public Sub Testprog()
    '"test()" is an array, "test" is not
    Dim test() As Variant
    'I am assuming that iCounter is the array size
    Dim iCounter As Integer

    '"On Error Resume Next" just makes us skip over a section that throws the error
    On Error Resume Next

    'if test() has not been assigned a UBound or LBound yet, calling either will throw an error
    '   without an LBound and UBound an array won't hold anything (we will assign them later)

    'Array size can be determined by (UBound(test) - LBound(test)) + 1
    If (UBound(test) - LBound(test)) + 1 > 0 Then
        iCounter = (UBound(test) - LBound(test)) + 1

        'So that we don't run the code that deals with UBound(test) throwing an error
        Exit Sub
    End If

    'All the code below here will run if UBound(test)/LBound(test) threw an error
    iCounter = 0

    'This makes LBound(test) = 0
    '   and UBound(test) = iCounter where iCounter is 0
    '   Which gives us one element at test(0)
    ReDim Preserve test(0 To iCounter)

    test(iCounter) = "test"
End Sub

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

How to convert Java String into byte[]?

You can use String.getBytes() which returns the byte[] array.

In Windows cmd, how do I prompt for user input and use the result in another command?

Try this:

@echo off
set /p id="Enter ID: "

You can then use %id% as a parameter to another batch file like jstack %id%.

For example:

set /P id=Enter id: 
jstack %id% > jstack.txt

Angular update object in object array

Another approach could be:

let myList = [{id:'aaa1', name: 'aaa'}, {id:'bbb2', name: 'bbb'}, {id:'ccc3', name: 'ccc'}];
let itemUpdated = {id: 'aaa1', name: 'Another approach'};

myList.find(item => item.id == itemUpdated.id).name = itemUpdated.name;

Android Shared preferences for creating one time activity (example)

Best way to create SharedPreference and for global usage you need to create a class like below:

public class PreferenceHelperDemo {
    private final SharedPreferences mPrefs;

    public PreferenceHelperDemo(Context context) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    }

    private String PREF_Key= "Key";

    public String getKey() {
        String str = mPrefs.getString(PREF_Key, "");
        return str;
    }

    public void setKey(String pREF_Key) {
        Editor mEditor = mPrefs.edit();
        mEditor.putString(PREF_Key, pREF_Key);
        mEditor.apply();
    }

}

Split array into two parts without for loop in java

copyOfRange

This does what you want without you having to create a new array as it returns a new array.

int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);

Replace spaces with dashes and make all letters lower-case

You can also use split and join:

"Sonic Free Games".split(" ").join("-").toLowerCase(); //sonic-free-games

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

setTimeout or setInterval?

Well, setTimeout is better in one situation, as I have just learned. I always use setInterval, which i have left to run in the background for more than half an hour. When i switched back to that tab, the slideshow (on which the code was used) was changing very rapidly, instead of every 5 seconds that it should have. It does in fact happen again as i test it more and whether it's the browser's fault or not isn't important, because with setTimeout that situation is completely impossible.

How do I compile the asm generated by GCC?

gcc can use an assembly file as input, and invoke the assembler as needed. There is a subtlety, though:

  • If the file name ends with ".s" (lowercase 's'), then gcc calls the assembler.
  • If the file name ends with ".S" (uppercase 'S'), then gcc applies the C preprocessor on the source file (i.e. it recognizes directives such as #if and replaces macros), and then calls the assembler on the result.

So, on a general basis, you want to do things like this:

gcc -S file.c -o file.s
gcc -c file.s

Auto highlight text in a textbox control

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

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

How can I create an Asynchronous function in Javascript?

Late, but to show an easy solution using promises after their introduction in ES6, it handles asynchronous calls a lot easier:

You set the asynchronous code in a new promise:

var asyncFunct = new Promise(function(resolve, reject) {
    $('#link').animate({ width: 200 }, 2000, function() {
        console.log("finished");                
        resolve();
    });             
});

Note to set resolve() when async call finishes.
Then you add the code that you want to run after async call finishes inside .then() of the promise:

asyncFunct.then((result) => {
    console.log("Exit");    
});

Here is a snippet of it:

_x000D_
_x000D_
$('#link').click(function () {_x000D_
    console.log("Enter");_x000D_
    var asyncFunct = new Promise(function(resolve, reject) {_x000D_
        $('#link').animate({ width: 200 }, 2000, function() {_x000D_
            console.log("finished");             _x000D_
            resolve();_x000D_
        });    _x000D_
    });_x000D_
    asyncFunct.then((result) => {_x000D_
        console.log("Exit");    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="link">Link</a>_x000D_
<span>Moving</span>
_x000D_
_x000D_
_x000D_

or JSFiddle

What does `set -x` do?

set -x

Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.

[source]

Example

set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30

set +x
echo `expr 10 + 20 `
30

Above example illustrates the usage of set -x. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.

  • First step expr has been evaluated.
  • Second step echo has been evaluated.

To know more about set ? visit this link

when it comes to your shell script,

[ "$DEBUG" == 'true' ] && set -x

Your script might have been printing some additional lines of information when the execution mode selected as DEBUG. Traditionally people used to enable debug mode when a script called with optional argument such as -d

Java - removing first character of a string

public String removeFirstChar(String s){
   return s.substring(1);
}

PDF to byte array and vice versa

Are'nt you creating the pdf file but not actually writing the byte array back? Therefore you cannot open the PDF.

out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
out.Write(b, 0, b.Length);
out.Position = 0;
out.Close();

This is in addition to correctly reading in the PDF to byte array.

Delete specified file from document directory

In Swift both 3&4

 func removeImageLocalPath(localPathName:String) {
            let filemanager = FileManager.default
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true)[0] as NSString
            let destinationPath = documentsPath.appendingPathComponent(localPathName)
 do {
        try filemanager.removeItem(atPath: destinationPath)
        print("Local path removed successfully")
    } catch let error as NSError {
        print("------Error",error.debugDescription)
    }
    }

or This method can delete all local file

func deletingLocalCacheAttachments(){
        let fileManager = FileManager.default
        let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            if fileURLs.count > 0{
                for fileURL in fileURLs {
                    try fileManager.removeItem(at: fileURL)
                }
            }
        } catch {
            print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
        }
    }

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The fix is to stop using correlated subqueries and use joins instead. Correlated subqueries are essentially cursors as they cause the query to run row-by-row and should be avoided.

You may need a derived table in the join in order to get the value you want in the field if you want only one record to match, if you need both values then the ordinary join will do that but you will get multiple records for the same id in the results set. If you only want one, you need to decide which one and do that in the code, you could use a top 1 with an order by, you could use max(), you could use min(), etc, depending on what your real requirement for the data is.

Setting JDK in Eclipse

Eclipse's compiler can assure that your java sources conform to a given JDK version even if you don't have that version installed. This feature is useful for ensuring backwards compatibility of your code.

Your code will still be compiled and run by the JDK you've selected.

Check if table exists without using "select from"

This modified solution from above does not require explicit knowledge of the current database. It is then more flexible.

SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable' 
AND TABLE_SCHEMA in (SELECT DATABASE());

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

Why can't I set text to an Android TextView?

The code should instead be something like this:

TextView text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("test");

Vue js error: Component template should contain exactly one root element

For a more complete answer: http://www.compulsivecoders.com/tech/vuejs-component-template-should-contain-exactly-one-root-element/

But basically:

  • Currently, a VueJS template can contain only one root element (because of rendering issue)
  • In cases you really need to have two root elements because HTML structure does not allow you to create a wrapping parent element, you can use vue-fragment.

To install it:

npm install vue-fragment

To use it:

import Fragment from 'vue-fragment';
Vue.use(Fragment.Plugin);

// or

import { Plugin } from 'vue-fragment';
Vue.use(Plugin);

Then, in your component:

<template>
  <fragment>
    <tr class="hola">
      ...
    </tr>
    <tr class="hello">
      ...
    </tr>
  </fragment>
</template>

How do I get a decimal value when using the division operator in Python?

Other answers suggest how to get a floating-point value. While this wlil be close to what you want, it won't be exact:

>>> 0.4/100.
0.0040000000000000001

If you actually want a decimal value, do this:

>>> import decimal
>>> decimal.Decimal('4') / decimal.Decimal('100')
Decimal("0.04")

That will give you an object that properly knows that 4 / 100 in base 10 is "0.04". Floating-point numbers are actually in base 2, i.e. binary, not decimal.

Fastest way(s) to move the cursor on a terminal command line?

Since this hasn't been closed yet, here are a few more options.

  • Use Ctrl+x followed by Ctrl+e to open the current line in the editor specified by $FCEDIT or $EDITOR or emacs (tried in that order).
  • If you ran the command earlier, hit Ctrl+r for a reverse history search and type option25 (in this case). The line will be displayed. Hit Tab to start editing at this point.
  • Use history expansion with the s/// modifier. E.g. !-2:s/--option25/--newoption/ would rerun the second-to-last command, but replace option25. To modify the last ./cmd command, use the !string syntax: !./cmd:s/--option25/--newoption/
    Any delimiter may be used in place of / in the substitution.
  • If editing the previous line, you can use quick substitution: ^--option25^--newoption
  • Character search. This was mentioned by Pax, and can be done in regular emacs-mode with Ctrl+] for forward search, and Ctrl+Alt+] for backward search.

I recommend the second option. Ctrl+r is really handy and fast, no mucking about with editors, and you see the results before the command is run (unlike the history expansions).

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

How can I get the last character in a string?

It does it:

myString.substr(-1);

This returns a substring of myString starting at one character from the end: the last character.

This also works:

myString.charAt(myString.length-1);

And this too:

myString.slice(-1);

How to read specific lines from a file (by line number)?

if you want line 7

line = open("file.txt", "r").readlines()[7]

How to install gem from GitHub source?

well, that depends on the project in question. Some projects have a *.gemspec file in their root directory. In that case, it would be

gem build GEMNAME.gemspec
gem install gemname-version.gem

Other projects have a rake task, called "gem" or "build" or something like that, in this case you have to invoke "rake ", but that depends on the project.

In both cases you have to download the source.

In jQuery, how do I get the value of a radio button when they all have the same name?

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

$(function(){
    $("#submit").click(function(){      
        alert($('input:radio:checked').val());
    });
 });

Maven Run Project

See the exec maven plugin. You can run Java classes using:

mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ...

The invocation can be as simple as mvn exec:java if the plugin configuration is in your pom.xml. The plugin site on Mojohaus has a more detailed example.

<project>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>com.example.Main</mainClass>
                    <arguments>
                        <argument>argument1</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Modifying location.hash without page scrolling

Here's my solution for history-enabled tabs:

    var tabContainer = $(".tabs"),
        tabsContent = tabContainer.find(".tabsection").hide(),
        tabNav = $(".tab-nav"), tabs = tabNav.find("a").on("click", function (e) {
                e.preventDefault();
                var href = this.href.split("#")[1]; //mydiv
                var target = "#" + href; //#myDiv
                tabs.each(function() {
                    $(this)[0].className = ""; //reset class names
                });
                tabsContent.hide();
                $(this).addClass("active");
                var $target = $(target).show();
                if ($target.length === 0) {
                    console.log("Could not find associated tab content for " + target);
                } 
                $target.removeAttr("id");
                // TODO: You could add smooth scroll to element
                document.location.hash = target;
                $target.attr("id", href);
                return false;
            });

And to show the last-selected tab:

var currentHashURL = document.location.hash;
        if (currentHashURL != "") { //a tab was set in hash earlier
            // show selected
            $(currentHashURL).show();
        }
        else { //default to show first tab
            tabsContent.first().show();
        }
        // Now set the tab to active
        tabs.filter("[href*='" + currentHashURL + "']").addClass("active");

Note the *= on the filter call. This is a jQuery-specific thing, and without it, your history-enabled tabs will fail.

Rest-assured. Is it possible to extract value from request json?

You can also do like this if you're only interested in extracting the "user_id":

String userId = 
given().
        contentType("application/json").
        body(requestBody).
when().
        post("/admin").
then().
        statusCode(200).
extract().
        path("user_id");

In its simplest form it looks like this:

String userId = get("/person").path("person.userId");

What is the difference between a URI, a URL and a URN?

URI => http://en.wikipedia.org/wiki/Uniform_Resource_Identifier

URL's are a subset of URI's (which also contain URNs).

Basically, a URI is a general identifier, where a URL specifies a location and a URN specifies a name.

How do I search a Perl array for a matching string?

For just a boolean match result or for a count of occurrences, you could use:

use 5.014; use strict; use warnings;
my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
my $patterns=join(',',@foo);
for my $str (qw(quux world hello hEllO)) {
    my $count=map {m/^$str$/i} @foo;
    if ($count) {
        print "I found '$str' $count time(s) in '$patterns'\n";
    } else {
        print "I could not find '$str' in the pattern list\n"
    };
}

Output:

I could not find 'quux' in the pattern list
I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'

Does not require to use a module.
Of course it's less "expandable" and versatile as some code above.
I use this for interactive user answers to match against a predefined set of case unsensitive answers.

HTML input fields does not get focus when clicked

I had this problem for over 6 months, it may be the same issue. Main symptom is that you can't move the cursor or select text in text inputs, only the arrow keys allow you to move around in the input field. Very annoying problem, especially for textarea input fields. I have this html that gets populated with 1 out of 100s of forms via Javascript:

<div class="dialog" id="alert" draggable="true">
    <div id="head" class="dialog_head">
        <img id='icon' src='images/icon.png' height=20 width=20><img id='icon_name' src='images/icon_name.png' height=15><img id='alert_close_button' class='close_button' src='images/close.png'>
    </div>
    <div id="type" class="type"></div>
    <div class='scroll_div'>
        <div id="spinner" class="spinner"></div>
        <div id="msg" class="msg"></div>
        <div id="form" class="form"></div>
    </div>
</div>

Apparently 6 months ago I had tried to make the popup draggable and failed, breaking text inputs at the same time. Once I removed draggable="true" it works again!

Moving up one directory in Python

>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\

MySQL error 1449: The user specified as a definer does not exist

The problem is clear - MySQL cannot find user specified as the definer.

I encountered this problem after synchronizing database model from development server, applying it to localhost, making changes to the model and then reapplying it to localhost. Apparently there was a view (I modified) defined and so I couldn't update my local version.

How to fix (easily):

Note: it involves deleting so it works just fine for views but make sure you have data backed-up if you try this on tables.

  1. Login to database as root (or whatever has enough power to make changes).
  2. Delete view, table or whatever you are having trouble with.
  3. Synchronize your new model - it will not complain about something that does not exist now. You may want to remove SQL SECURITY DEFINER part from the item definition you had problems with.

P.S. This is neither a proper nor best-all-around fix. I just posted it as a possible (and very simple) solution.

insert a NOT NULL column to an existing table

This worked for me, can also be "borrowed" from the design view, make changes -> right click -> generate change script.

BEGIN TRANSACTION
GO
ALTER TABLE dbo.YOURTABLE ADD
    YOURCOLUMN bit NOT NULL CONSTRAINT DF_YOURTABLE_YOURCOLUMN DEFAULT 0
GO
COMMIT

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

What you have written in your sql string is a Timestamp not Date. You must convert it to Date or change type of database field to Timestamp for it to be seen correctly.

How can I create a self-signed cert for localhost?

you could try mkcert.

macos: brew install mkcert

Copy an entire worksheet to a new worksheet in Excel 2010

If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.

Sub sbInsertWorksheetAfter()

    'This adds a new visible worksheet after the last visible worksheet

    ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

    'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created

    ThisWorkbook.Sheets("Master").Cells.Copy _
        Destination:=ActiveSheet.Cells

    'This gives the the new ActiveSheet a default name

    With ActiveSheet
        .Name = Sheet12.Name & " copied"
    End With

    'This changes the name of the ActiveSheet to the user's preference

    Dim sheetname As String

    With ActiveSheet
        sheetname = InputBox("Enter name of this Worksheet")
        .Name = sheetname
    End With

End Sub

Why am I getting an OPTIONS request instead of a GET request?

If you're trying to POST

Make sure to JSON.stringify your form data and send as text/plain.

<form id="my-form" onSubmit="return postMyFormData();">
    <input type="text" name="name" placeholder="Your Name" required>
    <input type="email" name="email" placeholder="Your Email" required>
    <input type="submit" value="Submit My Form">
</form>

function postMyFormData() {

    var formData = $('#my-form').serializeArray();
    formData = formData.reduce(function(obj, item) {
        obj[item.name] = item.value;
        return obj;
    }, {});
    formData = JSON.stringify(formData);

    $.ajax({
        type: "POST",
        url: "https://website.com/path",
        data: formData,
        success: function() { ... },
        dataType: "text",
        contentType : "text/plain"
    });
}

Detect IF hovering over element with jQuery

It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.

jQuery.fn.mouseIsOver = function () {
    return $(this).parent().find($(this).selector + ":hover").length > 0;
}; 

http://jsfiddle.net/Wp2v4/1/

What is a superfast way to read large files line-by-line in VBA?

With that code you load the file in memory (as a big string) and then you read that string line by line.

By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.

git clone: Authentication failed for <URL>

I had the same issue when Cloning the repository via Bash/VS Code with "fatal:Authentication failed". I used SSH Key authentication instead to connect my repository following the article: [https://docs.microsoft.com/en-us/azure/devops/repos/git/use-ssh-keys-to-authenticate?view=azure-devops&tabs=current-page][1] I didn't get any errors after with any bash commands!

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

What is a regular expression for a MAC Address?

This link might help you. You can use this : (([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})

'Framework not found' in Xcode

delete all frameworks from Embedded Binaries and re-add it

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

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

 $(this).siblings(':not(.closedTab)');

Escaping a forward slash in a regular expression

What context/language? Some languages use / as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the / has is it may be the designated pattern delimiter.

IF statement: how to leave cell blank if condition is false ("" does not work)

You can do something like this to show blank space:

=IF(AND((E2-D2)>0)=TRUE,E2-D2," ")

Inside if before first comma is condition then result and return value if true and last in value as blank if condition is false

Select data from date range between two dates

Here is a query to find all product sales that were running during the month of August

  • Find Product_sales there were active during the month of August
  • Include anything that started before the end of August
  • Exclude anything that ended before August 1st

Also adds a case statement to validate the query

SELECT start_date, 
       end_date, 
       CASE 
         WHEN start_date <= '2015-08-31' THEN 'true' 
         ELSE 'false' 
       END AS started_before_end_of_month, 
       CASE 
         WHEN NOT end_date <= '2015-08-01' THEN 'true' 
         ELSE 'false' 
       END AS did_not_end_before_begining_of_month 
FROM   product_sales 
WHERE  start_date <= '2015-08-31' 
       AND end_date >= '2015-08-01' 
ORDER  BY start_date; 

Assign static IP to Docker container

You can access other containers' service by their name(ping apachewill get the ip or curl http://apache would access the http service) And this can be a alternative of a static ip.

I want to convert std::string into a const wchar_t *

If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).

  • mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.

  • wcs stand for Wide Char String and is an array of wchar_t.

For more background details on wide chars have a look at glibc documentation here.

Creating a system overlay window (always on top)

Actually, you can try WindowManager.LayoutParams.TYPE_SYSTEM_ERROR instead of TYPE_SYSTEM_OVERLAY. It may sound like a hack, but it let you display view on top of everything and still get touch events.

How do I get a file name from a full path with PHP?

With SplFileInfo:

SplFileInfo The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Ref: http://php.net/manual/en/splfileinfo.getfilename.php

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

o/p: string(7) "foo.txt"

Convert String XML fragment to Document Node in Java

...and if you're using purely XOM, something like this:

    String xml = "<fakeRoot>" + xml + "</fakeRoot>";
    Document doc = new Builder( false ).build( xml, null );
    Nodes children = doc.getRootElement().removeChildren();
    for( int ix = 0; ix < children.size(); ix++ ) {
        otherDocumentElement.appendChild( children.get( ix ) );
    }

XOM uses fakeRoot internally to do pretty much the same, so it should be safe, if not exactly elegant.

Get current date in milliseconds

extension NSDate {

    func toMillis() -> NSNumber {
        return NSNumber(longLong:Int64(timeIntervalSince1970 * 1000))
    }

    static func fromMillis(millis: NSNumber?) -> NSDate? {
        return millis.map() { number in NSDate(timeIntervalSince1970: Double(number) / 1000)}
    }

    static func currentTimeInMillis() -> NSNumber {
        return NSDate().toMillis()
    }
}

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use &check; for ✓ and &cross; for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.

As mentioned in the comments, &check; and &cross; are not supported in HTML4, so you may be better off using the more cryptic &#x2713; and &#x2717; if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info: https://developers.google.com/apps-script/guides/menus

enter image description here enter image description here enter image description here

What's the difference between %s and %d in Python string formatting?

speaking of which ...
python3.6 comes with f-strings which makes things much easier in formatting!
now if your python version is greater than 3.6 you can format your strings with these available methods:

name = "python"

print ("i code with %s" %name)          # with help of older method
print ("i code with {0}".format(name))  # with help of format
print (f"i code with {name}")           # with help of f-strings

How to generate random number in Bash?

Please see $RANDOM:

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. It should not be used to generate an encryption key.

Like Operator in Entity Framework?

You can use a real like in Link to Entities quite easily

Add

    <Function Name="String_Like" ReturnType="Edm.Boolean">
      <Parameter Name="searchingIn" Type="Edm.String" />
      <Parameter Name="lookingFor" Type="Edm.String" />
      <DefiningExpression>
        searchingIn LIKE lookingFor
      </DefiningExpression>
    </Function>

to your EDMX in this tag:

edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema

Also remember the namespace in the <schema namespace="" /> attribute

Then add an extension class in the above namespace:

public static class Extensions
{
    [EdmFunction("DocTrails3.Net.Database.Models", "String_Like")]
    public static Boolean Like(this String searchingIn, String lookingFor)
    {
        throw new Exception("Not implemented");
    }
}

This extension method will now map to the EDMX function.

More info here: http://jendaperl.blogspot.be/2011/02/like-in-linq-to-entities.html

Setting background-image using jQuery CSS property

Further to the other answers, you can also use "background". This is particularly useful when you want to set other properties relating to the way the image is used by the background, such as:

$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath.

/html/body/div[1]/section/div/div[2]/div/form/div[2]/input[3]

Relative Xpath: Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.

Below is the example of a relative XPath.

//input[@name=’email’]