Programs & Examples On #Dbix class

DBIx::Class is a Perl object-relational mapping (ORM) module. It aims to make representing queries in your code as perl-ish as possible while still providing access to as many of the capabilities of the database as possible, including retrieving related records from multiple tables in a single query, JOIN, LEFT JOIN, COUNT, DISTINCT, GROUP BY, ORDER BY and HAVING support.

PHP upload image

<?php
include("config.php");

if(isset($_POST['but_upload'])){
 
  $name = $_FILES['file']['name'];
  $target_dir = "upload/";
  $target_file = $target_dir . basename($_FILES["file"]["name"]);

  // Select file type
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // Valid file extensions
  $extensions_arr = array("jpg","jpeg","png","gif");

  // Check extension
  if( in_array($imageFileType,$extensions_arr) ){
 
     // Insert record
     $query = "insert into images(name) values('".$name."')";
     mysqli_query($con,$query);
  
     // Upload file
     move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);

  }
 
}
?>
<form method="post" action="" enctype='multipart/form-data'>
  <input type='file' name='file' />
  <input type='submit' value='Save name' name='but_upload'>
</form>

Select the name or path of the image which you have stored in the database table and use it in the image source. Read More

 <?php
    $sql = "select name from images where id=1";
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_array($result)){
          $image = $row['name'];
          $image_src = "upload/".$image; 
          <img src='<?php echo $image_src;  ?>' > echo '<br>';
    }
    ?>

source code: https://www.phpcodingstuff.com/blog/how-to-insert-image-in-php.html

Align HTML input fields by :

I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.

JSFiddle

HTML

<table>

    <tr><td>Name:</td><td><input type="text"/></td></tr>

    <tr><td>Age:</td><td><input type="text"/></td></tr>

</table>

<!--You can add the fields as you want-->

CSS

td{
    text-align:right;
}

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

How to validate an email address in JavaScript

It's hard to get an email validator 100% correct. The only real way to get it correct would be to send a test email to the account. That said, there are a few basic checks that can help make sure that you're getting something reasonable.

Some things to improve:

Instead of new RegExp, just try writing the regexp out like this:

if (reg.test(/@/))

Second, check to make sure that a period comes after the @ sign, and make sure that there are characters between the @s and periods.

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

Rails: How to reference images in CSS within Rails 4

When using gem 'sass-rails', in Rails 5, bootstrap 4, the following worked for me,

in .scss file:

    background-image: url(asset_path("black_left_arrow.svg"));

in view file(e.g. .html.slim):

    style=("background-image: url(#{ show_image_path("event_background.png") })");

How can I access Google Sheet spreadsheets only with Javascript?

You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:

https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html

Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).

Some example code (this example makes an RGraph chart):

<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>

<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>

<script>
    // Create a new RGraph Sheets object using the spreadsheet's key and
    // the callback function that creates the chart. The RGraph.Sheets object is
    // passed to the callback function as an argument so it doesn't need to be
    // assigned to a variable when it's created
    new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
    {
        // Get the labels from the spreadsheet by retrieving part of the first row
        var labels = sheet.get('A2:A7');

        // Use the column headers (ie the names) as the key
        var key = sheet.get('B1:E1');

        // Get the data from the sheet as the data for the chart
        var data   = [
            sheet.get('B2:E2'), // January
            sheet.get('B3:E3'), // February
            sheet.get('B4:E4'), // March
            sheet.get('B5:E5'), // April
            sheet.get('B6:E6'), // May
            sheet.get('B7:E7')  // June
        ];

        // Create and configure the chart; using the information retrieved above
        // from the spreadsheet
        var bar = new RGraph.Bar({
            id: 'cvs',
            data: data,
            options: {
                backgroundGridVlines: false,
                backgroundGridBorder: false,
                xaxisLabels: labels,
                xaxisLabelsOffsety: 5,
                colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
                shadow: false,
                colorsStroke: 'rgba(0,0,0,0)',
                yaxis: false,
                marginLeft: 40,
                marginBottom: 35,
                marginRight: 40,
                key: key,
                keyBoxed: false,
                keyPosition: 'margin',
                keyTextSize: 12,
                textSize: 12,
                textAccessible: false,
                axesColor: '#aaa'
            }
        }).wave();
    });
</script>

How to fix error with xml2-config not found when installing PHP from sources?

Ubuntu, Debian:

sudo apt install libxml2-dev

Centos:

sudo yum install libxml2-devel

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

How to find out when an Oracle table was updated the last time

How long does the batch process take to write the file? It may be easiest to let it go ahead and then compare the file against a copy of the file from the previous run to see if they are identical.

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

Export query result to .csv file in SQL Server 2008

Building on N.S's answer, I have a PowerShell script that exports to a CSV file with the quote marks around the field and comma separated and it skips the header information in the file.

add-pssnapin sqlserverprovidersnapin100
add-pssnapin sqlservercmdletsnapin100

$qry = @"
Select
  *
From
 tablename
"@

Invoke-Sqlcmd -ServerInstance Server -Database DBName -Query $qry | convertto-CSV -notype | select -skip 1  > "full path and filename.csv"

The first two lines enable the ability to use the Invoke-SqlCmd command-let.

Python concatenate text files

def concatFiles():
    path = 'input/'
    files = os.listdir(path)
    for idx, infile in enumerate(files):
        print ("File #" + str(idx) + "  " + infile)
    concat = ''.join([open(path + f).read() for f in files])
    with open("output_concatFile.txt", "w") as fo:
        fo.write(path + concat)

if __name__ == "__main__":
    concatFiles()

Find commit by hash SHA in Git

Just use the following command

git show a2c25061

or (the exact equivalent):

git log -p -1 a2c25061

What is a thread exit code?

what happened to me is that I have multiple projects in my solution. I meant to debug project 1, however, the project 2 was set as the default starting project. I fixed this by, right click on the project and select "Set as startup project", then running debugging is fine.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

PUT /testIndex
{
    "mappings": {
        "properties": {     <--ADD THIS
            "field1": {
                "type": "integer"
            },
            "field2": {  
                "type": "integer"
            },
            "field3": {
                "type": "string",
                "index": "not_analyzed"
            },
            "field4": {
                "type": "string",
                "analyzer": "autocomplete",
                "search_analyzer": "standard"
            }
        }
    },
    "settings": {
        bla
        bla
        bla
    }
}

Here's a similar command I know works:

curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex

The breakdown for the above curl command is:

PUT /manzanaIndex
{
    "mappings":{
        "properties":{
                "city":{
                    "type": "text"
                }
        }
    }
}

CSS - How to Style a Selected Radio Buttons Label?

As there is currently no CSS solution to style a parent, I use a simple jQuery one here to add a class to a label with checked input inside it.

$(document).on("change","input", function(){
 $("label").removeClass("checkedlabel");
 if($(this).is(":checked")) $(this).closest("label").addClass("checkedlabel");
});

Don't forget to give the pre-checked input's label the class checkedlabel too

How to read embedded resource text file

When you added the file to the resources, you should select its Access Modifiers as public than you can make something like following.

byte[] clistAsByteArray = Properties.Resources.CLIST01;

CLIST01 is the name of the embedded file.

Actually you can go to the resources.Designer.cs and see what is the name of the getter.

How to re-index all subarray elements of a multidimensional array?

Here you can see the difference between the way that deceze offered comparing to the simple array_values approach:

The Array:

$array['a'][0] = array('x' => 1, 'y' => 2, 'z' => 3);
$array['a'][5] = array('x' => 4, 'y' => 5, 'z' => 6);

$array['b'][1] = array('x' => 7, 'y' => 8, 'z' => 9);
$array['b'][7] = array('x' => 10, 'y' => 11, 'z' => 12);

In deceze way, here is your output:

$array = array_map('array_values', $array);
print_r($array);

/* Output */

Array
(
    [a] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [1] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [b] => Array
        (
            [0] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )

            [1] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

And here is your output if you only use array_values function:

$array = array_values($array);
print_r($array);

/* Output */

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [x] => 1
                    [y] => 2
                    [z] => 3
                )
            [5] => Array
                (
                    [x] => 4
                    [y] => 5
                    [z] => 6
                )
        )
    [1] => Array
        (
            [1] => Array
                (
                    [x] => 7
                    [y] => 8
                    [z] => 9
                )
            [7] => Array
                (
                    [x] => 10
                    [y] => 11
                    [z] => 12
                )
        )
)

How to determine whether a year is a leap year?

The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:

A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0

I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:

leap = A and (not B or C)

This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.

ASP.NET Web API application gives 404 when deployed at IIS 7

For me, this issue was slightly different than other answers, as I was only receiving 404s on OPTIONS, yet I already had OPTIONS specifically stated in my Integrated Extensionless URL Handler options. Very confusing.

  1. As others have stated, runAllManagedModulesForAllRequests="true" in the modules node is an easy way to blanket-fix most Web API 404 issues - although I prefer @DavidAndroidDev 's answer which is much less intrusive. But there was something additional in my case.
  2. Unfortunately, I had this set in IIS under Request Filtering in the site:

OPTIONS Issue with Request Filtering

By adding the following security node to the web.config was necessary to knock that out - full system.webserver included for context:

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <remove name="WebDAV" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <security>
      <requestFiltering>
        <verbs>
          <remove verb="OPTIONS" />
        </verbs>
      </requestFiltering>
    </security>
  </system.webServer>

Although it's not the perfect answer for this question, it is the first result for "IIS OPTIONS 404" on Google, so I hope this helps someone out; cost me an hour today.

UICollectionView cell selection and cell reuse

