Programs & Examples On #Relational

What's the best practice for primary keys in tables?

I look for natural primary keys and use them where I can.

If no natural keys can be found, I prefer a GUID to a INT++ because SQL Server use trees, and it is bad to always add keys to the end in trees.

On tables that are many-to-many couplings I use a compound primary key of the foreign keys.

Because I'm lucky enough to use SQL Server I can study execution plans and statistics with the profiler and the query analyzer and find out how my keys are performing very easily.

Loading all images using imread from a given folder

you can use glob function to do this. see the example

import cv2
import glob
for img in glob.glob("path/to/folder/*.png"):
    cv_img = cv2.imread(img)

How do I right align div elements?

If you are using bootstrap, then:

<div class="pull-right"></div>

How to access the contents of a vector from a pointer to the vector in C++?

There are many solutions, here's a few I've come up with:

int main(int nArgs, char ** vArgs)
{
    vector<int> *v = new vector<int>(10);
    v->at(2); //Retrieve using pointer to member
    v->operator[](2); //Retrieve using pointer to operator member
    v->size(); //Retrieve size
    vector<int> &vr = *v; //Create a reference
    vr[2]; //Normal access through reference
    delete &vr; //Delete the reference. You could do the same with
                //a pointer (but not both!)
}

Command CompileSwift failed with a nonzero exit code in Xcode 10

My problem was I had due to the non-existence of a native Swift CommonCrypto, used a bridging header and a target that with some magic included it in the build. Since CommonCrypto is now native, I solved the problem by removing the target and the #import and instead added an import CommonCrypto where I used it.

Eliminate extra separators below UITableView

Here's another way to do that w/out the grouped table style, and one you'd probably not guess. Adding a header and footer to the table (perhaps one or the other suffices, haven't checked) causes the separators to disappear from the filler/blank rows.

I stumbled onto this because I wanted a little space at the top and bottom of tables to decrease the risk of hitting buttons instead of a table cell with meaty fingers. Here's a method to stick a blank view in as header and footer. Use whatever height you like, you still eliminate the extra separator lines.

- (void) addHeaderAndFooter
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    v.backgroundColor = [UIColor clearColor];
    [self.myTableView setTableHeaderView:v];
    [self.myTableView setTableFooterView:v];
    [v release];
}

In response to @Casebash, I went back to the code in my app ("AcmeLists" List Manager in iTunes store...) and short-circuited the addHeaderAndFooter method to verify. Without it, I have the extra row separators; with the code, I have what you see in this window snap: no table row separators picture. So I'm not sure why it wouldn't have worked for you. Moreover, it makes sense to me that having any custom footer on a table view would necessarily have to stop drawing row separators for blank rows below it. That would be hideous. For reference, I looked at tables where there were more rows than could be viewed on screen, and then for a table with two rows. In both cases, no extraneous separators.

Perhaps your custom views were not actually added. To check that, set the background color to something other than clearColor, e.g., [UIColor redColor]. If you don't see some red bars at the bottom of the table, your footer wasn't set.

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

How can I check whether Google Maps is fully loaded?

In my case, Tile Image loaded from remote url and tilesloaded event was triggered before render the image.

I solved with following dirty way.

var tileCount = 0;
var options = {
    getTileUrl: function(coord, zoom) {
        tileCount++;
        return "http://posnic.com/tiles/?param"+coord;
    },
    tileSize: new google.maps.Size(256, 256),
    opacity: 0.5,
    isPng: true
};
var MT = new google.maps.ImageMapType(options);
map.overlayMapTypes.setAt(0, MT);
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    var checkExist = setInterval(function() {
        if ($('#map_canvas > div > div > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div > div').length === tileCount) {
            callyourmethod();
            clearInterval(checkExist);
        }
    }, 100); // check every 100ms
});

How can I trim beginning and ending double quotes from a string?

To remove the first character and last character from the string, use:

myString = myString.substring(1, myString.length()-1);

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

Adding an arbitrary line to a matplotlib plot in ipython notebook

It's not too late for the newcomers.

plt.axvline(x, color='r')

It takes the range of y as well, using ymin and ymax.

Replace HTML Table with Divs

You can create simple float-based forms without having to lose your liquid layout. For example:

<style type="text/css">
    .row { clear: left; padding: 6px; }
    .row label { float: left; width: 10em; }
    .row .field { display: block; margin-left: 10em; }
    .row .field input, .row .field select {
        width: 100%;
        box-sizing: border-box;
        -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;
    }
</style>

<div class="row">
    <label for="f-firstname">First name</label>
    <span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
</div>
<div class="row">
    <label for="f-state">State</label>
    <span class="field"><select name="state" id="f-state">
        <option value="NY">NY</option>
    </select></span>
</div>

This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.

For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.

How can I delete derived data in Xcode 8?

Go to the root of the project using terminal and then paste the below mentioned line

rm -rf ~/Library/Developer/Xcode/DerivedData

Once it is executed, you can verify by going to Xcode > Preference > Locations -> Tap arrow shows ["DeriveData"] end point.

Convert NSData to String?

Swift 3:

String(data: data, encoding: .utf8)

Firestore Getting documents id from collection

I have tried this

return this.db.collection('items').snapshotChanges().pipe(
          map(actions => {       
            return actions.map(a => {
              const data = a.payload.doc.data() as Item;
              data.id = a.payload.doc.id;
              data.$key = a.payload.doc.id;
              return data;
            });
          })
        );

Mysql - delete from multiple tables with one query

from two tables with foreign key you can try this Query:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition

z-index issue with twitter bootstrap dropdown menu

Solved by removing the -webkit-transform from the navbar:

-webkit-transform: translate3d(0, 0, 0);

pillaged from https://stackoverflow.com/a/12653766/391925

Why do we always prefer using parameters in SQL statements?

In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.

More information about query plan caching

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

http://www.tripadvisor.com/help/what_type_of_tripadvisor_content_is_available

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to pipes.yahoo.com and do a search for existing hotel pipes and you'll get the idea..

What is the difference between _tmain() and main() in C++?

Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello" that would probably end up as "H\0e\0l\0l\0o\0\0\0" and your program would only print the 'H' before it sees what it thinks is a null terminator.

So now you may wonder why it even compiles and links.

Well it compiles because you are allowed to define an overload to a function.

Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.

Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[]) version.

Python - How to cut a string in Python?

s[0:"s".index("&")]

what does this do:

  • take a slice from the string starting at index 0, up to, but not including the index of &in the string.

How to perform OR condition in django queryset?

Just adding this for multiple filters attaching to Q object, if someone might be looking to it. If a Q object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.

an example would be

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')

Here the OR condition and a filter with category of income is taken into account

varbinary to string on SQL Server

"Converting a varbinary to a varchar" can mean different things.

If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it

declare @b varbinary(max)
set @b = 0x5468697320697320612074657374

select cast(@b as varchar(max)) /*Returns "This is a test"*/

This is the equivalent of using CONVERT with a style parameter of 0.

CONVERT(varchar(max), @b, 0)

Other style parameters are available with CONVERT for different requirements as noted in other answers.

Simple JavaScript Checkbox Validation

You can do something like this:

<form action="../" onsubmit="return checkCheckBoxes(this);">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
    if (
    theForm.MyCheckbox.checked == false) 
    {
        alert ('You didn\'t choose any of the checkboxes!');
        return false;
    } else {    
        return true;
    }
}
//-->
</script> 

http://lab.artlung.com/validate-checkbox/

Although less legible imho, this can be done without a separate function definition like this:

<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

Declare a constant array

As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).

I have shortened your slice to make it...shorter...:

func GetLetterGoodness() []float32 {
    return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}

Speed up rsync with Simultaneous/Concurrent File Transfers?

I've developed a python package called: parallel_sync

https://pythonhosted.org/parallel_sync/pages/examples.html

Here is a sample code how to use it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds)

parallelism by default is 10; you can increase it:

from parallel_sync import rsync
creds = {'user': 'myusername', 'key':'~/.ssh/id_rsa', 'host':'192.168.16.31'}
rsync.upload('/tmp/local_dir', '/tmp/remote_dir', creds=creds, parallelism=20)

however note that ssh typically has the MaxSessions by default set to 10 so to increase it beyond 10, you'll have to modify your ssh settings.

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