In your custom cell create public method:

- (void)showSelection:(BOOL)selection
{
    self.contentView.backgroundColor = selection ? [UIColor blueColor] : [UIColor white];
}

Also write redefenition of -prepareForReuse cell method:

- (void)prepareForReuse
{
    [self showSelection:NO];
    [super prepareForReuse];
}

And in your ViewController you should have _selectedIndexPath variable, which defined in -didSelectItemAtIndexPath and nullified in -didDeselectItemAtIndexPath

NSIndexPath *_selectedIndexPath;

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    if (_selectedIndexPath) {
        [cell showSelection:[indexPath isEqual:_selectedIndexPath]];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell showSelection:![indexPath isEqual:_selectedIndexPath]];// on/off selection
    _selectedIndexPath = [indexPath isEqual:_selectedIndexPath] ? nil : indexPath;
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell showSelection:NO];
    _selectedIndexPath = nil;
}

In Python, how do I convert all of the items in a list to floats?

[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

How to enable assembly bind failure logging (Fusion) in .NET

Just in case you're wondering about the location of FusionLog.exe - You know you have it, but you cannot find it? I was looking for FUSLOVW in last few years over and over again. After move to .NET 4.5 number of version of FUSION LOG has exploded. Her are places where it can be found on your disk, depending on software which you have installed:

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\x64

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass annotation (optimize later).

Example of optimization using the @BeforeClass setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.

Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.

Defining lists as global variables in Python

No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

How can I set the form action through JavaScript?

Setting form action after selection of option using JavaScript

<script>
    function onSelectedOption(sel) {
        if ((sel.selectedIndex) == 0) {
            document.getElementById("edit").action =
            "http://www.example.co.uk/index.php";
            document.getElementById("edit").submit();
        }
        else
        {
            document.getElementById("edit").action =
            "http://www.example.co.uk/different.php";
            document.getElementById("edit").submit();
        }
    }
</script>

<form name="edit" id="edit" action="" method="GET">
    <input type="hidden" name="id" value="{ID}" />
</form>

<select name="option" id="option" onchange="onSelectedOption(this);">
    <option name="contactBuyer">Edit item</option>
    <option name="relist">End listing</option>
</select>

Hibernate-sequence doesn't exist

Working with Spring Boot

Solution

Put the string below in .application.properties

spring.jpa.properties.hibernate.id.new_generator_mappings=false

Explanation

On Hibernate 4.X this attribute defaults to true.

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

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

I've found a working code:

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);

Numpy where function multiple conditions

Try:

import numpy as np
dist = np.array([1,2,3,4,5])
r = 2
dr = 3
np.where(np.logical_and(dist> r, dist<=r+dr))

Output: (array([2, 3]),)

You can see Logic functions for more details.

How to use greater than operator with date?

Adding this since this was not mentioned.

SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');

Because that's what actually works for me. Adding date() function on both comparison values.

jQuery get the image src

You may find likr

$('.class').find('tag').attr('src');

php.ini: which one?

Generally speaking, the cli/php.ini file is used when the PHP binary is called from the command-line.
You can check that running php --ini from the command-line.

fpm/php.ini will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo() from a php page served by your webserver.

cgi/php.ini, in your situation, will most likely not be used.


Using two distinct php.ini files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.

Typically, in the php.ini file that's used by the web-server, you'll specify a rather short max_execution_time : web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini file that will be used is the one in cli/. For those scripts, you'll specify a much longer max_execution_time in cli/php.ini than you did in fpm/php.ini.

max_execution_time is a common example ; you could do the same with several other configuration directives, of course.

How to uninstall Jenkins?

Run the following commands to completely uninstall Jenkins from MacOS Sierra. You don't need to change anything, just run these commands.

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins '/Library/Application Support/Jenkins' /Library/Documentation/Jenkins
sudo rm -rf /Users/Shared/Jenkins
sudo rm -rf /var/log/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
pkgutil --pkgs
grep 'org\.jenkins-ci\.'
xargs -n 1 sudo pkgutil --forget

Salam

Shah

Recursive sub folder search and return files in a list python

I will translate John La Rooy's list comprehension to nested for's, just in case anyone else has trouble understanding it.

result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

Should be equivalent to:

import glob
import os

result = []

for x in os.walk(PATH):
    for y in glob.glob(os.path.join(x[0], '*.txt')):
        result.append(y)

Here's the documentation for list comprehension and the functions os.walk and glob.glob.

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

MongoDB inserts float when trying to insert integer

A slightly simpler syntax (in Robomongo at least) worked for me:

db.database.save({ Year : NumberInt(2015) });

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is my personal goto for this topic:

Gist here, (pull requests welcome!): https://gist.github.com/thorsummoner/b5b1dfcff7e7fdd334ec

import multiprocessing
import sys

THREADS = 3

# Used to prevent multiple threads from mixing thier output
GLOBALLOCK = multiprocessing.Lock()


def func_worker(args):
    """This function will be called by each thread.
    This function can not be a class method.
    """
    # Expand list of args into named args.
    str1, str2 = args
    del args

    # Work
    # ...



    # Serial-only Portion
    GLOBALLOCK.acquire()
    print(str1)
    print(str2)
    GLOBALLOCK.release()


def main(argp=None):
    """Multiprocessing Spawn Example
    """
    # Create the number of threads you want
    pool = multiprocessing.Pool(THREADS)

    # Define two jobs, each with two args.
    func_args = [
        ('Hello', 'World',), 
        ('Goodbye', 'World',), 
    ]


    try:
        # Spawn up to 9999999 jobs, I think this is the maximum possible.
        # I do not know what happens if you exceed this.
        pool.map_async(func_worker, func_args).get(9999999)
    except KeyboardInterrupt:
        # Allow ^C to interrupt from any thread.
        sys.stdout.write('\033[0m')
        sys.stdout.write('User Interupt\n')
    pool.close()

if __name__ == '__main__':
    main()

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

How to write connection string in web.config file and read from it?

Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.

The configuration and the access to the Connection string looks all right to me. I would always add a providername

<connectionStrings>
  <add name="Dbconnection" 
       connectionString="Server=localhost; Database=OnlineShopping; 
       Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

How to update the value stored in Dictionary in C#?

It's possible by accessing the key as index

for example:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

Error: Uncaught SyntaxError: Unexpected token <

This is a browser issue rather than a javascript or JQuery issue; it's attempting to interpret the angle bracket as an HTML tag.

Try doing this when setting up your javascripts:

<script>
//<![CDATA[

    // insert teh codez

//]]>
</script>

Alternatively, move your javascript to a separate file.

Edit: Ahh.. with that link I've tracked it down. What I said was the issue wasn't the issue at all. this is the issue, stripped from the website:

<script type="text/javascript"
    $(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

Can you spot the error? It's in the first line: the <script tag isn't closed. It should be <script type="text/javascript">

My previous suggestion still stands, however: you should enclose intra-tagged scripts in a CDATA block, or move them to a separately linked file.

That wasn't the issue here, but it would have shown the real issue faster.

Why do we use Base64?

What does it mean "media that are designed to deal with textual data"?

That those protocols were designed to handle text (often, only English text) instead of binary data (like .png and .jpg images).

They can deal with binary => they can deal with anything.

But the converse is not true. A protocol designed to represent text may improperly treat binary data that happens to contain:

  • The bytes 0x0A and 0x0D, used for line endings, which differ by platform.
  • Other control characters like 0x00 (NULL = C string terminator), 0x03 (END OF TEXT), 0x04 (END OF TRANSMISSION), or 0x1A (DOS end-of-file) which may prematurely signal the end of data.
  • Bytes above 0x7F (if the protocol that was designed for ASCII).
  • Byte sequences that are invalid UTF-8.

So you can't just send binary data over a text-based protocol. You're limited to the bytes that represent the non-space non-control ASCII characters, of which there are 94. The reason Base 64 was chosen was that it's faster to work with powers of two, and 64 is the largest one that works.

One question though. How is that systems still don't agree on a common encoding technique like the so common UTF-8?

On the Web, at least, they mostly have. A majority of sites use UTF-8.

The problem in the West is that there is a lot of old software that ass-u-me-s that 1 byte = 1 character and can't work with UTF-8.

The problem in the East is their attachment to encodings like GB2312 and Shift_JIS.

And the fact that Microsoft seems to have still not gotten over having picked the wrong UTF encoding. If you want to use the Windows API or the Microsoft C runtime library, you're limited to UTF-16 or the locale's "ANSI" encoding. This makes it painful to use UTF-8 because you have to convert all the time.

How to echo xml file in php

If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.

<?php 
$curl = curl_init();        
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');   
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
$result = curl_exec ($curl);   

if ($result === false) {
    die('Error fetching data: ' . curl_error($curl));   
}
curl_close ($curl);    

//we can at this point echo the XML if you want
//echo $result;

//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);

if ($xml === false) {
    die('Error parsing XML');   
}

//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
    print $item->title;   
}

Allow docker container to connect to a local/host postgres database

In Ubuntu:

First You have to check that is the Docker Database port is Available in your system by following command -

sudo iptables -L -n

Sample OUTPUT:

Chain DOCKER (1 references)
target     prot opt source               destination         
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.2           tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:22

Here 3306 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

Now, You can easily access the Docker Database from your local system by following configuration

  host: 172.17.0.2 
  adapter: mysql
  database: DATABASE_NAME
  port: 3307
  username: DATABASE_USER
  password: DATABASE_PASSWORD
  encoding: utf8

In CentOS:

First You have to check that is the Docker Database port is Available in your firewall by following command -

sudo firewall-cmd --list-all

Sample OUTPUT:

  target: default
  icmp-block-inversion: no
  interfaces: eno79841677
  sources: 
  services: dhcpv6-client ssh
  **ports: 3307/tcp**
  protocols: 
  masquerade: no
  forward-ports: 
  sourceports: 
  icmp-blocks: 
  rich rules:

Here 3307 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo firewall-cmd --zone=public --add-port=3307/tcp

In server, You can add the port permanently

sudo firewall-cmd --permanent --add-port=3307/tcp
sudo firewall-cmd --reload

Now, You can easily access the Docker Database from your local system by the above configuration.

How to get a value from the last inserted row?

With PostgreSQL you can do it via the RETURNING keyword:

PostgresSQL - RETURNING

INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield

It will return the value of "anyfield". "anyfield" may be a sequence or not.

To use it with JDBC, do:

ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID");
rs.next();
rs.getInt(1);

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Programmatically change the src of an img tag

Give your image an id. Then you can do this in your javascript.

document.getElementById("blaah").src="blaah";

You can use the ".___" method to change the value of any attribute of any element.

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

Math.random() explanation

int randomWithRange(int min, int max)
{
   int range = (max - min) + 1;     
   return (int)(Math.random() * range) + min;
}

Output of randomWithRange(2, 5) 10 times:

5
2
3
3
2
4
4
4
5
4

The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

EDIT: If someone was going to try and be stupid and reverse min and max, you could change the code to:

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2: For your question about doubles, it's just:

double randomWithRange(double min, double max)
{
   double range = (max - min);     
   return (Math.random() * range) + min;
}

And again if you want to idiot-proof it it's just:

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}

How to test if a string is basically an integer in quotes using Ruby

You can use regular expressions. Here is the function with @janm's suggestions.

class String
    def is_i?
       !!(self =~ /\A[-+]?[0-9]+\z/)
    end
end

An edited version according to comment from @wich:

class String
    def is_i?
       /\A[-+]?\d+\z/ === self
    end
end

In case you only need to check positive numbers

  if !/\A\d+\z/.match(string_to_check)
      #Is not a positive number
  else
      #Is all good ..continue
  end  

How to set a value for a selectize.js input?

I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value to set associations.

I solved this by setting a coffeescript var of @valueAttr to the id of each object and a var of @dataAttr to the name of the record. Then I went through each option and set:

 opts.labelField = @dataAttr
 opts.valueField = @valueAttr

It helps to see the full diff: https://github.com/18F/C2/pull/912/files

Close Android Application

android.os.Process.killProcess(android.os.Process.myPid());

This code kill the process from OS Using this code disturb the OS. So I would recommend you to use the below code

this.finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

How to get the current working directory in Java?

This isn't exactly what's asked, but here's an important note: When running Java on a Windows machine, the Oracle installer puts a "java.exe" into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there's a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(".") keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.

Unfortunately, there's really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it's launched. Everything else is going to have at least some nuance that could break under certain situations.

How to refer to relative paths of resources when working with a code repository

Try to use a filename relative to the current files path. Example for './my_file':

fn = os.path.join(os.path.dirname(__file__), 'my_file')

In Python 3.4+ you can also use pathlib:

fn = pathlib.Path(__file__).parent / 'my_file'

Dart/Flutter : Converting timestamp

You can use intl package, first import

import 'package:intl/intl.dart';

And then

int timeInMillis = 1586348737122;
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat.yMMMd().format(date); // Apr 8, 2020

What is the best way to get all the divisors of a number?

For me this works fine and is also clean (Python 3)

def divisors(number):
    n = 1
    while(n<number):
        if(number%n==0):
            print(n)
        else:
            pass
        n += 1
    print(number)

Not very fast but returns divisors line by line as you wanted, also you can do list.append(n) and list.append(number) if you really want to

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

For security reason mysql -u root wont work untill you pass -p in command so try with below way

 mysql -u root -p[Enter]
 //enter your localhost password

Escaping quotes and double quotes

I found myself in a similar predicament today while trying to run a command through a Node.js module:

I was using the PowerShell and trying to run:

command -e 'func($a)'

But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:

command -e `"func($a)`"

How to find all trigger associated with a table with SQL Server?

you can open your trigger with sp_helptext yourtriggername

Best practices for circular shift (rotate) operations in C++

Source Code x bit number

int x =8;
data =15; //input
unsigned char tmp;
for(int i =0;i<x;i++)
{
printf("Data & 1    %d\n",data&1);
printf("Data Shifted value %d\n",data>>1^(data&1)<<(x-1));
tmp = data>>1|(data&1)<<(x-1);
data = tmp;  
}

Is log(n!) = T(n·log(n))?

Remember that

log(n!) = log(1) + log(2) + ... + log(n-1) + log(n)

You can get the upper bound by

log(1) + log(2) + ... + log(n) <= log(n) + log(n) + ... + log(n)
                                = n*log(n)

And you can get the lower bound by doing a similar thing after throwing away the first half of the sum:

log(1) + ... + log(n/2) + ... + log(n) >= log(n/2) + ... + log(n) 
                                       = log(n/2) + log(n/2+1) + ... + log(n-1) + log(n)
                                       >= log(n/2) + ... + log(n/2)
                                        = n/2 * log(n/2) 

Is background-color:none valid CSS?

write this:

.class {
background-color:transparent;
}

Android design support library for API 28 (P) not working

Try this:

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Get the row(s) which have the max value in groups using groupby

df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

df.groupby(['sp', 'mt']).apply(lambda grp: grp.nlargest(1, 'count'))

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

Based on user @andygjp's answer, its better if you override the base Db.SaveChanges() method and add a function to override any date which does not fall between SqlDateTime.MinValue and SqlDateTime.MaxValue.

Here is the sample code

public class MyDb : DbContext
{
    public override int SaveChanges()
    {
        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries().Where(x => (x.State == EntityState.Added || x.State == EntityState.Modified)))
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Taken from the user @sky-dev's comment on https://stackoverflow.com/a/11297294/9158120

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

Maybe a bit late, but this is my RE:

/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/

Explanation:

\w* -> 0 or more alphanumeric digits, at the beginning

\d+[a-zA-Z]|[a-zA-Z]+\d -> a digit + a letter OR a letter + a digit

\w* -> 0 or more alphanumeric digits, again

I hope it was understandable

Storing Objects in HTML5 localStorage

Another option would be to use an existing plugin.

For example persisto is an open source project that provides an easy interface to localStorage/sessionStorage and automates persistence for form fields (input, radio buttons, and checkboxes).

persisto features

(Disclaimer: I am the author.)

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

Python TypeError: not enough arguments for format string

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.

In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)

In [28]: Series(np.random.randn(3))*1000000000
Out[28]: 
0    -757322420.605
1   -1436160588.997
2   -1235116117.064
dtype: float64

I'm not sure if that's the preferred way to do this, but it works.

Converting numbers to strings purely for aesthetic purposes seems like a bad idea, but if you have a good reason, this is one way:

In [6]: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)
Out[6]: 
0     0.026
1    -0.482
2    -0.694
dtype: object

How to get Bitmap from an Uri?

you can do this structure:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    Bundle extras = imageReturnedIntent.getExtras();
                    bitmap = extras.getParcelable("data");
            }
            break;
   }

by this you can easily convert a uri to bitmap. hope help u.

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

Simple as that :

stuff = [2, 4, 8, 15, 11]

index = stuff.index(max(stuff))

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

try the following query.

select object_name(sfc.constraint_object_id) AS constraint_name,
       OBJECT_Name(parent_object_id) AS table_name ,
       ac1.name as table_column_name,
       OBJECT_name(referenced_object_id) as reference_table_name,      
       ac2.name as reference_column_name
from  sys.foreign_key_columns sfc
join sys.all_columns ac1 on (ac1.object_id=sfc.parent_object_id and ac1.column_id=sfc.parent_column_id)
join sys.all_columns ac2 on (ac2.object_id=sfc.referenced_object_id and ac2.column_id=sfc.referenced_column_id) 
where sfc.parent_object_id=OBJECT_ID(<main table name>);

this will give the constraint_name, column_names which will be referring and tables which will be depending on the constraint will be there.

How to completely uninstall Visual Studio 2010?

There is a solution here : Add

/full /netfx at the end of the path!

This should clear almost all. You should only be left with SQL Server.

Git: Recover deleted (remote) branch

Your deleted branches are not lost, they were copied into origin/contact_page and origin/new_pictures “remote tracking branches” by the fetch you showed (they were also pushed back out by the push you showed, but they were pushed into refs/remotes/origin/ instead of refs/heads/). Check git log origin/contact_page and git log origin/new_pictures to see if your local copies are “up to date” with whatever you think should be there. If any new commits were pushed onto those branches (from some other repo) between the fetch and push that you showed, you may have “lost” those (but probably you could probably find them in the other repo that most recently pushed those branches).

Fetch/Push Conflict

It looks like you are fetching in a normal, ‘remote mode’ (remote refs/heads/ are stored locally in refs/remotes/origin/), but pushing in ‘mirror mode’ (local refs/ are pushed onto remote refs/). Check your .git/config and reconcile the remote.origin.fetch and remote.origin.push settings.

Make a Backup

Before trying any changes, make a simple tar or zip archive or your whole local repo. That way, if you do not like what happens, you can try again from a restored repo.

Option A: Reconfigure as a Mirror

If you intend to use your remote repo as a mirror of your local one, do this:

git branch contact_page origin/contact_page &&
git branch new_pictures origin/new_pictures &&
git config remote.origin.fetch '+refs/*:refs/*' &&
git config --unset remote.origin.push &&
git config remote.origin.mirror true

You might also eventually want to do delete all your refs/remotes/origin/ refs, since they are not useful if you are operating in mirror mode (your normal branches take the place of the usual remote tracking branches).

Option B: Reconfigure as a Normal Remote

But since it seems that you are using this remote repo with multiple “work” repos, you probably do not want to use mirror mode. You might try this:

git config push.default tracking &&
git config --unset remote.origin.push
git config --unset remote.origin.mirror

Then, you will eventually want to delete the bogus refs/remotes/origin refs in your remote repo: git push origin :refs/remotes/origin/contact_page :refs/remotes/origin/new_pictures ….

Test Push

Try git push --dry-run to see what it git push would do without having it make any changes on the remote repo. If you do not like what it says it is going to do, recover from your backup (tar/zip) and try the other option.

Selected tab's color in Bottom Navigation View

This will work:

setItemBackgroundResource(android.R.color.holo_red_light)

Getting the computer name in Java

The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.

import java.net.InetAddress;
import java.net.UnknownHostException;

String hostname = "Unknown";

try
{
    InetAddress addr;
    addr = InetAddress.getLocalHost();
    hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
    System.out.println("Hostname can not be resolved");
}

Convert seconds to Hour:Minute:Second

$given = 685;

 /*
 * In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
 * We would need to take this into consideration, and so we will first
 * check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
 * and then after multiplying it by the number of hours in a day (24), we
 * will just use "floor" to get the number of hours as the rest would
 * be the minutes and seconds anyways.
 *
 * We can also have minutes and seconds combined in one variable,
 * e.g. $min_sec = gmdate( "i:s", $given );
 * But for versatility sake, I have taken them separately.
 */

$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

$min = gmdate( "i", $given );

$sec = gmdate( "s", $given );

echo $formatted_string = $hours.':'.$min.':'.$sec;

To convert it into a function:

function getHoursFormat( $given ){

 $hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

 $min = gmdate( "i", $given );

 $sec = gmdate( "s", $given );

 $formatted_string = $hours.':'.$min.':'.$sec;

 return $formatted_string;

}

How to query between two dates using Laravel and Eloquent?

I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

You will also need to use Carbon

use Carbon\Carbon;

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

gulp command not found - error after installing gulp

Try to add to your PATH variable the following:

C:\Users\YOUR_USER\AppData\Roaming\npm

I had the same problem and I solved adding the path to my node modules.

OnClick in Excel VBA

SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...

I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)

You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.

If you don't like VBA, btw, you can do the same using VB.NET or C#.

[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]

How do I trim a file extension from a String in Java?

public static String removeExtension(String file) {
    if(file != null && file.length() > 0) {
        while(file.contains(".")) {
            file = file.substring(0, file.lastIndexOf('.'));
        }
    }
    return file;
}

Break out of a While...Wend loop

Another option would be to set a flag variable as a Boolean and then change that value based on your criteria.

Dim count as Integer 
Dim flag as Boolean

flag = True

While flag
    count = count + 1 

    If count = 10 Then
        'Set the flag to false         '
        flag = false
    End If 
Wend

Filtering Table rows using Jquery

tr:not(:contains(.... work for me

function busca(busca){
    $("#listagem tr:not(:contains('"+busca+"'))").css("display", "none");
    $("#listagem tr:contains('"+busca+"')").css("display", "");
}

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Inject service in app.config

I don't think you're supposed to be able to do this, but I have successfully injected a service into a config block. (AngularJS v1.0.7)

angular.module('dogmaService', [])
    .factory('dogmaCacheBuster', [
        function() {
            return function(path) {
                return path + '?_=' + Date.now();
            };
        }
    ]);

angular.module('touch', [
        'dogmaForm',
        'dogmaValidate',
        'dogmaPresentation',
        'dogmaController',
        'dogmaService',
    ])
    .config([
        '$routeProvider',
        'dogmaCacheBusterProvider',
        function($routeProvider, cacheBuster) {
            var bust = cacheBuster.$get[0]();

            $routeProvider
                .when('/', {
                    templateUrl: bust('touch/customer'),
                    controller: 'CustomerCtrl'
                })
                .when('/screen2', {
                    templateUrl: bust('touch/screen2'),
                    controller: 'Screen2Ctrl'
                })
                .otherwise({
                    redirectTo: bust('/')
                });
        }
    ]);

angular.module('dogmaController', [])
    .controller('CustomerCtrl', [
        '$scope',
        '$http',
        '$location',
        'dogmaCacheBuster',
        function($scope, $http, $location, cacheBuster) {

            $scope.submit = function() {
                $.ajax({
                    url: cacheBuster('/customers'),  //server script to process data
                    type: 'POST',
                    //Ajax events
                    // Form data
                    data: formData,
                    //Options to tell JQuery not to process data or worry about content-type
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function() {
                        $location
                            .path('/screen2');

                        $scope.$$phase || $scope.$apply();
                    }
                });
            };
        }
    ]);

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

How to remove all namespaces from XML with C#?

user892217's answer is almost correct. It won't compile as is, so needs a slight correction to the recursive call:

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    XElement xElement;

    if (!xmlDocument.HasElements)
    {
        xElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
    }
    else
    {
        xElement = new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(x => RemoveAllNamespaces(x)));
    }

    foreach (var attribute in xmlDocument.Attributes())
    {
        if (!attribute.IsNamespaceDeclaration)
        {
            xElement.Add(attribute);
        }
    }

    return xElement;
}

How to grant all privileges to root user in MySQL 8.0

This worked for me:

mysql> FLUSH PRIVILEGES 
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

how to loop through each row of dataFrame in pyspark

Give A Try Like this

    result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]); 
    for f in result.collect(): 
        print (f.col_name)

replacing text in a file with Python

This should do it

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        outfile.write(line)

EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:

lines = []
with open('path/to/input/file') as infile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        lines.append(line)
with open('path/to/input/file', 'w') as outfile:
    for line in lines:
        outfile.write(line)

Edit: If you are using Python 3.x, use replacements.items() instead of replacements.iteritems()

Switch statement equivalent in Windows batch file

Try by this way. To perform some list of operations like

  1. Switch case has been used.
  2. Checking the conditional statements.
  3. Invoking the function with more than two arguments.

 @echo off
 :Start2 
    cls
    goto Start
    :Start
    echo --------------------------------------
    echo     Welcome to the Shortcut tool     
    echo --------------------------------------            
    echo Choose from the list given below:
    echo [1] 2017
    echo [2] 2018
    echo [3] Task

    set /a one=1
    set /a two=2
    set /a three=3
    set /a four=4
    set input=
    set /p input= Enter your choice:
    if %input% equ %one% goto Z if NOT goto Start2
    if %input% equ %two% goto X if NOT goto Start2
    if %input% equ %three% goto C if NOT goto Start2
    if %input% geq %four% goto N

    :Z
    cls
    echo You have selected year : 2017
    set year=2017
    echo %year%
    call:branches year

    pause
    exit

    :X
    cls
    echo You have selected year : 2018
    set year=2018
    echo %year%
    call:branches year
    pause
    exit

    :C  
    cls
    echo You have selected Task
    call:Task
    pause
    exit

    :N
    cls
    echo Invalid Selection! Try again
    pause
    goto :start2




    :branches
    cls
    echo Choose from the list of Branches given below:
    echo [1] January
    echo [2] Feburary
    echo [3] March
    SETLOCAL
    set /a "Number1=%~1"
    set input=
    set /p input= Enter your choice:
    set /a b=0
    set /a bd=3
    set /a bdd=4
    if %input% equ %b% goto N
    if %input% leq %bd% call:Z1 Number1,input if NOT goto Start2
    if %input% geq %bdd% goto N



    :Z1
    cls
    SETLOCAL
    set /a "Number1=%~1"
    echo year = %Number1%
    set /a "Number2=%~2"
    echo branch = %Number2%
    call:operation Number1,Number2
    pause
    GOTO :EOF


    :operation
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set /a "year=%~1"
    echo Your have selected year = %year%
    set /a "month=%~2"
    echo You have selected Branch = %month%
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2






    :Task
    cls
    echo Choose from the list of Operation given below:
    echo [1] UB
    echo [3] B
    echo [4] C
    echo [5] l
    echo [6] R
    echo [7] JT
    echo [8] CT
    echo [9] JT
    SETLOCAL
    set operation=
    set /p operation= Enter your choice:
    set /a b=0
    set /a bd=9
    set /a bdd=10
    if %input% equ %b% goto N
    if %operation% leq %bd% goto :switch-case-N-%operation% if NOT goto Start2
    if %input% geq %bdd% goto N




    :switch-case-N-1
    echo Januray
    echo %operation%
    goto :switch-case-end

    :switch-case-N-2
    echo Feburary
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-N-3
    echo march
    echo %year%,%month%,%operation%
    goto :switch-case-end

    :switch-case-end
       echo Task Completed
       pause
       exit
       goto :start2

T-SQL Subquery Max(Date) and Joins

SELECT
    MyParts.*,MyPriceDate.Price,MyPriceDate.PriceDate
    FROM MyParts
        INNER JOIN (SELECT Partid, MAX(PriceDate) AS MaxPriceDate FROM MyPrice GROUP BY Partid) dt ON MyParts.Partid = dt.Partid
        INNER JOIN MyPrice ON dt.Partid = MyPrice.Partid AND MyPrice.PriceDate=dt.MaxPriceDate