Float a div right, without impacting on design

What do you mean by impacts? Content will flow around a float. That's how they work.

If you want it to appear above your design, try setting:

z-index: 10;  
position: absolute;  
right: 0;  
top: 0;

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

Is "&#160;" a replacement of "&nbsp;"?

&#160; is the numeric reference for the entity reference &nbsp; — they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.

See the Wikipedia page for the non-breaking space.

Appending a list or series to a pandas DataFrame as a row?

Following onto Mike Chirico's answer... if you want to append a list after the dataframe is already populated...

>>> list = [['f','g']]
>>> df = df.append(pd.DataFrame(list, columns=['col1','col2']),ignore_index=True)
>>> df
  col1 col2
0    a    b
1    d    e
2    f    g

Difference between Activity Context and Application Context

You can see a difference between the two contexts when you launch your app directly from the home screen vs when your app is launched from another app via share intent.

Here a practical example of what "non-standard back stack behaviors", mentioned by @CommonSenseCode, means:

Suppose that you have two apps that communicate with each other, App1 and App2.

Launch App2:MainActivity from launcher. Then from MainActivity launch App2:SecondaryActivity. There, either using activity context or application context, both activities live in the same task and this is ok (given that you use all standard launch modes and intent flags). You can go back to MainActivity with a back press and in the recent apps you have only one task.

Suppose now that you are in App1 and launch App2:MainActivity with a share intent (ACTION_SEND or ACTION_SEND_MULTIPLE). Then from there try to launch App2:SecondaryActivity (always with all standard launch modes and intent flags). What happens is:

  • if you launch App2:SecondaryActivity with application context on Android < 10 you cannot launch all the activities in the same task. I have tried with android 7 and 8 and the SecondaryActivity is always launched in a new task (I guess is because App2:SecondaryActivity is launched with the App2 application context but you're coming from App1 and you didn't launch the App2 application directly. Maybe under the hood android recognize that and use FLAG_ACTIVITY_NEW_TASK). This can be good or bad depending on your needs, for my application was bad.
    On Android 10 the app crashes with the message
    "Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?".
    So to make it work on Android 10 you have to use FALG_ACTIVITY_NEW_TASK and you cannot run all activities in the same task.
    As you can see the behavior is different between android versions, weird.

  • if you launch App2:SecondaryActivity with activity context all goes well and you can run all the activities in the same task resulting in a linear backstack navigation.

I hope I have added some useful information

Hex transparency in colors

I built this small helper method for an android app, may come of use:

 /**
 * @param originalColor color, without alpha
 * @param alpha         from 0.0 to 1.0
 * @return
 */
public static String addAlpha(String originalColor, double alpha) {
    long alphaFixed = Math.round(alpha * 255);
    String alphaHex = Long.toHexString(alphaFixed);
    if (alphaHex.length() == 1) {
        alphaHex = "0" + alphaHex;
    }
    originalColor = originalColor.replace("#", "#" + alphaHex);


    return originalColor;
}

How do I replace whitespaces with underscore?

Python has a built in method on strings called replace which is used as so:

string.replace(old, new)

So you would use:

string.replace(" ", "_")

I had this problem a while ago and I wrote code to replace characters in a string. I have to start remembering to check the python documentation because they've got built in functions for everything.

How to write log file in c#?

as posted by @randymohan, with using statements instead

public static void WriteLog(string strLog)
{
    string logFilePath = @"C:\Logs\Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
    FileInfo logFileInfo = new FileInfo(logFilePath);
    DirectoryInfo logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
    if (!logDirInfo.Exists) logDirInfo.Create();
    using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append))
    {
        using (StreamWriter log = new StreamWriter(fileStream))
        {
            log.WriteLine(strLog);
        }
    }
}

Equivalent to AssemblyInfo in dotnet core/csproj

As you've already noticed, you can control most of these settings in .csproj.

If you'd rather keep these in AssemblyInfo.cs, you can turn off auto-generated assembly attributes.

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> 

If you want to see what's going on under the hood, checkout Microsoft.NET.GenerateAssemblyInfo.targets inside of Microsoft.NET.Sdk.

How do I access the HTTP request header fields via JavaScript?

One way to obtain the headers from JavaScript is using the WebRequest API, which allows us to access the different events that originate from http or websockets, the life cycle that follows is this: WebRequest Lifecycle