Spring get current ApplicationContext

Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:

    applicationContext.getBean(String serviceName,Interface.Class)

What is the official name for a credit card's 3 digit code?

You can't find a consistent reference because it seems to go by at least six different names!

  • Card Security Code
  • Card Verification Value (CVV or CV2)
  • Card Verification Value Code (CVVC)
  • Card Verification Code (CVC)
  • Verification Code (V-Code or V Code)
  • Card Code Verification (CCV)

How do I best silence a warning about unused variables?

Using an UNREFERENCED_PARAMETER(p) could work. I know it is defined in WinNT.h for Windows systems and can easily be defined for gcc as well (if it doesn't already have it).

UNREFERENCED PARAMETER(p) is defined as

#define UNREFERENCED_PARAMETER(P)          (P)

in WinNT.h.

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

Searching for UUIDs in text with regex

In python re, you can span from numberic to upper case alpha. So..

import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']

That makes the simplest Python UUID regex:

re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)

I'll leave it as an exercise to the reader to use timeit to compare the performance of these.

Enjoy. Keep it Pythonic™!

NOTE: Those spans will also match :;<=>?@' so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)

Mobile Redirect using htaccess

Thanks Tim Stone, naunu, and Kevin Bond, those answers really helped me. Here is my adaption of your code. I added the functionality to be redirected back to the desktop site from m.example.com in case the user does not visit the site with a mobile device. Additionally I added an environment variable to preserve http/https requests:

# Set an environment variable for http/https.
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=ps:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=ps:http]

# Check if m=1 is set and set cookie 'm' equal to 1.
RewriteCond %{QUERY_STRING} (^|&)m=1(&|$)
RewriteRule ^ - [CO=m:1:example.com]

# Check if m=0 is set and set cookie 'm' equal to 0.
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
RewriteRule ^ - [CO=m:0:example.com]

# Cookie can't be set and read in the same request so check.
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
RewriteRule ^ - [S=1]

# Check if this looks like a mobile device.
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
RewriteCond %{HTTP:Profile} !^$
# Check if we're not already on the mobile site.
RewriteCond %{HTTP_HOST} !^m\.
# Check if cookie is not set to force desktop site.
RewriteCond %{HTTP_COOKIE} !^.*m=0.*$ [NC]
# Now redirect to the mobile site preserving http or https.
RewriteRule ^ %{ENV:ps}://m.example.com%{REQUEST_URI} [R,L]

# Check if this looks like a desktop device.
RewriteCond %{HTTP_USER_AGENT} "!(android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile)" [NC]
# Check if we're on the mobile site.
RewriteCond %{HTTP_HOST} ^m\.
# Check if cookie is not set to force mobile site.
RewriteCond %{HTTP_COOKIE} !^.*m=1.*$ [NC]
# Now redirect to the mobile site preserving http or https.
RewriteRule ^ %{ENV:ps}://example.com%{REQUEST_URI} [R,L]

This seems to work fine except one thing: When I'm on the desktop site with a desktop device and I visit m.example.com/?m=1, I'm redirected to example.com. When I try again, I "stay" at m.example.com. It seems as if the cookie isn't set and/or read correctly the first time.

Maybe there is a better way to determine if the device is a desktop device, I just negated the device detection from above.

And I'm wondering if this way all mobile devices are detected. In Tim Stone's and naunu's code that part is much larger.

downcast and upcast

  • Upcasting is an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
  • Downcasting is an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)

In your case

Employee emp = (Employee)mgr; //mgr is Manager

you are doing an upcasting.

An upcast always succeeds unlike a downcast that requires an explicit cast because it can potentially fail at runtime.(InvalidCastException).

C# offers two operators to avoid this exception to be thrown:

Starting from:

Employee e = new Employee();

First:

Manager m = e as Manager; // if downcast fails m is null; no exception thrown

Second:

if (e is Manager){...} // the predicate is false if the downcast is not possible 

Warning: When you do an upcast you can only access to the superclass' methods, properties etc...

Phone number formatting an EditText in Android

//(123) 456 7890  formate set

private int textlength = 0;

public class MyPhoneTextWatcher implements TextWatcher {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {


        String text = etMobile.getText().toString();
        textlength = etMobile.getText().length();

        if (text.endsWith(" "))
            return;

        if (textlength == 1) {
            if (!text.contains("(")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, "(").toString());
                etMobile.setSelection(etMobile.getText().length());
            }

        } else if (textlength == 5) {

            if (!text.contains(")")) {
                etMobile.setText(new StringBuilder(text).insert(text.length() - 1, ")").toString());
                etMobile.setSelection(etMobile.getText().length());
            }

        } else if (textlength == 6 || textlength == 10) {
            etMobile.setText(new StringBuilder(text).insert(text.length() - 1, " ").toString());
            etMobile.setSelection(etMobile.getText().length());
        }

    }
    @Override
    public void afterTextChanged(Editable editable) {
    }
}

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

Saving any file to in the database, just convert it to a byte array?

Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.

It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.

How to pass a function as a parameter in Java?

Java does not (yet) support closures. But there are other languages like Scala and Groovy which run in the JVM and do support closures.

Label on the left side instead above an input field

Put the <label> outside the form-group:

<form class="form-inline">
  <label for="rg-from">Ab: </label>
  <div class="form-group">
    <input type="text" id="rg-from" name="rg-from" value="" class="form-control">
  </div>
  <!-- rest of form -->
</form>

Why is `input` in Python 3 throwing NameError: name... is not defined

I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.

how to get all markers on google-maps-v3

I'm assuming you have multiple markers that you wish to display on a google map.

The solution is two parts, one to create and populate an array containing all the details of the markers, then a second to loop through all entries in the array to create each marker.

Not know what environment you're using, it's a little difficult to provide specific help.

My best advice is to take a look at this article & accepted answer to understand the principals of creating a map with multiple markers: Display multiple markers on a map with their own info windows

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

What is the minimum I have to do to create an RPM file?

RPMs are usually built from source, not the binaries.

You need to write the spec file that covers how to configure and compile your application; also, which files to include in your RPM.

A quick glance at the manual shows that most of what you need is covered in Chapter 8 -- also, as most RPM-based distributions have sources available, there's literally a zillion of examples of different approaches you could look at.

how to get GET and POST variables with JQuery?

Here's something to gather all the GET variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.

jQuery.extend({
    'Q' : window.location.search.length <= 1 ? {}
        : function(a){
            var i = a.length, 
                r = /%25/g,  // Ensure '%' is properly represented 
                h = {};      // (Safari auto-encodes '%', Firefox 1.5 does not)
            while(i--) {
                var p = a[i].split('=');
                h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
            }
            return h;
        }(window.location.search.substr(1).split('&'))
});

Example usage:

switch ($.Q.event) {
    case 'new' :
        // http://www.site.com/?event=new
        $('#NewItemButton').trigger('click');
        break;
    default :
}

Hope this helps. ;)

Undefined variable: $_SESSION

Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start being on (defaults to off)

If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):

/etc/php.d/my-new-file.ini :

session.auto_start = 1

(This is correct for CentOS 8, adjust for your OS/packaging)

Excel VBA Run Time Error '424' object required

Private Sub CommandButton1_Click()

    Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption

    Me.Hide

    Run "filename"

End Sub

Private Sub MUN_Change()
    Dim r As Integer
    r = 2

    While Range("m" & CStr(r)).Value <> ""
        If Range("m" & CStr(r)).Value = MUN.Text Then
        Label5.Caption = Range("n" & CStr(r)).Value
        End If
        r = r + 1
    Wend

End Sub

Private Sub PROV_Change()
    If PROV.Text = "LAGUNA" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M26:M56"
    ElseIf PROV.Text = "CAVITE" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M2:M25"
    ElseIf PROV.Text = "QUEZON" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M57:M97"
    End If
End Sub

java.net.SocketException: Connection reset

I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

Using 24 hour time in bootstrap timepicker

<script>    
    $(function () {

        /* setting time */
        $("#timepicker").datetimepicker({
            format : "HH:mm:ss"
        });

    }    
</script>

Example bootstrap datetimepicker eonasdan

Create numpy matrix filled with NaNs

I compared the suggested alternatives for speed and found that, for large enough vectors/matrices to fill, all alternatives except val * ones and array(n * [val]) are equally fast.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot

val = 42.0


def fill(n):
    a = numpy.empty(n)
    a.fill(val)
    return a


def colon(n):
    a = numpy.empty(n)
    a[:] = val
    return a


def full(n):
    return numpy.full(n, val)


def ones_times(n):
    return val * numpy.ones(n)


def list(n):
    return numpy.array(n * [val])


perfplot.show(
    setup=lambda n: n,
    kernels=[fill, colon, full, ones_times, list],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

Get all files that have been modified in git branch

An alternative to the answer by @Marco Ponti, and avoiding the checkout:

git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>)

If your particular shell doesn't understand the $() construct, use back-ticks instead.

What strategies and tools are useful for finding memory leaks in .NET?

You still need to worry about memory when you are writing managed code unless your application is trivial. I will suggest two things: first, read CLR via C# because it will help you understand memory management in .NET. Second, learn to use a tool like CLRProfiler (Microsoft). This can give you an idea of what is causing your memory leak (e.g. you can take a look at your large object heap fragmentation)

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

I think the problem is with the user having deny privileges. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want.

GRANT the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database.

How do I escape a percentage sign in T-SQL?

You can use the code below to find a specific value.

WHERE col1 LIKE '%[%]75%'

When you want a single digit number after the% sign, you can write the following code.

WHERE col2 LIKE '%[%]_'

Why does adb return offline after the device string?

also make sure adb isn't running in your processes automatically. If it's there right click open file location, figure out what is starting it, kill it with fire. Run the updated adb from an updated android sdk platform tools. This was the issue with mine, hope it helps someone.

How can I move all the files from one folder to another using the command line?

move c:\sourcefolder c:\targetfolder

will work, but you will end up with a structure like this:

c:\targetfolder\sourcefolder\[all the subfolders & files]

If you want to move just the contents of one folder to another, then this should do it:

SET src_folder=c:\srcfold
SET tar_folder=c:\tarfold

for /f %%a IN ('dir "%src_folder%" /b') do move "%src_folder%\%%a" "%tar_folder%\"

pause

Python virtualenv questions

Normally virtualenv creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32 for some reason, I would use a different directory for environments.

You shouldn't need to mess with paths: use the activate script (in <env>\Scripts) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate to set everything back to how it was before activation.

Example:

c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>

Notice how I didn't need to specify a path for deactivate - activate does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix and it should print the root of your environment.)

You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.

If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper (the link points to a port of this to Powershell) makes life with virtualenv even easier.

Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.

Further update: You should be able to use pip, distribute instead of setuptools, and just plain python setup.py install with virtualenv. Just ensure you've activated an environment before installing something into it.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

filters on ng-model in an input

Use a directive which adds to both the $formatters and $parsers collections to ensure that the transformation is performed in both directions.

See this other answer for more details including a link to jsfiddle.

jQuery.animate() with css class only, without explicit styles

The jQueryUI provides a extension to animate function that allows you to animate css class.

edit: Example here

There are also methods to add/remove/toggle class which you might also be interested in.

How to retrieve records for last 30 minutes in MS SQL?

SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

How to get a enum value from string in C#?

baseKey choice;
if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
     uint value = (uint)choice;

     // `value` is what you're looking for

} else { /* error: the string was not an enum member */ }

Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")

How to get the last five characters of a string using Substring() in C#?

string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}

What is PostgreSQL equivalent of SYSDATE from Oracle?

SYSDATE is an Oracle only function.

The ANSI standard defines current_date or current_timestamp which is supported by Postgres and documented in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

(Btw: Oracle supports CURRENT_TIMESTAMP as well)

You should pay attention to the difference between current_timestamp, statement_timestamp() and clock_timestamp() (which is explained in the manual, see the above link)


This statement:

select up_time from exam where up_time like sysdate

Does not make any sense at all. Neither in Oracle nor in Postgres. If you want to get rows from "today", you need something like:

select up_time 
from exam 
where up_time = current_date

Note that in Oracle you would probably want trunc(up_time) = trunc(sysdate) to get rid of the time part that is always included in Oracle.

What is the best way to implement constants in Java?

Creating static final constants in a separate class can get you into trouble. The Java compiler will actually optimize this and place the actual value of the constant into any class that references it.

If you later change the 'Constants' class and you don't do a hard re-compile on other classes that reference that class, you will wind up with a combination of old and new values being used.

Instead of thinking of these as constants, think of them as configuration parameters and create a class to manage them. Have the values be non-final, and even consider using getters. In the future, as you determine that some of these parameters actually should be configurable by the user or administrator, it will be much easier to do.

Multipart forms from C# client

I needed to simulate a browser login to a website to get a login cookie, and the login form was multipart/form-data.

I took some clues from the other answers here, and then tried to get my own scenario working. It took a bit of frustrating trial and error before it worked right, but here is the code:

    public static class WebHelpers
    {
        /// <summary>
        /// Post the data as a multipart form
        /// </summary>
       public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, string> values)
       {
           string formDataBoundary = "---------------------------" + WebHelpers.RandomHexDigits(12);
           string contentType = "multipart/form-data; boundary=" + formDataBoundary;

           string formData = WebHelpers.MakeMultipartForm(values, formDataBoundary);
           return WebHelpers.PostForm(postUrl, userAgent, contentType, formData);
       }

        /// <summary>
        /// Post a form
        /// </summary>
        public static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, string formData)
        {
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            // Add these, as we're doing a POST
            request.Method = "POST";
            request.ContentType = contentType;
            request.UserAgent = userAgent;
            request.CookieContainer = new CookieContainer();

            // We need to count how many bytes we're sending. 
            byte[] postBytes = Encoding.UTF8.GetBytes(formData);
            request.ContentLength = postBytes.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                // Push it out there
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();
            }

            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// Generate random hex digits 
        /// </summary>
        public static string RandomHexDigits(int count)
        {
            Random random = new Random();
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                int digit = random.Next(16);
                result.AppendFormat("{0:x}", digit);
            }

            return result.ToString();
        }

        /// <summary>
        /// Turn the key and value pairs into a multipart form
        /// </summary>
        private static string MakeMultipartForm(Dictionary<string, string> values, string boundary)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var pair in values)
            {
                sb.AppendFormat("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, pair.Key, pair.Value);
            }

            sb.AppendFormat("--{0}--\r\n", boundary);

            return sb.ToString();    
        }
    }
}

It doesn't handle file data, just form since that's all that I needed. I called like this:

    try
    {
        using (HttpWebResponse response = WebHelpers.MultipartFormDataPost(postUrl, UserAgentString, this.loginForm)) 
        {
            if (response != null)
            {
                Cookie loginCookie = response.Cookies["logincookie"];
                .....

Can you center a Button in RelativeLayout?

Summarized

Adding:

android:layout_centerInParent="true"

just works on RelativeLayout, if one of the following attributes is also set for the view:

android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"

which alignes the child view to the parent view. The "center" is based on the axis of the alignement you have chosen:

left/right -> vertical

top/bottom -> horizontal

Setting the gravity of childs/content inside the view:

android:gravity="center"

is centering the child inside the parent view in any case, if there is no alignment set. Optional you can choose:

<!-- Axis to Center -->
android:gravity="center_horizontal"
android:gravity="center_vertical"

<!-- Alignment to set-->
android:gravity="top"
android:gravity="bottom"
android:gravity="left"
android:gravity="right"
android:gravity="fill"
...

Then there is:

android:layout_gravity="center"

which is centering the view itself inside it's parent

And at last you can add the following attribute to the parents view:

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

JavaScript: Is there a way to get Chrome to break on all errors?

I got trouble to get it so I post pictures showing different options:

Chrome 75.0.3770.142 [29 July 2018]

Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]

In tab Sources :

enter image description here

When button is activated, you can Pause On Caught Exceptions with the checkbox below: enter image description here


Previous versions

Chrome 32.0.1700.102 [03 feb 2014]

enter image description here

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

Chrome 27.0.1453.93 Stable

Debug options

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

On Debian/Ubuntu use:

sudo apt-get install g++-multilib libc6-dev-i386

How can I convert a date to GMT?

Simply use Date.getUTC*() family of methods. On my computer (CET, UTC+01:00):

new Date().toString()
//Fri Jan 20 2012 18:05:16 GMT+0100 (CET)

new Date().getHours()
//18

new Date().getUTCHours()
//17

Notice that getUTCHours() returns correct hour in UTC.

See also:

How do I change screen orientation in the Android emulator?

On Android Studio 4.0.1, the emulator includes buttons for rotation.

In the image below, the Rotate Left (shortcut: Ctrl + Left) button is outlined in blue and the Rotate Right (shortcut: Ctrl + Right) button is outlined in red.

Android Emulator

After pressing one of the buttons to rotate, the orientation of the application itself will not change. For instance, if we pressed Rotate Left, the application would look this:

Android Emulator Rotated Left

To change the orientation of the running application, it is necessary to click the icon outlined in red above. Note that this icon may take a few seconds to show up and will disappear shortly. Also, when rotating back to portrait orientation, one must press the opposite rotate button for the icon to appear. This means that if we pressed Rotate Left, we need to press Rotate Right to return to the original orientation, and vice versa.

Android Emulator Landscape

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

How to access the ith column of a NumPy multidimensional array?

>>> test
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

>>> ncol = test.shape[1]
>>> ncol
5L

Then you can select the 2nd - 4th column this way:

>>> test[0:, 1:(ncol - 1)]
array([[1, 2, 3],
       [6, 7, 8]])

How do I resolve "Cannot find module" error using Node.js?

I faced the same problem when someone else in the team updated package.json in SVN. Merely removing the node_modules directory did not help. How I solved the problem is:

rm -rf node_modules
rm package.json
rm package-lock.json
svn up
npm install
ng build --env=prod

Hope this helps someone!

Check if a property exists in a class

There are 2 possibilities.

You really don't have Label property.

You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance

If your property is not public, you will need to use BindingFlags.NonPublic or some other combination of flags which fits your use case. Read the referenced API docs to find the details.

EDIT:

ooops, just noticed you call GetProperty on typeof(MyClass). typeof(MyClass) is Type which for sure has no Label property.

NSDate get year/month/day

Swift 2.x

extension NSDate {
    func currentDateInDayMonthYear() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "d LLLL yyyy"
        return dateFormatter.stringFromDate(self)
    }
}

You can use it as

NSDate().currentDateInDayMonthYear()

Output

6 March 2016

Getting the error "Missing $ inserted" in LaTeX

also, I had this problem but the bib file wouldn't recompile. I removed the problem, which was an underscore in the note field, and compiled the tex file again, but kept getting the same errors. In the end I del'd the compiled bib file (.bbl I think) and it worked fine. I had to escape the _ using a backslash.

How to check if a table contains an element in Lua?

I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.

ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.

function addValue(key, value)
    if (value == nil) then
        removeKey(key)
        return
    end
    _primaryTable[key] = value
    _secodaryTable[value] = key
end

function removeKey(key)
    local value = _primaryTable[key]
    if (value == nil) then
        return
    end
    _primaryTable[key] = nil
    _secondaryTable[value] = nil
end

function getValue(key)
    return _primaryTable[key]
end

function containsValue(value)
    return _secondaryTable[value] ~= nil
end

You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.

If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring on it for example, and then use that as the key.

Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.

The wording of the question however strongly suggests that you have a large number of items to deal with.

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

Node.js: How to read a stream into a buffer?

I just want to post my solution. Previous answers was pretty helpful for my research. I use length-stream to get the size of the stream, but the problem here is that the callback is fired near the end of the stream, so i also use stream-cache to cache the stream and pipe it to res object once i know the content-length. In case on an error,

var StreamCache = require('stream-cache');
var lengthStream = require('length-stream');

var _streamFile = function(res , stream , cb){
    var cache = new StreamCache();

    var lstream = lengthStream(function(length) {
        res.header("Content-Length", length);
        cache.pipe(res);
    });

    stream.on('error', function(err){
        return cb(err);
    });

    stream.on('end', function(){
        return cb(null , true);
    });

    return stream.pipe(lstream).pipe(cache);
}

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If M2_HOME is configured to point to the Maven home directory then:

  1. Go to File -> Settings
  2. Search for Maven
  3. Select Runner
  4. Insert in the field VM Options the following string:

    Dmaven.multiModuleProjectDirectory=$M2_HOME
    

Click Apply and OK

Java string to date conversion

While some of the answers are technically correct, they are not advisable.

  • The java.util.Date & Calendar classes are notoriously troublesome. Because of flaws in design and implementation, avoid them. Fortunately we have our choice of two other excellent date-time libraries:
    • Joda-Time
      This popular open-source free-of-cost library can be used across several versions of Java. Many examples of its usage may be found on StackOverflow. Reading some of these will help get you up to speed quickly.
    • java.time.* package
      This new set of classes are inspired by Joda-Time and defined by JSR 310. These classes are built into Java 8. A project is underway to backport these classes to Java 7, but that backporting is not backed by Oracle.
  • As Kristopher Johnson correctly noted in his comment on the question, the other answers ignore vital issues of:
    • Time of Day
      Date has both a date portion and a time-of-day portion)
    • Time Zone
      The beginning of a day depends on the time zone. If you fail to specify a time zone, the JVM's default time zone is applied. That means the behavior of your code may change when run on other computers or with a modified time zone setting. Probably not what you want.
    • Locale
      The Locale's language specifies how to interpret the words (name of month and of day) encountered during parsing. (The answer by BalusC handles this properly.) Also, the Locale affects the output of some formatters when generating a string representation of your date-time.