So in order to access the headers of a page it would be like this:

    browser.webRequest.onHeadersReceived.addListener(
     (headersDetails)=> {
      console.log("Request: " + headersDetails);
    },
    {urls: ["*://hostName/*"]}
    );`

The issue is that in order to use this API, it must be executed from the browser, that is, the browser object refers to the browser itself (tabs, icons, configuration), and the browser does have access to all the Request and Reponse of any page , so you will have to ask the user for permissions to be able to do this (The permissions will have to be declared in the manifest for the browser to execute them)

And also being part of the browser you lose control over the pages, that is, you can no longer manipulate the DOM, (not directly) so to control the DOM again it would be done as follows:

    browser.webRequest.onHeadersReceived.addListener(
        browser.tabs.executeScript({
        code: 'console.log("Headers success")',
    });
});

or if you want to run a lot of code

    browser.webRequest.onHeadersReceived.addListener(
        browser.tabs.executeScript({
        file: './headersReveiced.js',
    });
});

Also by having control over the browser we can inject CSS and images

Documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived

Default optional parameter in Swift function

It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,

func test(param: Int? = nil)

These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.

So it is always better not to use nil as default value.

Change the content of a div based on selection from dropdown menu

here is a jsfiddle with an example of showing/hiding div's via a select.

HTML:

<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

jQuery:

$(document).ready(function () {
  $('.group').hide();
  $('#option1').show();
  $('#selectMe').change(function () {
    $('.group').hide();
    $('#'+$(this).val()).show();
  })
});

How to compare two double values in Java?

You can use Double.compare; It compares the two specified double values.

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

Which characters make a URL invalid?

To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.

There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.

Excluded US-ASCII Characters disallowed within the URI syntax:

   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.

List of unwise characters are allowed but may cause problems:

   unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Characters that are reserved within a query component and/or have special meaning within a URI/URL:

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/ where the '@' character has special meaning.

Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:

http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg

Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb if using Java with a URI object instance.

Handle spring security authentication exceptions with @ExceptionHandler

Taking answers from @Nicola and @Victor Wing and adding a more standardized way:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UnauthorizedErrorAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {

    private HttpMessageConverter messageConverter;

    @SuppressWarnings("unchecked")
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        MyGenericError error = new MyGenericError();
        error.setDescription(exception.getMessage());

        ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
        outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED);

        messageConverter.write(error, null, outputMessage);
    }

    public void setMessageConverter(HttpMessageConverter messageConverter) {
        this.messageConverter = messageConverter;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        if (messageConverter == null) {
            throw new IllegalArgumentException("Property 'messageConverter' is required");
        }
    }

}

Now, you can inject configured Jackson, Jaxb or whatever you use to convert response bodies on your MVC annotation or XML based configuration with its serializers, deserializers and so on.

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

Php $_POST method to get textarea value

Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you :

Issue using $_POST with a textarea

How to calculate age in T-SQL with years, months, and days

Implemented by arithmetic with ISO formatted date.

declare @now date,@dob date, @now_i int,@dob_i int, @days_in_birth_month int
declare @years int, @months int, @days int
set @now = '2013-02-28' 
set @dob = '2012-02-29' -- Date of Birth

set @now_i = convert(varchar(8),@now,112) -- iso formatted: 20130228
set @dob_i = convert(varchar(8),@dob,112) -- iso formatted: 20120229
set @years = ( @now_i - @dob_i)/10000
-- (20130228 - 20120229)/10000 = 0 years

set @months =(1200 + (month(@now)- month(@dob))*100 + day(@now) - day(@dob))/100 %12
-- (1200 + 0228 - 0229)/100 % 12 = 11 months

set @days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,@dob),112),6)+'01'))
set @days = (sign(day(@now) - day(@dob))+1)/2 * (day(@now) - day(@dob))
          + (sign(day(@dob) - day(@now))+1)/2 * (@days_in_birth_month - day(@dob) + day(@now))
-- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28))
-- Explain: if the days of now is bigger than the days of birth, then diff the two days
--          else add the days of now and the distance from the date of birth to the end of the birth month 
select @years,@months,@days -- 0, 11, 28 

Test Cases

The approach of days is different from the accepted answer, the differences shown in the comments below:

       dob        now  years  months  days 
2012-02-29 2013-02-28      0      11    28  --Days will be 30 if calculated by the approach in accepted answer. 
2012-02-29 2016-02-28      3      11    28  --Days will be 31 if calculated by the approach in accepted answer, since the day of birth will be changed to 28 from 29 after dateadd by years. 
2012-02-29 2016-03-31      4       1     2
2012-01-30 2016-02-29      4       0    30
2012-01-30 2016-03-01      4       1     2  --Days will be 1 if calculated by the approach in accepted answer, since the day of birth will be changed to 30 from 29 after dateadd by years.
2011-12-30 2016-02-29      4       1    30

An short version of Days by case statement:

set @days = CASE WHEN day(@now) >= day(@dob) THEN day(@now) - day(@dob)
                 ELSE @days_in_birth_month - day(@dob) + day(@now) END

If you want the age of years and months only, it could be simpler

set @years = ( @now_i/100 - @dob_i/100)/100
set @months =(12 + month(@now) - month(@dob))%12 
select @years,@months -- 1, 0

NOTE: A very useful link of SQL Server Date Formats

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

Bootstrap how to get text to vertical align in a div container

HTML:

First, we will need to add a class to your text container so that we can access and style it accordingly.

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

WORKING EXAMPLE

Regular Expressions and negating a whole character group

Yes its called negative lookahead. It goes like this - (?!regex here). So abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc.

Similarly there is positive lookahead - (?=regex here). So abc(?=def) will match abc followed by def.

There are also negative and positive lookbehind - (?<!regex here) and (?<=regex here) respectively

One point to note is that the negative lookahead is zero-width. That is, it does not count as having taken any space.

So it may look like a(?=b)c will match "abc" but it won't. It will match 'a', then the positive lookahead with 'b' but it won't move forward into the string. Then it will try to match the 'c' with 'b' which won't work. Similarly ^a(?=b)b$ will match 'ab' and not 'abb' because the lookarounds are zero-width (in most regex implementations).

More information on this page

Find the differences between 2 Excel worksheets?

May be this replay is too late. But hope will help some one looking for a solution

What i did was, I saved both excel file as CSV file and did compare with Windiff.

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

How to get row count using ResultSet in Java?

The ResultSet has it's methods that move the Cursor back and forth depending on the option provided. By default, it's forward moving(TYPE_FORWARD_ONLY ResultSet type). Unless CONSTANTS indicating Scrollability and Update of ResultSet properly, you might end up getting an error. E.g. beforeLast() This method has no effect if the result set contains no rows. Throws Error if it's not TYPE_FORWARD_ONLY.

The best way to check if empty rows got fetched --- Just to insert new record after checking non-existence

if( rs.next() ) {

   Do nothing
} else {
  No records fetched!
}

See here

Remove quotes from a character vector in R

I think I was trying something very similar to the original poster. the get() worked for me, although the name inside the chart was not inherited. Here is the code that worked for me.

#install it if you dont have it
library(quantmod)

# a list of stock tickers
myStocks <- c("INTC", "AAPL", "GOOG", "LTD")

# get some stock prices from default service
getSymbols(myStocks)

# to pause in between plots
par(ask=TRUE)

# plot all symbols
for (i in 1:length(myStocks)) {
    chartSeries(get(myStocks[i]), subset="last 26 weeks")
}

SQL: How do I SELECT only the rows with a unique value on certain column?

I'm a fan of NOT EXISTS

SELECT DISTINCT contract, activity FROM table t1
WHERE NOT EXISTS (
  SELECT * FROM table t2
  WHERE t2.contract = t1.contract AND t2.activity != t1.activity
)

The model backing the <Database> context has changed since the database was created

For Entity Framework 5.0.0.0 - 6.1.3

You DO indeed want to do the following:

1. using System.Data.Entity;   to startup file (console app --> Program.cs / mvc --> global.asax
2. Database.SetInitializer<YourDatabaseContext>(null);

Yes, Matt Frear is correct. UPDATE -EDIT: Caveat is that I agree with others in that instead of adding this code to global.asax added to your DbContext class

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // other code 
    Database.SetInitializer<YOURContext>(null);
    // more code here.
}

As others mentioned this also is good for handling the unit testing.

Currently I am using this with Entity Framework 6.1.3 /.net 4.6.1

I will come back to provide a CORE snippet in the near future.

jQuery - selecting elements from inside a element

Have a look here -- to query a sub-element of an element:

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

How can I combine multiple nested Substitute functions in Excel?

=SUBSTITUTE(text, old_text, new_text)

if: a=!, b=@, c=#,... x=>, y=?, z=~, " "="     "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~     ...     ;}?     ;*(|     ]:;

RULES:

(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")

---so if a=z,b=y,...y=b,z=a, then the result is 
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)

The formula is:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," ","     ")

Is there any WinSCP equivalent for linux?

scp file user@host:/path/on/host

How to set a dropdownlist item as selected in ASP.NET?

You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.

dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;

You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue

dropdownlist.ClearSelection();  
dropdownlist.Items.FindByValue(value).Selected = true;

Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.

If you expect that you may be looking for text/value that wont be present in DropDownList ListItem collection then you must check if you get the ListItem object or null from FindByText or FindByValue before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.

ListItem listItem = dropdownlist.Items.FindByValue(value);

if(listItem != null) 
{
   dropdownlist.ClearSelection();
   listItem.Selected = true;
}

HighCharts Hide Series Name from the Legend

Replace return 'Legend' by return ''

How to use JavaScript to change the form action

I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

function setAction (element, page)
{
  if(checkCondition(page))
  {
    /* Insert a hidden input into the form to set the page as a parameter.
     */
    var input = document.createElement("input");
    input.setAttribute("type","hidden");
    input.setAttribute("name","page");
    input.setAttribute("value",page);
    element.form.appendChild(input);

    /* Change the form's action. This doesn't chage which page is displayed,
     * it just make the URL look right.
     */
    element.form.action = '/' + page;
    element.form.submit();
  }
}

In the form:

<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />

Here are my Apache rewrite rules:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}

I'd be interested in any explanation as to why just setting the action didn't work.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

How to programmatically set cell value in DataGridView?

Do you remember to refresh the dataGridView?

datagridview.refresh();

Import a file from a subdirectory?

  • Create a subdirectory named lib.
  • Create an empty file named lib\__init__.py.
  • In lib\BoxTime.py, write a function foo() like this:

    def foo():
        print "foo!"
    
  • In your client code in the directory above lib, write:

    from lib import BoxTime
    BoxTime.foo()
    
  • Run your client code. You will get:

    foo!
    

Much later -- in linux, it would look like this:

% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc>     print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py

0 directories, 2 files
% python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!

How to get current time in milliseconds in PHP?

This works even if you are on 32-bit PHP:

list($msec, $sec) = explode(' ', microtime());

$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'

Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.


If you need integers, 64-bit PHP is mandatory.

Then you can reuse the above code and cast to (int):

list($msec, $sec) = explode(' ', microtime());

// these parentheses are mandatory otherwise the precedence is wrong!
//                  ?                        ?
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300

Or you can use the good ol' one-liners:

$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300

Bootstrap carousel width and height

Are you trying to make it responsive? If you are then I would just recommend the following:

.tales {
  width: 100%;
}
.carousel-inner{
  width:100%;
  max-height: 200px !important;
}

However, the best way to handle this responsively would be thru the use of media queries like such:

/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {}

/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {}

/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {}

/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {}

/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {}

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I solve this problem by always using the [h] option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.

I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)

The manual for the memoir class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.

How to check type of files without extensions in python?

You can also install the official file binding for Python, a library called file-magic (it does not use ctypes, like python-magic).

It's available on PyPI as file-magic and on Debian as python-magic. For me this library is the best to use since it's available on PyPI and on Debian (and probably other distributions), making the process of deploying your software easier. I've blogged about how to use it, also.

Change the Arrow buttons in Slick slider

This worked for me:

http://codepen.io/anon/pen/qNbWwK

Hide the default buttons in CSS and use:

<!-- In HTML: -->
<p class="left">left</p>
<p class="right">right</p>

/* In the JS file */
$('.slider').slick({
  arrows: false
})

$('.left').click(function(){
  $('.slider').slick('slickPrev');
})

$('.right').click(function(){
  $('.slider').slick('slickNext');
})

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

What is an IIS application pool?

Assume scenario where swimmers swim in swimming pool in the areas reserved for them.what happens if swimmers swim other than the areas reserved for them,the whole thing would become mess.similarly iis uses application pools to seperate one process from another.

How do I use MySQL through XAMPP?

<?php
if(!@mysql_connect('127.0.0.1', 'root', '*your default password*'))
{
    echo "mysql not connected ".mysql_error();
    exit;

}
echo 'great work';
?>

if no error then you will get greatwork as output.

Try it saved my life XD XD

isPrime Function for Python Language

The number 1 is a special case which is considered neither prime nor composite. For more info visit : http://mathworld.wolfram.com/PrimeNumber.html

And, (n**0.5) --> This will give us the "square root" of 'n'. As it is "n raised to the power 0.5 or 1/2"

And WHY do we do that, Take for example the number 400: We can represent it in the form a*b

1*400 = 400
2*200 = 400
4*100 = 400
5*80 = 400
8*50 = 400
10*40 = 400
16*25 = 400
20*20 = 400
25*16 = 400
40*10 = 400
50*8 = 400
80*5 = 400
100*4 = 400
200*2 = 400
400*1 = 400

Square root of 400 is 20: and we can see that we only need to check the divisibility till 20 because, as 'a' reaches 20 'b' starts decreasing... So, ultimately we are checking divisibility with the numbers less than the square root.

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Completely Remove MySQL Ubuntu 14.04 LTS

remove mysql :

sudo apt -y purge mysql*
sudo apt -y autoremove
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

Restart instance :

sudo shutdown -r now

How to use PrintWriter and File classes in Java?

The PrintWriter class can actually create the file for you.

This example works in JDK 1.7+.

// This will create the file.txt in your working directory.

PrintWriter printWriter = null;

try {

    printWriter = new PrintWriter("file.txt", "UTF-8");
    // The second parameter determines the encoding. It can be
    // any valid encoding, but I used UTF-8 as an example.

} catch (FileNotFoundException | UnsupportedEncodingException error) {
    error.printStackTrace();
}

printWriter.println("Write whatever you like in your file.txt");

// Make sure to close the printWriter object otherwise nothing
// will be written to your file.txt and it will be blank.
printWriter.close();

For a list of valid encodings, see the documentation.

Alternatively, you can just pass the file path to the PrintWriter class without declaring the encoding.

How to reset selected file with input tag file type in Angular 2?

You can use ViewChild to access the input in your component. First, you need to add #someValue to your input so you can read it in the component:

<input #myInput type="file" placeholder="File Name" name="filename" (change)="onChange($event)">

Then in your component you need to import ViewChild from @angular/core:

import { ViewChild } from '@angular/core';

Then you use ViewChild to access the input from template:

@ViewChild('myInput')
myInputVariable: ElementRef;

Now you can use myInputVariable to reset the selected file because it's a reference to input with #myInput, for example create method reset() that will be called on click event of your button:

reset() {
    console.log(this.myInputVariable.nativeElement.files);
    this.myInputVariable.nativeElement.value = "";
    console.log(this.myInputVariable.nativeElement.files);
}

First console.log will print the file you selected, second console.log will print an empty array because this.myInputVariable.nativeElement.value = ""; deletes selected file(s) from the input. We have to use this.myInputVariable.nativeElement.value = ""; to reset the value of the input because input's FileList attribute is readonly, so it is impossible to just remove item from array. Here's working Plunker.

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

How do you dynamically add elements to a ListView on Android?

The short answer: when you create a ListView you pass it a reference to the data. Now, whenever this data will be altered, it will affect the list view and thus add the item to it, after you'll call adapter.notifyDataSetChanged();.

If you're using a RecyclerView, update only the last element (if you've added it at the end of the list of objs) to save memory with: mAdapter.notifyItemInserted(mItems.size() - 1);

IF...THEN...ELSE using XML

Personally, I would prefer

<IF>
  <TIME from="5pm" to="9pm" />
  <THEN>
    <!-- action -->
  </THEN>
  <ELSE>
    <!-- action -->
  </ELSE>
</IF>

In this way you don't need an id attribute to tie together the IF, THEN, ELSE tags

React - How to pass HTML tags in props?

Here is a solution that doesn't use the dangerouslySetInnerHTML which is dangerous as the name says.

import { IntlProvider, FormattedMessage } from "react-intl";

<FormattedMessage
          id="app.greeting"
          description="Bold text example"
          defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
          values={{
            b: (chunks) => <b>{chunks}</b>,
            i: (chunks) => <i>{chunks}</i>,
            a: (chunks) => (
              <a class="external_link" target="_blank" href="https://jiga.dev/">
                {chunks}
              </a>
            )
          }}
        />

This should be rendered as:

react jiga.dev

Full example in https://jiga.dev/react-render-string-with-html-tags-from-props/

Tooltips for cells in HTML table (no Javascript)

Yes. You can use the title attribute on cell elements, with poor usability, or you can use CSS tooltips (several existing questions, possibly duplicates of this one).

How to solve a pair of nonlinear equations using Python?

for numerical solution, you can use fsolve:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve

from scipy.optimize import fsolve
import math

def equations(p):
    x, y = p
    return (x+y**2-4, math.exp(x) + x*y - 3)

x, y =  fsolve(equations, (1, 1))

print equations((x, y))

In a URL, should spaces be encoded using %20 or +?

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

Setting mime type for excel document

I was setting MIME type from .NET code as below -

File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

My application generates excel using OpenXML SDK. This MIME type worked -

vnd.openxmlformats-officedocument.spreadsheetml.sheet

How to overlay density plots in R?

use lines for the second one:

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

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

c# razor url parameter from view

@(ViewContext.RouteData.Values["parameterName"])

worked with ROUTE PARAM.

Request.Params["paramName"]

did not work with ROUTE PARAM.

How to read a CSV file into a .NET Datatable

I've recently written a CSV parser for .NET that I'm claiming is currently the fastest available as a nuget package: Sylvan.Data.Csv.

Using this library to load a DataTable is extremely easy.

using var dr = CsvDataReader.Create("data.csv");
var dt = new DataTable();
dt.Load(dr);

Assuming your file is a standard comma separated files with headers, that's all you need. There are also options to allow reading files without headers, and using alternate delimiters etc.

It is also possible to provide a custom schema for the CSV file so that columns can be treated as something other than string values. This will allow the DataTable columns to be loaded with values that can be easier to work with, as you won't have to coerce them when you access them.

This can be accomplished by providing an ICsvSchemaProvider implementation, which exposes a single method DbColumn? GetColumn(string? name, int ordinal). The DbColumn type is an abstract type defined in System.Data.Common, which means that you would have to provide an implementation of that too if you implement your own schema provider. The DbColumn type exposes a variety of metadata about a column, and you can choose to expose as much of the metadata as needed. The most important metadata is the DataType and AllowDBNull.

A very simple implementation that would expose type information could look like the following:

class TypedCsvColumn : DbColumn
{
    public TypedCsvColumn(Type type, bool allowNull)
    {
        // if you assign ColumnName here, it will override whatever is in the csv header
        this.DataType = type;
        this.AllowDBNull = allowNull;
    }
}
    
class TypedCsvSchema : ICsvSchemaProvider
{
    List<TypedCsvColumn> columns;

    public TypedCsvSchema()
    {
        this.columns = new List<TypedCsvColumn>();
    }

    public TypedCsvSchema Add(Type type, bool allowNull = false)
    {
        this.columns.Add(new TypedCsvColumn(type, allowNull));
        return this;
    }

    DbColumn? ICsvSchemaProvider.GetColumn(string? name, int ordinal)
    {
        return ordinal < columns.Count ? columns[ordinal] : null;
    }
}

To consume this implementation you would do the following:


var schema = new TypedCsvSchema()
    .Add(typeof(int))
    .Add(typeof(string))
    .Add(typeof(double), true)
    .Add(typeof(DateTime))
    .Add(typeof(DateTime), true);
var options = new CsvDataReaderOptions
{
    Schema = schema
};


using var dr = CsvDataReader.Create("data.csv", options);
...

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

How to select a dropdown value in Selenium WebDriver using Java

I have not tried in Selenium, but for Galen test this is working,

var list = driver.findElementByID("periodID"); // this will return web element

list.click(); // this will open the dropdown list.

list.typeText("14w"); // this will select option "14w".

You can try this in selenium, the galen and selenium working are similar.

How do I git rm a file without deleting it from disk?

git rm --cached file

should do what you want.

You can read more details at git help rm

How to convert a file into a dictionary?

IMHO a bit more pythonic to use generators (probably you need 2.7+ for this):

with open('infile.txt') as fd:
    pairs = (line.split(None) for line in fd)
    res   = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()}

This will also filter out lines not starting with an integer or not containing exactly two items

Append a dictionary to a dictionary

The answer I want to give is "use collections.ChainMap", but I just discovered that it was only added in Python 3.3: https://docs.python.org/3.3/library/collections.html#chainmap-objects

You can try to crib the class from the 3.3 source though: http://hg.python.org/cpython/file/3.3/Lib/collections/init.py#l763

Here is a less feature-full Python 2.x compatible version (same author): http://code.activestate.com/recipes/305268-chained-map-lookups/

Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).

SQL Server Regular expressions in T-SQL

If you are using SQL Server 2016 or above, you can use sp_execute_external_script along with R. It has functions for Regular Expression searches, such as grep and grepl.

Here's an example for email addresses. I'll query some "people" via the SQL Server database engine, pass the data for those people to R, let R decide which people have invalid email addresses, and have R pass back that subset of people to SQL Server. The "people" are from the [Application].[People] table in the [WideWorldImporters] sample database. They get passed to the R engine as a dataframe named InputDataSet. R uses the grepl function with the "not" operator (exclamation point!) to find which people have email addresses that don't match the RegEx string search pattern.

EXEC sp_execute_external_script 
 @language = N'R',
 @script = N' RegexWithR <- InputDataSet;
OutputDataSet <- RegexWithR[!grepl("([_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4}))", RegexWithR$EmailAddress), ];',
 @input_data_1 = N'SELECT PersonID, FullName, EmailAddress FROM Application.People'
 WITH RESULT SETS (([PersonID] INT, [FullName] NVARCHAR(50), [EmailAddress] NVARCHAR(256)))

Note that the appropriate features must be installed on the SQL Server host. For SQL Server 2016, it is called "SQL Server R Services". For SQL Server 2017, it was renamed to "SQL Server Machine Learning Services".

Closing Thoughts Microsoft's implementation of SQL (T-SQL) doesn't have native support for RegEx. This proposed solution may not be any more desirable to the OP than the use of a CLR stored procedure. But it does offer an additional way to approach the problem.

LINQ: "contains" and a Lambda query

var depthead = (from s in db.M_Users
                  join m in db.M_User_Types on s.F_User_Type equals m.UserType_Id
                  where m.UserType_Name.ToUpper().Trim().Contains("DEPARTMENT HEAD")
                  select new {s.FullName,s.F_User_Type,s.userId,s.UserCode } 
               ).OrderBy(d => d.userId).ToList();

Model.AvailableDeptHead.Add(new SelectListItem { Text = "Select", Value = "0" });
for (int i = 0; i < depthead.Count; i++)
    Model.AvailableDeptHead.Add(new SelectListItem { Text = depthead[i].UserCode + " - " + depthead[i].FullName, Value = Convert.ToString(depthead[i].userId) });

How Do I Uninstall Yarn

For Windows User:

Just use the installer file(i.e yarn-1.22.4.msi in my case) to uninstall yarn.

Once you open the installer you will get three options, i.e to install, repair and uninstall yarn from your machine. Select uninstall and it will remove all the yarn files from your pc.

android.widget.Switch - on/off event listener?

Switch inherits CompoundButton's attributes, so I would recommend the OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do something, the isChecked will be
        // true if the switch is in the On position
    }
});

HTML input file selection event not firing upon selecting the same file

<form enctype='multipart/form-data'>
    <input onchange="alert(this.value); this.value=null; return false;" type='file'>
    <br>
    <input type='submit' value='Upload'>
</form>

this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;

Here is a FIDDLE

How do I create a new line in Javascript?

\n dosen't work. Use html tags

document.write("<br>");
document.write("?");

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

Getting hold of the outer class object from the inner class object

/**
 * Not applicable to Static Inner Class (nested class)
 */
public static Object getDeclaringTopLevelClassObject(Object object) {
    if (object == null) {
        return null;
    }
    Class cls = object.getClass();
    if (cls == null) {
        return object;
    }
    Class outerCls = cls.getEnclosingClass();
    if (outerCls == null) {
        // this is top-level class
        return object;
    }
    // get outer class object
    Object outerObj = null;
    try {
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field != null && field.getType() == outerCls
                    && field.getName() != null && field.getName().startsWith("this$")) {
                field.setAccessible(true);
                outerObj = field.get(object);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return getDeclaringTopLevelClassObject(outerObj);
}

Of course, the name of the implicit reference is unreliable, so you shouldn't use reflection for the job.

Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

If you only need to remove the first character you would do:

s = ":dfa:sif:e"
fixed = s[1:]

If you want to remove a character at a particular position, you would do:

s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]

If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

How to change ProgressBar's progress indicator color in Android

simply add android:indeterminateTint="@color/colorPrimary" to your progressBar

Example:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminateTint="@color/colorPrimary"/>

in case of progressBarStyleHorizontal change android:progressTint="@color/colorPrimary"

Example:

 <ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:progress="50"
    android:progressTint="@color/colorPrimary" />

make iframe height dynamic based on content inside- JQUERY/Javascript

I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

So in the parent document, add an event listener:

window.addEventListener('message', function(e) {
  var $iframe = jQuery("#myIframe");
  var eventName = e.data[0];
  var data = e.data[1];
  switch(eventName) {
    case 'setHeight':
      $iframe.height(data);
      break;
  }
}, false);

And inside the iframe, write a function to post the message:

function resize() {
  var height = document.getElementsByTagName("html")[0].scrollHeight;
  window.parent.postMessage(["setHeight", height], "*"); 
}

Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

<body onLoad="resize();">

Contains case insensitive

To do a better search use the following code,

var myFav   = "javascript";
var theList = "VB.NET, C#, PHP, Python, JavaScript, and Ruby";

// Check for matches with the plain vanilla indexOf() method:
alert( theList.indexOf( myFav ) );

// Now check for matches in lower-cased strings:
alert( theList.toLowerCase().indexOf( myFav.toLowerCase() ) );

In the first alert(), JavaScript returned "-1" - in other words, indexOf() did not find a match: this is simply because "JavaScript" is in lowercase in the first string, and properly capitalized in the second. To perform case-insensitive searches with indexOf(), you can make both strings either uppercase or lowercase. This means that, as in the second alert(), JavaScript will only check for the occurrence of the string you are looking for, capitalization ignored.

Reference, http://freewebdesigntutorials.com/javaScriptTutorials/jsStringObject/indexOfMethod.htm

AngularJS: factory $http.get JSON file

I wanted to note that the fourth part of Accepted Answer is wrong .

theApp.factory('mainInfo', function($http) { 

var obj = {content:null};

$http.get('content.json').success(function(data) {
    // you can do some processing here
    obj.content = data;
});    

return obj;    
});

The above code as @Karl Zilles wrote will fail because obj will always be returned before it receives data (thus the value will always be null) and this is because we are making an Asynchronous call.

The details of similar questions are discussed in this post


In Angular, use $promise to deal with the fetched data when you want to make an asynchronous call.

The simplest version is

theApp.factory('mainInfo', function($http) { 
    return {
        get:  function(){
            $http.get('content.json'); // this will return a promise to controller
        }
});


// and in controller

mainInfo.get().then(function(response) { 
    $scope.foo = response.data.contentItem;
});

The reason I don't use success and error is I just found out from the doc, these two methods are deprecated.

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

Min and max value of input in angular4 application

Here is the solution :

This is kind of hack , but it will work

<input type="number" 
placeholder="Charge" 
[(ngModel)]="rateInput" 
name="rateInput"
pattern="^$|^([0-9]|[1-9][0-9]|[1][0][0])?"
required 
#rateInput2 = "ngModel">

<div *ngIf="rateInput2.errors && (rateInput2.dirty || rateInput2.touched)"
    <div [hidden]="!rateInput2.errors.pattern">
        Number should be between 0 and 100
    </div>
</div>

Here is the link to the plunker , please have a look.

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

I'd just use zip:

In [1]: from pandas import *

In [2]: def calculate(x):
   ...:     return x*2, x*3
   ...: 

In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})

In [4]: df
Out[4]: 
   a  b
0  1  2
1  2  3
2  3  4

In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))

In [6]: df
Out[6]: 
   a  b  A1  A2
0  1  2   2   3
1  2  3   4   6
2  3  4   6   9

How do I check if a given string is a legal/valid file name under Windows?

This is what I use:

    public static bool IsValidFileName(this string expression, bool platformIndependent)
    {
        string sPattern = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$";
        if (platformIndependent)
        {
           sPattern = @"^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?))\\)*[^\\/:\*\?""\|<>\. ](([^\\/:\*\?""\|<>\. ])|([^\\/:\*\?""\|<>]*[^\\/:\*\?""\|<>\. ]))?$";
        }
        return (Regex.IsMatch(expression, sPattern, RegexOptions.CultureInvariant));
    }

The first pattern creates a regular expression containing the invalid/illegal file names and characters for Windows platforms only. The second one does the same but ensures that the name is legal for any platform.

Git fatal: protocol 'https' is not supported

You might be using a windows or linux computer where you have not logged into git hub so the certificate is not verified. From the sytem where you are getting error login to github with the credential then try to use the command it will work . Good Luck

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

Git add all files modified, deleted, and untracked?

Try:

git add -A

Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:

git add -A .

Also see: Difference of git add -A and git add .

event.preventDefault() vs. return false

From my experience event.stopPropagation() is mostly used in CSS effect or animation works, for instance when you have hover effect for both card and button element, when you hover on the button both card and buttons hover effect will be triggered in this case, you can use event.stopPropagation() stop bubbling actions, and event.preventDefault() is for prevent default behaviour of browser actions. For instance, you have form but you only defined click event for the submit action, if the user submits the form by pressing enter, the browser triggered by keypress event, not your click event here you should use event.preventDefault() to avoid inappropriate behavior. I don't know what the hell is return false; sorry.For more clarification visit this link and play around with line #33 https://www.codecademy.com/courses/introduction-to-javascript/lessons/requests-i/exercises/xhr-get-request-iv

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

Is it safe to store a JWT in localStorage with ReactJS?

A way to look at this is to consider the level of risk or harm.

Are you building an app with no users, POC/MVP? Are you a startup who needs to get to market and test your app quickly? If yes, I would probably just implement the simplest solution and maintain focus on finding product-market-fit. Use localStorage as its often easier to implement.

Are you building a v2 of an app with many daily active users or an app that people/businesses are heavily dependent on. Would getting hacked mean little or no room for recovery? If so, I would take a long hard look at your dependencies and consider storing token information in an http-only cookie.

Using both localStorage and cookie/session storage have their own pros and cons.

As stated by first answer: If your application has an XSS vulnerability, neither will protect your user. Since most modern applications have a dozen or more different dependencies, it becomes increasingly difficult to guarantee that one of your application's dependencies is not XSS vulnerable.

If your application does have an XSS vulnerability and a hacker has been able to exploit it, the hacker will be able to perform actions on behalf of your user. The hacker can perform GET/POST requests by retrieving token from localStorage or can perform POST requests if token is stored in a http-only cookie.

The only down-side of the storing your token in local storage is the hacker will be able to read your token.

How to get C# Enum description from value?

Update

The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

In Enums.NET you'd use:

string description = ((MyEnum)value).AsString(EnumFormat.Description);

Original post

I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description

I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

How to test if a DataSet is empty?

We can check total three ways.

  1. if(ds != null)
  2. if(ds.Tables.Count > 0 )
  3. if(ds.Tables[0].Rows.Count > 0)

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.

GL!

jquery UI dialog: how to initialize without a title bar?

I figured out a fix for dynamically removing the title bar.

$("#example").dialog(dialogOpts);
// remove the title bar
$(".ui-dialog-titlebar").hide();

This will remove all elements with the class 'ui-dialog-titlebar' after the dialog box is rendered.

How to allow access outside localhost

run command

ng serve --host=0.0.0.0 --disable-host-check

this will disable host check and allow to access from outside(instead of localhost) with IP address

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

In Linux I resolve this problem by going to the root command prompt type:

# mysqladmin -u root password 'Secret Phrase Here'

Then go back and login. Works every time!

slashes in url variables

You need to escape those but don't just replace it by %2F manually. You can use URLEncoder for this.

Eg URLEncoder.encode(url, "UTF-8")

Then you can say

yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")

JSON datetime between Python and JavaScript

For the Python to JavaScript date conversion, the date object needs to be in specific ISO format, i.e. ISO format or UNIX number. If the ISO format lacks some info, then you can convert to the Unix number with Date.parse first. Moreover, Date.parse works with React as well while new Date might trigger an exception.

In case you have a DateTime object without milliseconds, the following needs to be considered. :

  var unixDate = Date.parse('2016-01-08T19:00:00') 
  var desiredDate = new Date(unixDate).toLocaleDateString();

The example date could equally be a variable in the result.data object after an API call.

For options to display the date in the desired format (e.g. to display long weekdays) check out the MDN doc.

Undefined reference to pthread_create in Linux

For Linux the correct command is:

gcc -o term term.c -lpthread
  1. you have to put -lpthread just after the compile command,this command will tell to the compiler to execute program with pthread.h library.
  2. gcc -l links with a library file.Link -l with library name without the lib prefix.

How to split a string to 2 strings in C

You can do:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

Fatal error: Class 'SoapClient' not found

Diagnose

Look up the following inside your script file

phpinfo();

If you can't find Soap Client set to enabled like so: the way soap should appear in phpinfo()

Fix

Do the following:

  1. Locate php.ini in your apache bin folder, I.e Apache/bin/php.ini
  2. Remove the ; from the beginning of extension=php_soap.dll
  3. Restart your Apache server
  4. Look up your phpinfo(); again and check if you see a similar picture to the one above
  5. If you do, problem solved!

On the other hand if this doesn't solve your issue, you may want to check the requirements for SOAP here. Also in the comment section you can find good advice on connecting to https.

How to configure custom PYTHONPATH with VM and PyCharm?

An update to the correct answer phil provided, for more recent versions of Pycharm (e.g. 2019.2).

Go to File > Settings and find your project, then select Project Interpreter. Now click the button with a cog to the right of the selected project interpreter (used to be a ...).

enter image description here

From the drop-down menu select Show All... and in the dialog that opens click the icon with a folder and two sub-folders.

enter image description here

You are presented with a dialog with the current interpreter paths, click on + to add one more.

How to change sa password in SQL Server 2008 express?

I didn't know the existing sa password so this is what I did:

  1. Open Services in Control Panel

  2. Find the "SQL Server (SQLEXPRESS)" entry and select properties

  3. Stop the service

  4. Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;

  5. Start the service

  6. Open a Command Prompt

Enter the command:

osql -S YourPcName\SQLEXPRESS -E

(change YourPcName to whatever your PC is called).

  1. At the prompt type the following commands:
alter login sa enable
go
sp_password NULL,'new_password','sa'
go
quit
  1. Stop the "SQL Server (SQLEXPRESS)" service

  2. Remove the "-m" from the Start parameters field

  3. Start the service

DECODE( ) function in SQL Server

It's easy to do:

select 
    CASE WHEN 10 > 1 THEN 'Yes'
    ELSE 'No'
END 

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to get the CUDA version?

On Ubuntu Cuda V8:

$ cat /usr/local/cuda/version.txt

What does the "$" sign mean in jQuery or JavaScript?

Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:

"test".match( /t(e)st/ );
alert( RegExp.$1 );

will alert "e"

But also here it's not "magic" but simply part of the properties name

What is the maximum number of characters that nvarchar(MAX) will hold?

Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX) field.

Using the other answer's more detailed numbers, you should be able to store

(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters

1 billion, 73 million, 741 thousand and 822 characters to be precise

in your NVARCHAR(MAX) column (unfortunately, that last half character is wasted...)

Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1 length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

this is a version problem change version > 2.4 to 1.9 solve it

<dependency>  
<groupId>com.fasterxml.jackson.jaxrs</groupId>  
<artifactId>jackson-jaxrs-xml-provider</artifactId>  
<version>2.4.1</version>  

to

<dependency>  
<groupId>org.codehaus.jackson</groupId>  
<artifactId>jackson-mapper-asl</artifactId>  
<version>1.9.4</version>  

swift 3.0 Data to String?

This is much easier in Swift 3 and later using reduce:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.reduce("") { $0 + String(format: "%02x", $1) }

    DispatchQueue.global(qos: .background).async { 
        let url = URL(string: "https://example.com/myApp/apns.php")!

        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        request.httpBody = try! JSONSerialization.data(withJSONObject: [
            "token" : token, 
            "ios" : UIDevice.current.systemVersion,
            "languages" : Locale.preferredLanguages.joined(separator: ", ")
            ])

        URLSession.shared.dataTask(with: request).resume()
    }
}

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I was getting this when the app deployed. In my case, I chose "This is a full trust application" on the project security tab, and that fixed it.

Google Play on Android 4.0 emulator

  1. Download the gapps package from http://goo.im/gapps
  2. extract GoogleLoginService.apk,GoogleServicesFramework.apk and Vending.apk Go to cmd window type adb shell
    1. on the shell type mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
    2. then press Ctrl+c to exit. cd to the directory where apks has been extracted,
    3. type adb push <appname>.apk /system/app
    4. then type adb reboot

SQL Server: Database stuck in "Restoring" state

RESTORE DATABASE {DatabaseName}
   FROM DISK = '{databasename}.bak'
   WITH REPLACE, RECOVERY

How to Set Active Tab in jQuery Ui

If you want to set the active tab by ID instead of index, you can also use the following:

$('#tabs').tabs({ active: $('#tabs ul').index($('#tab-101')) });

Initializing an Array of Structs in C#

Change const to static readonly and initialise it like this

static readonly MyStruct[] MyArray = new[] {
    new MyStruct { label = "a", id = 1 },
    new MyStruct { label = "b", id = 5 },
    new MyStruct { label = "q", id = 29 }
};

How does facebook, gmail send the real time notification?

The way Facebook does this is pretty interesting.

A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.

Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.

In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.

  • Don't forget to change your PHP max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll(); 
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json'); 
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global AJAX timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

Testing if value is a function

using a string based variable as example and making use instanceof Function You register the function..assign the variable...check the variable is the name of function...do pre-process... assign the function to new var...then call the function.

function callMe(){
   alert('You rang?');
}

var value = 'callMe';

if (window[value] instanceof Function) { 
    // do pre-process stuff
    // FYI the function has not actually been called yet
    console.log('callable function');
    //now call function
   var fn = window[value];
   fn();
}

long long in C/C++

your code compiles here fine (even with that line uncommented. had to change it to

num3 = 100000000000000000000;

to start getting the warning.

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

How to reload a page using JavaScript

Use this button to refresh the page

DEMO

<input type="button" value="Reload Page" onClick="document.location.reload(true)">

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

As in the docs, if you are on windows you can use hyperv drivers.

Docker for Windows - You can use docker-machine create with the hyperv driver to create additional local machines.

How do I get and set Environment variables in C#?

I ran into this while working on a .NET console app to read the PATH environment variable, and found that using System.Environment.GetEnvironmentVariable will expand the environment variables automatically.

I didn't want that to happen...that means folders in the path such as '%SystemRoot%\system32' were being re-written as 'C:\Windows\system32'. To get the un-expanded path, I had to use this:

string keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);

Worked like a charm for me.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Since you're dealing with values that are just supposed to be boolean anyway, just use == and convert the logical response to as.integer:

df <- data.frame(col = c("true", "true", "false"))
df
#     col
# 1  true
# 2  true
# 3 false
df$col <- as.integer(df$col == "true")
df
#   col
# 1   1
# 2   1
# 3   0

Prevent redirect after form is submitted

The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.

How to copy text to the client's clipboard using jQuery?

Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.

Here's how to do it for Internet Explorer:

function copy (str)
{
    //for IE ONLY!
    window.clipboardData.setData('Text',str);
}

Labeling file upload button

You get your browser's language for your button. There's no way to change it programmatically.

How do I delete all messages from a single queue using the CLI?

you can directly run this command

sudo rabbitmqctl purge_queue queue_name

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Optional.map. Your code would then look like:

object.map(o -> "result" /* or your function */)
      .orElseThrow(MyCustomException::new);

I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant:

public String getString(Object yourObject) {
  if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
     throw new MyCustomException();
  }
  String result = ...
  // your string mapping function
  return result;
}

If you already have the Optional-object due to another call, I would still recommend you to use the map-method, instead of isPresent, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

TextAppearance.Holo.Widget.ActionBar.Title appears to have been added in API Level 13. Make sure your build target is set to 13, not just 11.

How to get the bluetooth devices as a list?

Find list of Nearby Bluetooth Devices:

Find Screenshot for the same.

enter image description here

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    private ListView listView;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private BluetoothAdapter mBluetoothAdapter;

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

        listView = (ListView) findViewById(R.id.listView);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.startDiscovery();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.bluetoothdemo.MainActivity" >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"/>

</RelativeLayout>

Manifest file:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note:

Please make sure that you ask Location permission to your user and turn GPS On.

Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.

More reference:

  1. https://developer.android.com/guide/topics/connectivity/bluetooth
  2. https://getlief.zendesk.com/hc/en-us/articles/360007600233-Why-does-Android-require-Location-Permissions-for-Bluetooth-

Done

Fix footer to bottom of page

CSS

html {
    height:100%;
}
body {
    min-height:100%; position:relative;
}
.footer {
    background-color: rgb(200,200,200);
    height: 115px;
    position:absolute; bottom:0px;
}
.footer-ghost { height:115px; }

HTML

<div class="header">...</div>
<div class="content">...</div>
<div class="footer"></div>
<div class="footer-ghost"></div>

How to completely uninstall Visual Studio 2010?

Best way I have used is to mount the VS 2010 Image or insert the Installation disc and run the uninstall option, really works well

How can I get a side-by-side diff when I do "git diff"?

I personally really like icdiff !

If you're on Mac OS X with HomeBrew, just do brew install icdiff.

To get the file labels correctly, plus other cool features, I have in my ~/.gitconfig:

[pager]
    difftool = true
[diff]
    tool = icdiff
[difftool "icdiff"]
    cmd = icdiff --head=5000 --highlight --line-numbers -L \"$BASE\" -L \"$REMOTE\" \"$LOCAL\" \"$REMOTE\"

And I use it like: git difftool

How to get directory size in PHP

Thanks to Jonathan Sampson, Adam Pierce and Janith Chinthana I did this one checking for most performant way to get the directory size. Should work on Windows and Linux Hosts.

static function getTotalSize($dir)
{
    $dir = rtrim(str_replace('\\', '/', $dir), '/');

    if (is_dir($dir) === true) {
        $totalSize = 0;
        $os        = strtoupper(substr(PHP_OS, 0, 3));
        // If on a Unix Host (Linux, Mac OS)
        if ($os !== 'WIN') {
            $io = popen('/usr/bin/du -sb ' . $dir, 'r');
            if ($io !== false) {
                $totalSize = intval(fgets($io, 80));
                pclose($io);
                return $totalSize;
            }
        }
        // If on a Windows Host (WIN32, WINNT, Windows)
        if ($os === 'WIN' && extension_loaded('com_dotnet')) {
            $obj = new \COM('scripting.filesystemobject');
            if (is_object($obj)) {
                $ref       = $obj->getfolder($dir);
                $totalSize = $ref->size;
                $obj       = null;
                return $totalSize;
            }
        }
        // If System calls did't work, use slower PHP 5
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
        foreach ($files as $file) {
            $totalSize += $file->getSize();
        }
        return $totalSize;
    } else if (is_file($dir) === true) {
        return filesize($dir);
    }
}

How to select a column name with a space in MySQL

To each his own but the right way to code this is to rename the columns inserting underscore so there are no gaps. This will ensure zero errors when coding. When printing the column names for public display you could search-and-replace to replace the underscore with a space.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Swift

This is a self contained project so that you can see everything in context.

Layout

Create a layout like the following with a UIView and a UIButton. The UIView will be the container in which we will play our video.

enter image description here

Add a video to the project

If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).

Code

Here is the complete code for the project.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVPlayer?

    @IBOutlet weak var videoViewContainer: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeVideoPlayerWithVideo()
    }
    
    func initializeVideoPlayerWithVideo() {
        
        // get the path string for the video from assets
        let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
        guard let unwrappedVideoPath = videoString else {return}

        // convert the path string to a url
        let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)

        // initialize the video player with the url
        self.player = AVPlayer(url: videoUrl)

        // create a video layer for the player
        let layer: AVPlayerLayer = AVPlayerLayer(player: player)
        
        // make the layer the same size as the container view
        layer.frame = videoViewContainer.bounds
        
        // make the video fill the layer as much as possible while keeping its aspect size
        layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        
        // add the layer to the container view
        videoViewContainer.layer.addSublayer(layer)
    }

    @IBAction func playVideoButtonTapped(_ sender: UIButton) {
        // play the video if the player is initialized
        player?.play()
    }
}

Notes

  • If you are going to be switching in and out different videos, you can use AVPlayerItem.
  • If you are only using AVFoundation and AVPlayer, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController. You will need to import AVKit for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.
  • MPMoviePlayerController that you may have seen in other answers is deprecated.

Result

The project should look like this now.

enter image description here

Didn't Java once have a Pair class?

There is no Pair in the standard framework, but the Apache Commons Lang, which comes quite close to “standard”, has a Pair.

Rails server says port already used, how to kill that process?

All the answers above are really good but I needed a way to type as little as possible in the terminal so I created a gem for that. You can install the gem only once and run the command 'shutup' every time you wanna kill the Rails process (while being in the current folder).

gem install shutup

then go in the current folder of your rails project and run

shutup # this will kill the Rails process currently running

You can use the command 'shutup' every time you want

DICLAIMER: I am the creator of this gem

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

Dynamically load JS inside JS

Here is a little lib to load javascript and CSS files dynamically:

https://github.com/todotresde/javascript-loader

I guess is usefull to load css and js files in order and dynamically.

Support to extend to load any lib you want, and not just the main file, you can use it to load custom files.

I.E.:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="scripts/javascript-loader.js" type="text/javascript" charset="utf-8" ></script>    
    <script type="text/javascript">
        $(function() {

            registerLib("threejs", test);

            function test(){
                console.log(THREE);
            }

            registerLib("tinymce", draw);

            function draw(){
                tinymce.init({selector:'textarea'});
            }

        }); 
    </script>
</head>
<body>
    <textarea>Your content here.</textarea>
</body>

How to change the ROOT application?

the context.xml configuration didn't work for me. Tomcat 6.0.29 complains about the docBase being inside the appBase: ... For Tomcat 5 this did actually work.

So one solution is to put the application in the ROOT folder.

Another very simple solution is to put an index.jsp to ROOT that redirects to my application like this: response.sendRedirect("/MyApplicationXy");

Best Regards, Jan

How to limit the maximum files chosen when using multiple file input

if you want php you can count the array and just make an if statement like

if((int)count($_FILES['i_dont_know_whats_coming_next'] > 2)
      echo "error message";

How to create JSON string in JavaScript?

Use JSON.stringify:

> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

How to detect Safari, Chrome, IE, Firefox and Opera browser?

You can use Detect-browser.js, JavaScript library that detects and prints an object of browser information including browser language/name, user agent, device type, user OS, referer, online/0ffline, user timezone, screen resolution, and cookie enabled.

Get it from here detect-browser.js

it will give you something like that:

enter image description here

Take a list of numbers and return the average

If you have the numpy package:

In [16]: x = [1,2,3,4]    
    ...: import numpy
    ...: numpy.average(x)

Out[16]: 2.5

How to send custom headers with requests in Swagger UI?

Here's a simpler answer for the ASP.NET Core Web Api/Swashbuckle combo, that doesn't require you to register any custom filters. Third time's a charm you know :).

Adding the code below to your Swagger config will cause the Authorize button to appear, allowing you to enter a bearer token to be sent for all requests. Don't forget to enter this token as Bearer <your token here> when asked.

Note that the code below will send the token for any and all requests and operations, which may or may not be what you want.


    services.AddSwaggerGen(c =>
    {
        //...

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = "header",
            Type = "apiKey"
        });

        c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] { } }
        });

        //...
    }

Via this thread.

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

Export Postgresql table data using pgAdmin

In the pgAdmin4, Right click on table select backup like this

enter image description here

After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.

enter image description here

How to get number of video views with YouTube API?

I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:

<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>

Ref: Youtube API - Retrieving information about a single video

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.

JavaScript load a page on button click

Don't abuse form elements where <a> elements will suffice.

<style>
    /* or put this in your stylesheet */

    .button {
        display: inline-block;
        padding: 3px 5px;
        border: 1px solid #000;
        background: #eee;
    }

</style>

<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>

Explaining Python's '__enter__' and '__exit__'

If you know what context managers are then you need nothing more to understand __enter__ and __exit__ magic methods. Lets see a very simple example.

In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.

fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
    for line in fp:
        print(line)
finally:
    fp.close()

Now I am opening same file with with statement:

with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
    for line in fp:
        print(line) 

If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed) attribute -- which returns True.

This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__ and __exit__. It is also known as context manager. __enter__ method is called at the start of with block and __exit__ method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__ and __exit__ methods. A class which implement both methods is known as context manager class.

Now lets define our own context manager class.

 class Log:
    def __init__(self,filename):
        self.filename=filename
        self.fp=None    
    def logging(self,text):
        self.fp.write(text+'\n')
    def __enter__(self):
        print("__enter__")
        self.fp=open(self.filename,"a+")
        return self    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.fp.close()

with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
    print("Main")
    logfile.logging("Test1")
    logfile.logging("Test2")

I hope now you have basic understanding of both __enter__ and __exit__ magic methods.

How to place Text and an Image next to each other in HTML?

img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example

Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

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

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

Console output in a Qt GUI app?

Oh you can Output a message when using QT += gui and CONFIG += console.

You need printf("foo bar") but cout << "foo bar" doesn't works

Create an Excel file using vbscripts

This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")

set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "\temp.xls")

ReadFile in Base64 Nodejs

I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

request exceeds the configured maxQueryStringLength when using [Authorize]

When an unauthorized request comes in, the entire request is URL encoded, and added as a query string to the request to the authorization form, so I can see where this may result in a problem given your situation.

According to MSDN, the correct element to modify to reset maxQueryStringLength in web.config is the <httpRuntime> element inside the <system.web> element, see httpRuntime Element (ASP.NET Settings Schema). Try modifying that element.

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

pg_config executable not found

On MAC Mojave, if you have installed it using brew, then do brew info <your postgres>

It will show you all environment variables that you should set, simply copy-paste those commands, restart your shell and thats it!

Get the latest date from grouped MySQL data

Are you looking for the max date for each model?

SELECT model, max(date) FROM doc
GROUP BY model

If you're looking for all models matching the max date of the entire table...

SELECT model, date FROM doc
WHERE date IN (SELECT max(date) FROM doc)

[--- Added ---]

For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):

SELECT d.model, d.date, d.color, d.etc FROM doc d
WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)

MySQL 8.0 and newer supports the OVER clause, producing the same results a bit faster for larger data sets.

SELECT model, date, color, etc FROM (SELECT model, date, color, etc, 
  max(date) OVER (PARTITION BY model) max_date FROM doc) predoc 
WHERE date=max_date;

Case insensitive 'in'

You could do

matcher = re.compile('MICHAEL89', re.IGNORECASE)
filter(matcher.match, USERNAMES) 

Update: played around a bit and am thinking you could get a better short-circuit type approach using

matcher = re.compile('MICHAEL89', re.IGNORECASE)
if any( ifilter( matcher.match, USERNAMES ) ):
    #your code here

The ifilter function is from itertools, one of my favorite modules within Python. It's faster than a generator but only creates the next item of the list when called upon.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

I've recently found a lib called ion that brings a little extra to the table.

ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.

I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.