Joda-Time

A few notes about Joda-Time follow.

Time Zone

In Joda-Time, a DateTime object truly knows its own assigned time zone. This contrasts the java.util.Date class which seems to have a time zone but does not.

Note in the example code below how we pass a time zone object to the formatter which parses the string. That time zone is used to interpret that date-time as having occurred in that time zone. So you need to think about and determine the time zone represented by that string input.

Since you have no time portion in your input string, Joda-Time assigns the first moment of the day of the specified time zone as the time-of-day. Usually this means 00:00:00 but not always, because of Daylight Saving Time (DST) or other anomalies. By the way, you can do the same to any DateTime instance by calling withTimeAtStartOfDay.

Formatter Pattern

The characters used in a formatter's pattern are similar in Joda-Time to those in java.util.Date/Calendar but not exactly the same. Carefully read the doc.

Immutability

We usually use the immutable classes in Joda-Time. Rather than modify an existing Date-Time object, we call methods that create a new fresh instance based on the other object with most aspects copied except where alterations were desired. An example is the call to withZone in last line below. Immutability helps to make Joda-Time very thread-safe, and can also make some work more clear.

Conversion

You will need java.util.Date objects for use with other classes/framework that do not know about Joda-Time objects. Fortunately, it is very easy to move back and forth.

Going from a java.util.Date object (here named date) to Joda-Time DateTime…

org.joda.time.DateTime dateTime = new DateTime( date, timeZone );

Going the other direction from Joda-Time to a java.util.Date object…

java.util.Date date = dateTime.toDate();

Sample Code

String input = "January 2, 2010";

java.util.Locale locale = java.util.Locale.US;
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Arbitrarily chosen for example.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMMM d, yyyy" ).withZone( timeZone ).withLocale( locale );
DateTime dateTime = formatter.parseDateTime( input );

System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.withZone( DateTimeZone.UTC ) );

When run…

dateTime: 2010-01-02T00:00:00.000-10:00
dateTime in UTC/GMT: 2010-01-02T10:00:00.000Z

How to show validation message below each textbox using jquery?

You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.

Your fiddle is updated, see here: jsfiddle

The code:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

The CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

How to save S3 object to a file using boto3

There is a customization that went into Boto3 recently which helps with this (among other things). It is currently exposed on the low-level S3 client, and can be used like this:

s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')

# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')

# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())

These functions will automatically handle reading/writing files as well as doing multipart uploads in parallel for large files.

Note that s3_client.download_file won't create a directory. It can be created as pathlib.Path('/path/to/file.txt').parent.mkdir(parents=True, exist_ok=True).

How to write to file in Ruby?

You can use the short version:

File.write('/path/to/file', 'Some glorious content')

It returns the length written; see ::write for more details and options.

To append to the file, if it already exists, use:

File.write('/path/to/file', 'Some glorious content', mode: 'a')

Change font-weight of FontAwesome icons?

The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

What do the terms "CPU bound" and "I/O bound" mean?

CPU bound means the program is bottlenecked by the CPU, or central processing unit, while I/O bound means the program is bottlenecked by I/O, or input/output, such as reading or writing to disk, network, etc.

In general, when optimizing computer programs, one tries to seek out the bottleneck and eliminate it. Knowing that your program is CPU bound helps, so that one doesn't unnecessarily optimize something else.

[And by "bottleneck", I mean the thing that makes your program go slower than it otherwise would have.]

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

Amazon Linux: apt-get: command not found

I faced the same issue regarding apt-get: command not found here are the steps how I resolved it on ubuntu xenial

  • Search the appropriate version of apt from here (apt_1.4_amd64.deb for ubuntu xenial)

  • Download the apt.deb

    wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

  • Install the apt.deb package

    sudo dpkg -i apt_1.4_amd64.deb

Now we can easily run

sudo apt-get install htop

How to sort a Collection<T>?

A Collection does not have an ordering, so wanting to sort it does not make sense. You can sort List instances and arrays, and the methods to do that are Collections.sort() and Arrays.sort()

How to use Chrome's network debugger with redirects

I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:

  1. Open the js console
  2. window.addEventListener("beforeunload", function() { debugger; }, false)

This will pause chrome before loading the new page by hitting a breakpoint.

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

How to open SharePoint files in Chrome/Firefox

Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!

It gave me the idea to change the function _DispEx that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file: enter image description here

See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:

    /**
 * fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
 * @param  {HTMLElement} p the <A> element
 * @param  {HTMLEvent} a the click event
 * @param  {Boolean} h TRUE
 * @param  {Boolean} e FALSE
 * @param  {Boolean} g FALSE
 * @param  {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
 * @param  {Number} c 0
 * @param  {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
 * @param  {String} m
 * @param  {String} b the replacement URL to the xslviewer
 */
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
  bak_DispEx = _DispEx;
  _DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
    // if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
    // in that case we want to open ask the user if he/she wants to readonly or edit the file
    var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
    if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
      // if the URL doesn't start with http
      if (!/^http/.test(fileURL)) {
        fileURL = window.location.protocol + "//" + window.location.host + fileURL;
      }
      var ohtml = document.createElement('div');
      ohtml.style.padding = "10px";
      ohtml.style.display = "inline-block";
      ohtml.style.width = "200px";
      ohtml.style.width = "200px";
      ohtml.innerHTML = '<style>'
                      + '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
                      + '.opendocument_button:hover { box-shadow: none }'
                      + '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
                      + '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
                      + '</style>'
                      + 'You are about to open:'
                      + '<ul class="opendocument_ul">'
                      + '  <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
                      + '  <li>From: <b>'+window.location.hostname+'</b></li>'
                      + '</ul>'
                      + 'How would like to open this file?'
                      + '<ul class="opendocument_ul">'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
                      + '</ul>'
                      + '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
      // show the modal
      modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
        html:ohtml,
        dialogReturnValueCallback:function(ret) {
          if (ret!==-1) {
            if (ret === true) { // edit
              // reformat the fileURL
              var ext;
              if (/\.xlsx?$/.test(b)) ext = "ms-excel";
              if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
              fileURL = ext + ":ofe|u|" + fileURL;
            }
            window.location.href = fileURL; // open the file
          }
        }
      });
      a.preventDefault();
      a.stopImmediatePropagation()
      a.cancelBubble = true;
      a.returnValue = false;
      return false;
    }
    return bak_DispEx.apply(this, arguments);
  }
}, "sp.scriptloaded-core.js")

I use SP.SOD.executeOrDelayUntilEventNotified to make sure the function will be executed when core.js is loaded.

Why is volatile needed in C?

My simple explanation is:

In some scenarios, based on the logic or code, the compiler will do optimisation of variables which it thinks do not change. The volatile keyword prevents a variable being optimised.

For example:

bool usb_interface_flag = 0;
while(usb_interface_flag == 0)
{
    // execute logic for the scenario where the USB isn't connected 
}

From the above code, the compiler may think usb_interface_flag is defined as 0, and that in the while loop it will be zero forever. After optimisation, the compiler will treat it as while(true) all the time, resulting in an infinite loop.

To avoid these kinds of scenarios, we declare the flag as volatile, we are telling to compiler that this value may be changed by an external interface or other module of program, i.e., please don't optimise it. That's the use case for volatile.

CSS - display: none; not working

Another trick is to use

.class {
position: absolute;
visibility:hidden;
display:none;
}

This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none works later on it will be working. Keep in mind that visibility:hidden may not remove it from screen readers.

How to 'insert if not exists' in MySQL?

use INSERT IGNORE INTO table

see http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html

there's also INSERT … ON DUPLICATE KEY UPDATE syntax, you can find explanations on dev.mysql.com


Post from bogdan.org.ua according to Google's webcache:

18th October 2007

To start: as of the latest MySQL, syntax presented in the title is not possible. But there are several very easy ways to accomplish what is expected using existing functionality.

There are 3 possible solutions: using INSERT IGNORE, REPLACE, or INSERT … ON DUPLICATE KEY UPDATE.

Imagine we have a table:

CREATE TABLE `transcripts` (
`ensembl_transcript_id` varchar(20) NOT NULL,
`transcript_chrom_start` int(10) unsigned NOT NULL,
`transcript_chrom_end` int(10) unsigned NOT NULL,
PRIMARY KEY (`ensembl_transcript_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now imagine that we have an automatic pipeline importing transcripts meta-data from Ensembl, and that due to various reasons the pipeline might be broken at any step of execution. Thus, we need to ensure two things:

  1. repeated executions of the pipeline will not destroy our database

  2. repeated executions will not die due to ‘duplicate primary key’ errors.

Method 1: using REPLACE

It’s very simple:

REPLACE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

If the record exists, it will be overwritten; if it does not yet exist, it will be created. However, using this method isn’t efficient for our case: we do not need to overwrite existing records, it’s fine just to skip them.

Method 2: using INSERT IGNORE Also very simple:

INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = 'ENSORGT00000000001',
`transcript_chrom_start` = 12345,
`transcript_chrom_end` = 12678;

Here, if the ‘ensembl_transcript_id’ is already present in the database, it will be silently skipped (ignored). (To be more precise, here’s a quote from MySQL reference manual: “If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted.”.) If the record doesn’t yet exist, it will be created.

This second method has several potential weaknesses, including non-abortion of the query in case any other problem occurs (see the manual). Thus it should be used if previously tested without the IGNORE keyword.

Method 3: using INSERT … ON DUPLICATE KEY UPDATE:

Third option is to use INSERT … ON DUPLICATE KEY UPDATE syntax, and in the UPDATE part just do nothing do some meaningless (empty) operation, like calculating 0+0 (Geoffray suggests doing the id=id assignment for the MySQL optimization engine to ignore this operation). Advantage of this method is that it only ignores duplicate key events, and still aborts on other errors.

As a final notice: this post was inspired by Xaprb. I’d also advise to consult his other post on writing flexible SQL queries.

iOS Launching Settings -> Restrictions URL Scheme

As of iOS8 you can open the built-in Settings app with:

NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
   [[UIApplication sharedApplication] openURL:url];
}

The actual URL string is @"app-settings:". I tried appending different sections to the string ("Bluetooth", "GENERAL", etc.) but seems only linking to the main Settings screen works. Post a reply if you find out otherwise.

Explain why constructor inject is better than other options

A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.

If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required or @Autowired , which is specific to Spring and is therefore not container-agnostic.

So to keep your code independent of Spring, use constructor arguments for injection.

Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired annotation at all.

What, why or when it is better to choose cshtml vs aspx?

While the syntax is certainly different between Razor (.cshtml/.vbhtml) and WebForms (.aspx/.ascx), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).

This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.

Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

If you just have a Python shell running, type:

import idlelib.PyShell
idlelib.PyShell.main()

Make EditText ReadOnly

I had no problem making EditTextPreference read-only, by using:

editTextPref.setSelectable(false);

This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html

private static final List<String> keyList;

static {
    keyList = new ArrayList<String>();
    keyList.add("field1");
    keyList.add("field2");
    keyList.add("field3");
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
        initSummary(getPreferenceScreen().getPreference(i));
    }
}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        for (int i = 0; i < pCat.getPreferenceCount(); i++) {
            initSummary(pCat.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }
}

private void updatePrefSummary(Preference p) {
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        //editTextPref.setEnabled(false); // this can be used to 'gray out' as well
        editTextPref.setSelectable(false);
        if (keyList.contains(p.getKey())) {
            p.setSummary(editTextPref.getText());
        }
    }
}

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

C++ delete vector, objects, free memory

If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time. Hope this helped. Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

How to get first and last day of the current week in JavaScript

Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.

You can use a third party date library to deal with dates. For example:

var startOfWeek = moment().startOf('week').toDate();
var endOfWeek   = moment().endOf('week').toDate();

EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)

Another popular alternative is date-fns.

Choosing the default value of an Enum type without having to change values

[DefaultValue(None)]
public enum Orientation
{
    None = -1,
    North = 0,
    East = 1,
    South = 2,
    West = 3
}

Then in the code you can use

public Orientation GetDefaultOrientation()
{
   return default(Orientation);
} 

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

How to increment datetime by custom months in python without using library

Here's my salt :

current = datetime.datetime(mydate.year, mydate.month, 1)
next_month = datetime.datetime(mydate.year + int(mydate.month / 12), ((mydate.month % 12) + 1), 1)

Quick and easy :)

Count indexes using "for" in Python

If you have some given list, and want to iterate over its items and indices, you can use enumerate():

for index, item in enumerate(my_list):
    print index, item

If you only need the indices, you can use range():

for i in range(len(my_list)):
    print i

How to run ~/.bash_profile in mac terminal

On MacOS: add source ~/.bash_profile to the end of ~/.zshrc. Then this profile will be in effect when you open zsh.

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream; 

// Create a trust manager that does not validate certificate chains like the default 

TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
        }
};

// Install the all-trusting trust manager
try 
{
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} 
catch (Exception e) 
{
    System.out.println(e);
}

Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool e.g. local testing with temporary certifcates.

Print to the same line and not a new line?

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

How to make an array of arrays in Java

there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.

Hoping this can help someone someday :)

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;


/**
 *
 * @author leBenj
 */
public class Array2DWeakRefsBuffered<T>
{
    private final WeakReference<T>[][] _array;
    private final Queue<T> _buffer;

    private final int _width;

    private final int _height;

    private final int _bufferSize;

    @SuppressWarnings( "unchecked" )
    public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
    {
        _width = w;
        _height = h;
        _bufferSize = bufferSize;
        _array = new WeakReference[_width][_height];
        _buffer = new LinkedList<T>();
    }

    /**
     * Tests the existence of the encapsulated object
     * /!\ This DOES NOT ensure that the object will be available on next call !
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     */public boolean exists( int x , int y ) throws IndexOutOfBoundsException
    {
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        }
        if( _array[x][y] != null )
        {
            T elem = _array[x][y].get();
            if( elem != null )
            {
            return true;
            }
        }
        return false;
    }

    /**
     * Gets the encapsulated object
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     * @throws NoSuchElementException
     */
    public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
    {
        T retour = null;
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        }
        if( _array[x][y] != null )
        {
            retour = _array[x][y].get();
            if( retour == null )
            {
            throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
            }
        }
        else
        {
            throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
        }
        return retour;
    }

    /**
     * Add/replace an object
     * @param o
     * @param x
     * @param y
     * @throws IndexOutOfBoundsException
     */
    public void set( T o , int x , int y ) throws IndexOutOfBoundsException
    {
        if( x >= _width || x < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
        }
        if( y >= _height || y < 0 )
        {
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
        }
        _array[x][y] = new WeakReference<T>( o );

        // store local "visible" references : avoids deletion, works in FIFO mode
        _buffer.add( o );
        if(_buffer.size() > _bufferSize)
        {
            _buffer.poll();
        }
    }

}

Example of how to use it :

// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
if(myArray.exists(3,3))
{
    System.out.println("Image at 3,3 is still in memory");
}

When should I use GC.SuppressFinalize()?

That method must be called on the Dispose method of objects that implements the IDisposable, in this way the GC wouldn't call the finalizer another time if someones calls the Dispose method.

See: GC.SuppressFinalize(Object) Method - Microsoft Docs

Run a Java Application as a Service on Linux

To run Java code as daemon (service) you can write JNI based stub.

http://jnicookbook.owsiak.org/recipe-no-022/

for a sample code that is based on JNI. In this case you daemonize the code that was started as Java and main loop is executed in C. But it is also possible to put main, daemon's, service loop inside Java.

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029

Have fun with JNI!

PHP Warning: Module already loaded in Unknown on line 0

In my case I had uncoment the ;extension=php_curl.so in php.ini, but Ubuntu was already calling this extension somewhere else.

To find this "somewhere else", on php.ini will informe. On my case: /etc/php/7.1/apache2/conf.d/20-curl.ini was the path.

So now we edit this file (terminal):

sudo nano /etc/php/7.1/apache2/conf.d/20-curl.ini

Comment the ;extension=php_curl.so

Save file and restart apache:

sudo systemctl restart apache2

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

This worked for me!

App/build.gradle

//Add this....Keep both version same

compileOptions {                                                          
    sourceCompatibility JavaVersion.VERSION_1_8 
    targetCompatibility JavaVersion.VERSION_1_8
}