Programs & Examples On #Soil

SOIL or Simple OpenGL Image Library is a lightweight image loading library for for C++ and C that is cross-platform.

Convert Python dictionary to JSON array

ensure_ascii=False really only defers the issue to the decoding stage:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

Android SharedPreferences in Fragment

It is possible to get a context from within a Fragment

Just do

public class YourFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
        // get context here
        Context context = getContext();
        // do as you please with the context


        // if you decide to go with second option
        SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
        Context context = homeViewModel.getContext();
        // do as you please with the context
        return root;
    }
}

You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

public class SomeViewModel extends AndroidViewModel {

    private MutableLiveData<ArrayList<String>> someMutableData;
    Context context;

    public SomeViewModel(Application application) {
        super(application);
        context = getApplication().getApplicationContext();
        someMutableData = new MutableLiveData<>();
        .
        .
     }

     public Context getContext() {
         return context
     }
  }

CodeIgniter - Correct way to link to another page in a view

The best way is to use the following code:

<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>

Find out if string ends with another string in C++

bool endswith(const std::string &str, const std::string &suffix)
{
    string::size_type totalSize = str.size();
    string::size_type suffixSize = suffix.size();

    if(totalSize < suffixSize) {
        return false;
    }

    return str.compare(totalSize - suffixSize, suffixSize, suffix) == 0;
}

Convert absolute path into relative path given a current directory using Bash

$ python -c "import os.path; print os.path.relpath('/foo/bar', '/foo/baz/foo')"

gives:

../../bar

allowing only alphabets in text box using java script

You can try:

 function onlyAlphabets(e, t) {
        return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;   
    }

How can I lookup a Java enum from its String value?

You can define your Enum as following code :

public enum Verbosity 
{
   BRIEF, NORMAL, FULL, ACTION_NOT_VALID;
   private int value;

   public int getValue()
   {
     return this.value;
   } 

   public static final Verbosity getVerbosityByValue(int value)
   {
     for(Verbosity verbosity : Verbosity.values())
     {
        if(verbosity.getValue() == value)
            return verbosity ;
     }

     return ACTION_NOT_VALID;
   }

   @Override
   public String toString()
   {
      return ((Integer)this.getValue()).toString();
   }
};

See following link for more clarification

How to read a line from a text file in c/c++?

In C, fgets(), and you need to know the maximum size to prevent truncation.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

ImportError: No module named mysql.connector using Python2

This worked in ubuntu 16.04 for python 2.7:

sudo pip install mysql-connector

How do I do redo (i.e. "undo undo") in Vim?

Use :earlier/:later. To redo everything you just need to do

later 9999999d

(assuming that you first edited the file at most 9999999 days ago), or, if you remember the difference between current undo state and needed one, use Nh, Nm or Ns for hours, minutes and seconds respectively. + :later N<CR> <=> Ng+ and :later Nf for file writes.

Disable Input fields in reactive form

To make a field disable and enable of reactive form angular 2+

1.To disable

  • Add [attr.disabled]="true" to input.

<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">

To enable

export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}

Enable whole form

this.formname.enable();

Enable particular field alone

this.formname.controls.firstname.enable();

same for disable, replace enable() with disable().

This Works fine. Comment for queries.

Appropriate datatype for holding percent values?

I agree with Thomas and I would choose the DECIMAL(5,4) solution at least for WPF applications.

Have a look to the MSDN Numeric Format String to know why : http://msdn.microsoft.com/en-us/library/dwhawy9k#PFormatString

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.

Then you would be able to use this in your XAML code:

DataFormatString="{}{0:P}"

Can I have multiple Xcode versions installed?

Whatever advice path you go down, make a copy of your project folder, and rename the external most one to reflect what XCode version it is being opened in. Your choice on whether you want it to update syntax or not, but the main reason for all this bovver is your storyboard will be altered just by looking. It may be resolved by the time a new reader coming across this in the future, or

Use ASP.NET MVC validation with jquery ajax?

What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel object( your action method parameter), using MVC model binding feature.

You can validate your form at client side and if everything is fine, send the data to server. The valid() method will come in handy.

$(function () {

    $("#yourSubmitButtonID").click(function (e) {

        e.preventDefault();
        var _this = $(this);
        var _form = _this.closest("form");

        var isvalid = _form .valid();  // Tells whether the form is valid

        if (isvalid)
        {           
           $.post(_form.attr("action"), _form.serialize(), function (data) {
              //check the result and do whatever you want
           })
        }

    });

});

Multiple parameters in a List. How to create without a class?

Another solution create generic list of anonymous type.

 var list = new[]
 { 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
 }.ToList();

 foreach (var item in list)
 {
    Console.WriteLine(item.Name);
 }

This also gives you intellisense support, I think in some situations its better than Tuple and Dictionary.

Regex to check whether a string contains only numbers

You could also use the following methods but be aware of their internal implementation and/or return values.

1A isNaN(+'13761123123123'); // returns true
1B isNaN(+'13761123123ABC'); // returns false

2A ~~'1.23'; // returns 1
2B ~~'1.2A'; // returns 0

For 1A & 1B the string is first type coerced using the + operator before being passed to the isNaN() function. This works because a number types that include non-numeric values return NaN. There are considerations with the isNaN()'s implementation details which is documented here. One consideration is if a boolean value is passed as isNaN(+false|true) are coerced to their numeric equivalents and thus false is returned but one might expect the function to return true since the boolean value isn't numeric in the sense of what we are testing.

For 2A & 2B it's worth noting that finding the complement of the number requires the given value in question to be within the range the values of a signed 32 bit integer which can be referenced in the spec.

My personal preference, although it could be argued to be less readable since they include the unary operator, is 1A & 1B because of the speed and conciseness.

Perf https://jsperf.com/numeric-string-test-regexvsisnan/1

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

Get loop count inside a Python FOR loop

I know rather old question but....came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

Component based game engine design

There does seem to be a lack of information on the subject. I recently implemented this system, and I found a really good GDC Powerpoint that explained the details that are often left behind quite well. That document is here: Theory and Practice of Game Object Component Architecture

In addition to that Powerpoint, there are some good resources and various blogs. PurplePwny has a good discussion and links to some other resources. Ugly Baby Studios has a bit of a discussion around the idea of how components interact with each other. Good luck!

How to use phpexcel to read data and insert into database?

In order to read data from microsoft excel 2007 by codeigniter just create a helper function excel_helper.php and add the following in:

      require_once APPPATH.'libraries/phpexcel/PHPExcel.php';
      require_once APPPATH.'libraries/phpexcel/PHPExcel/IOFactory.php';
      in controller add the following code to read spread sheet by active sheet
     //initialize php excel first  
     ob_end_clean();
     //define cachemethod
     $cacheMethod   = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
     $cacheSettings = array('memoryCacheSize' => '20MB');
     //set php excel settings
     PHPExcel_Settings::setCacheStorageMethod(
            $cacheMethod,$cacheSettings
          );

    $arrayLabel = array("A","B","C","D","E");
    //=== set object reader
    $objectReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objectReader->setReadDataOnly(true);

    $objPHPExcel = $objectReader->load("./forms/test.xlsx");
    $objWorksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');

    $starting = 1;
    $end      = 3;
    for($i = $starting;$i<=$end; $i++)
    {

       for($j=0;$j<count($arrayLabel);$j++)
       {
           //== display each cell value
           echo $objWorksheet->getCell($arrayLabel[$j].$i)->getValue();
       }
    }
     //or dump data
     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
     var_dump($sheetData);

     //see also the following link
     http://blog.mayflower.de/561-Import-and-export-data-using-PHPExcel.html
     ----------- import in another style around 5000 records ------
     $this->benchmark->mark('code_start');
    //=== change php ini limits. =====
    $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
    $cacheSettings = array( ' memoryCacheSize ' => '50MB');
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
    //==== create excel object of reader
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    //$objReader->setReadDataOnly(true);
    //==== load forms tashkil where the file exists
    $objPHPExcel = $objReader->load("./forms/5000records.xlsx");
    //==== set active sheet to read data
    $worksheet  = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');


    $highestRow         = $worksheet->getHighestRow(); // e.g. 10
    $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns          = ord($highestColumn) - 64;
    $worksheetTitle     = $worksheet->getTitle();

    echo "<br>The worksheet ".$worksheetTitle." has ";
    echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
    echo ' and ' . $highestRow . ' row.';
    echo '<br>Data: <table border="1"><tr>';
    //----- loop from all rows -----
    for ($row = 1; $row <= $highestRow; ++ $row) 
    {
        echo '<tr>';
        echo "<td>".$row."</td>";
        //--- read each excel column for each row ----
        for ($col = 0; $col < $highestColumnIndex; ++ $col) 
        {
            if($row == 1)
            {
                // show column name with the title
                 //----- get value ----
                $cell = $worksheet->getCellByColumnAndRow($col, $row);
                $val = $cell->getValue();
                //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                echo '<td>' . $val ."(".$row." X ".$col.")".'</td>';
            }
            else
            {
                if($col == 9)
                {
                    //----- get value ----
                    $cell = $worksheet->getCellByColumnAndRow($col, $row);
                    $val = $cell->getValue();
                    //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                    echo '<td>zone ' . $val .'</td>';
                }
                else if($col == 13)
                {
                    $date = PHPExcel_Shared_Date::ExcelToPHPObject($worksheet->getCellByColumnAndRow($col, $row)->getValue())->format('Y-m-d');
                    echo '<td>' .dateprovider($date,'dr') .'</td>';
                }
                else
                {
                     //----- get value ----
                    $cell = $worksheet->getCellByColumnAndRow($col, $row);
                    $val = $cell->getValue();
                    //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                    echo '<td>' . $val .'</td>';
                }
            }
        }
        echo '</tr>';
    }
    echo '</table>';
    $this->benchmark->mark('code_end');

    echo "Total time:".$this->benchmark->elapsed_time('code_start', 'code_end');     
    $this->load->view("error");

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

Using Mysql in the command line in osx - command not found?

for me the following commands worked:

$ brew install mysql

$ brew services start mysql

How can I detect window size with jQuery?

You make one div somewhere on the page and put this code:

<div id="winSize"></div>
<script>
    var WindowsSize=function(){
        var h=$(window).height(),
            w=$(window).width();
        $("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
    };
   $(document).ready(WindowsSize); 
   $(window).resize(WindowsSize); 
</script>

Here is a snippet:

_x000D_
_x000D_
var WindowsSize=function(){_x000D_
     var h=$(window).height(),_x000D_
      w=$(window).width();_x000D_
     $("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
 };_x000D_
 $(document).ready(WindowsSize); _x000D_
 $(window).resize(WindowsSize); 
_x000D_
#winSize{_x000D_
  position:fixed;_x000D_
  bottom:1%;_x000D_
  right:1%;_x000D_
  border:rgba(0,0,0,0.8) 3px solid;_x000D_
  background:rgba(0,0,0,0.6);_x000D_
  padding:5px 10px;_x000D_
  color:#fff;_x000D_
  text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
  z-index:9999_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="winSize"></div>
_x000D_
_x000D_
_x000D_

Of course, adapt it to fit your needs! ;)

@RequestParam in Spring MVC handling optional parameters

As part of Spring 4.1.1 onwards you now have full support of Java 8 Optional (original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false with Optional for your 3 params logout, name, password:

@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,   
 produces="text/xml")
public String showLoginWindow(@PathVariable("id") String id,
                              @RequestParam(value = "logout") Optional<String> logout,
                              @RequestParam("name") Optional<String> username,
                              @RequestParam("password") Optional<String> password,
                              @ModelAttribute("submitModel") SubmitModel model,
                              BindingResult errors) throws LoginException {...}

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

Eclipse: Set maximum line length for auto formatting?

Click Project->preferences. Type format into the search - you should see java->code style->formatter. Click that, then edit - finally, the line wrapping tab - its there :)

How to call servlet through a JSP page

You can submit your jsp page to servlet. For this use <form> tag.

And to redirect use:

response.sendRedirect("servleturl")

C/C++ Struct vs Class

Other that the differences in the default access (public/private), there is no difference.

However, some shops that code in C and C++ will use "class/struct" to indicate that which can be used in C and C++ (struct) and which are C++ only (class). In other words, in this style all structs must work with C and C++. This is kind of why there was a difference in the first place long ago, back when C++ was still known as "C with Classes."

Note that C unions work with C++, but not the other way around. For example

union WorksWithCppOnly{
    WorksWithCppOnly():a(0){}
    friend class FloatAccessor;
    int a;
private:
    float b;
};

And likewise

typedef union friend{
    int a;
    float b;
} class;

only works in C

Regex to match URL end-of-line or "/" character

In Ruby and Bash, you can use $ inside parentheses.

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|$)

(This solution is similar to Pete Boughton's, but preserves the usage of $, which means end of line, rather than using \z, which means end of string.)

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I just had the same problem .I solve it by adding this line:

@GeneratedValue(strategy=GenerationType.IDENTITY)

enter image description here

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

Vuejs: Event on route change

Another solution for typescript user:

import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

How to hide status bar in Android

We cannot prevent the status appearing in full screen mode in (4.4+) kitkat or above devices, so try a hack to block the status bar from expanding.

Solution is pretty big, so here's the link of SO:

StackOverflow : Hide status bar in android 4.4+ or kitkat with Fullscreen

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

Escaping single quote in PHP when inserting into MySQL

mysql_real_escape_string() or str_replace() function will help you to solve your problem.

http://phptutorial.co.in/php-echo-print/

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Both of these operations restore a set of files to a previous state and are essentially faster, safer ways of undoing mistakes than using the p4 obliterate command (and you don't need admin access to use them).

In the case of "Rollback...", this could be any number of files, even an entire depot. You can tell it to rollback to a specific revision, changelist, or label. The files are restored to the state they were in at the time of creation of that revision, changelist, or label.

In the case of "Back Out Submitted Changelist #####", the restore operation is restricted to the files that were submitted in changelist #####. Those files are restored to the state they were in before you submitted that changelist, provided no changes have been made to those files since. If subsequent changes have been made to any of those files, Perforce will tell you that those files are now out of date. You will have to sync to the head revision and then resolve the differences. This way you don't inadvertently clobber any changes that you actually want to keep.

Both operations work by essentially submitting old revisions as new revisions. When you perform a "Rollback...", you are restoring the files to the state they were in at a specific point in time, regardless of what has happened to them since. When you perform a "Back out...", you are attempting to undo the changes you made at a specific point in time, while maintaining the changes that have occurred since.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
response = client.execute(httppost, localContext);

doesn't work in 4.5 version without

cookie.setDomain(".domain.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

Make a UIButton programmatically in Swift

Swift 2.2 Xcode 7.3

Since Objective-C String Literals are deprecated now for button callback methods

let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)

func buttonClicked() {
     print("Button Clicked")
}

Swift 3 Xcode 8

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

func buttonClicked() {
    print("Button Clicked")
}

Swift 4 Xcode 9

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

@objc func buttonClicked() {
    print("Button Clicked")
}

How do I convert a PDF document to a preview image in PHP?

If you're loading the PDF from a blob this is how you get the first page instead of the last page:

$im->readimageblob($blob);
$im->setiteratorindex(0);

How do you print in Sublime Text 2

Sorry to say that there is no print function in sublimetext2, may be 3 will fix this?

Anyway there are a few plugins that are floating about, the most helpful for you might be print-to-HTML https://github.com/joelpt/sublimetext-print-to-html .

How can I URL encode a string in Excel VBA?

No, nothing built-in (until Excel 2013 - see this answer).

There are three versions of URLEncode() in this answer.

  • A function with UTF-8 support. You should probably use this one (or the alternative implementation by Tom) for compatibility with modern requirements.
  • For reference and educational purposes, two functions without UTF-8 support:
    • one found on a third party website, included as-is. (This was the first version of the answer)
    • one optimized version of that, written by me

A variant that supports UTF-8 encoding and is based on ADODB.Stream (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):

Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function

This function was found on freevbcode.com:

Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function

I've corrected a little bug that was in there.


I would use more efficient (~2× as fast) version of the above:

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function

Note that neither of these two functions support UTF-8 encoding.

Call and receive output from Python script in Java?

I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).

JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.

At first, start jpserve on Python side

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

Then call Python from JAVA side:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

Double Iteration in List Comprehension

I hope this helps someone else since a,b,x,y don't have much meaning to me! Suppose you have a text full of sentences and you want an array of words.

# Without list comprehension
list_of_words = []
for sentence in text:
    for word in sentence:
       list_of_words.append(word)
return list_of_words

I like to think of list comprehension as stretching code horizontally.

Try breaking it up into:

# List Comprehension 
[word for sentence in text for word in sentence]

Example:

>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> [word for sentence in text for word in sentence]
['Hi', 'Steve!', "What's", 'up?']

This also works for generators

>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> gen = (word for sentence in text for word in sentence)
>>> for word in gen: print(word)
Hi
Steve!
What's
up?

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Read and Write CSV files including unicode with Python 2.7

Because str in python2 is bytes actually. So if want to write unicode to csv, you must encode unicode to str using utf-8 encoding.

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

Use class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds):

  • py2
    • The csvfile: open(fp, 'w')
    • pass key and value in bytes which are encoded with utf-8
      • writer.writerow({py2_unicode_to_str(k): py2_unicode_to_str(v) for k,v in row.items()})
  • py3
    • The csvfile: open(fp, 'w')
    • pass normal dict contains str as row to writer.writerow(row)

Finally code

import sys

is_py2 = sys.version_info[0] == 2

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

with open('file.csv', 'w') as f:
    if is_py2:
        data = {u'Python??': u'Python??', u'Python??2': u'Python??2'}

        # just one more line to handle this
        data = {py2_unicode_to_str(k): py2_unicode_to_str(v) for k, v in data.items()}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)
    else:
        data = {'Python??': 'Python??', 'Python??2': 'Python??2'}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)

Conclusion

In python3, just use the unicode str.

In python2, use unicode handle text, use str when I/O occurs.

How to delete file from public folder in laravel 5.1

the easiest way for you to delete the image of the news is using the model event like below and the model delete the image if the news deleted

at first you should import this in top of the model class use Illuminate\Support\Facades\Storage after that in the model class News you should do this

public static function boot(){
    parent::boot();

    static::deleting(function ($news) {
          Storage::disk('public')->delete("{$news->image}");
    })
}

or you can delete the image in your controller with this command

Storage::disk('public')->delete("images/news/{$news->file_name}");

but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name

INNER JOIN vs LEFT JOIN performance in SQL Server

There is one important scenario that can lead to an outer join being faster than an inner join that has not been discussed yet.

When using an outer join, the optimizer is always free to drop the outer joined table from the execution plan if the join columns are the PK of the outer table, and none of the outer table columns are referenced outside of the outer join itself. For example SELECT A.* FROM A LEFT OUTER JOIN B ON A.KEY=B.KEY and B.KEY is the PK for B. Both Oracle (I believe I was using release 10) and Sql Server (I used 2008 R2) prune table B from the execution plan.

The same is not necessarily true for an inner join: SELECT A.* FROM A INNER JOIN B ON A.KEY=B.KEY may or may not require B in the execution plan depending on what constraints exist.

If A.KEY is a nullable foreign key referencing B.KEY, then the optimizer cannot drop B from the plan because it must confirm that a B row exists for every A row.

If A.KEY is a mandatory foreign key referencing B.KEY, then the optimizer is free to drop B from the plan because the constraints guarantee the existence of the row. But just because the optimizer can drop the table from the plan, doesn't mean it will. SQL Server 2008 R2 does NOT drop B from the plan. Oracle 10 DOES drop B from the plan. It is easy to see how the outer join will out-perform the inner join on SQL Server in this case.

This is a trivial example, and not practical for a stand-alone query. Why join to a table if you don't need to?

But this could be a very important design consideration when designing views. Frequently a "do-everything" view is built that joins everything a user might need related to a central table. (Especially if there are naive users doing ad-hoc queries that do not understand the relational model) The view may include all the relevent columns from many tables. But the end users might only access columns from a subset of the tables within the view. If the tables are joined with outer joins, then the optimizer can (and does) drop the un-needed tables from the plan.

It is critical to make sure that the view using outer joins gives the correct results. As Aaronaught has said - you cannot blindly substitute OUTER JOIN for INNER JOIN and expect the same results. But there are times when it can be useful for performance reasons when using views.

One last note - I haven't tested the impact on performance in light of the above, but in theory it seems you should be able to safely replace an INNER JOIN with an OUTER JOIN if you also add the condition <FOREIGN_KEY> IS NOT NULL to the where clause.

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

HTTP requests and JSON parsing in Python

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

How do I remove a CLOSE_WAIT socket connection

I'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.

To see open connections, you may use:

sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT

As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).

To change them, you need to edit /etc/sysctl.conf.

Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`

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

Thats an if/else statement equilavent to

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

Div table-cell vertical align not working

Sometime floats brake the vertical align, is better to avoid them.

How to create a String with carriage returns?

Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");

When to use Hadoop, HBase, Hive and Pig?

Consider that you work with RDBMS and have to select what to use - full table scans, or index access - but only one of them.
If you select full table scan - use hive. If index access - HBase.

How to Use UTF-8 Collation in SQL Server database?

Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp, BULK_INSERT, and OPENROWSET.

Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.

jQuery: How can I create a simple overlay?

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

django MultiValueDictKeyError error, how do I deal with it

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”

In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.

The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

You can handle this error by putting :

is_private = request.POST.get('is_private', False);

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Restrictions

You can ask the system catalog pg_database - accessible from any database in the same database cluster. The tricky part is that CREATE DATABASE can only be executed as a single statement. The manual:

CREATE DATABASE cannot be executed inside a transaction block.

So it cannot be run directly inside a function or DO statement, where it would be inside a transaction block implicitly.

(SQL procedures, introduced with Postgres 11, cannot help with this either.)

Workaround from within psql

You can work around it from within psql by executing the DDL statement conditionally:

SELECT 'CREATE DATABASE mydb'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec

The manual:

\gexec

Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.

Workaround from the shell

With \gexec you only need to call psql once:

echo "SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec" | psql

You may need more psql options for your connection; role, port, password, ... See:

The same cannot be called with psql -c "SELECT ...\gexec" since \gexec is a psql meta-command and the -c option expects a single command for which the manual states:

command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a -c option.

Workaround from within Postgres transaction

You could use a dblink connection back to the current database, which runs outside of the transaction block. Effects can therefore also not be rolled back.

Install the additional module dblink for this (once per database):

Then:

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM pg_database WHERE datname = 'mydb') THEN
      RAISE NOTICE 'Database already exists';  -- optional
   ELSE
      PERFORM dblink_exec('dbname=' || current_database()  -- current db
                        , 'CREATE DATABASE mydb');
   END IF;
END
$do$;

Again, you may need more psql options for the connection. See Ortwin's added answer:

Detailed explanation for dblink:

You can make this a function for repeated use.

How to discard uncommitted changes in SourceTree?

Ok so in Windows sourcetree that is simple, on macOS I looked as well for a while..

Click Command + Shift + R while in source tree a hidden popup will be shown that will let you discard individual files OR ALL! Why is this hidden? We will never know.. but it works!

enter image description here

Remove attribute "checked" of checkbox

Both of these should work:

$("#captureImage").prop('checked', false);

AND/OR

$("#captureImage").removeAttr('checked');

... you can try both together.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Convert String to SecureString

You can follow this:

string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();

Test if a property is available on a dynamic variable

If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...

public class DynamicValue<T>
{
    internal DynamicValue(T value, bool exists)
    {
         Value = value;
         Exists = exists;
    }

    T Value { get; private set; }
    bool Exists { get; private set; }
}

Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists on every property access and then hit Value if it does with value being default(T) (and irrelevant) if it doesn't.

That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

How to get Current Directory?

I guess, that the easiest way to locate the current directory is to cut it from command line args.

#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
  std::string cur_dir(argv[0]);
  int pos = cur_dir.find_last_of("/\\");

  std::cout << "path: " << cur_dir.substr(0, pos) << std::endl;
  std::cout << "file: " << cur_dir.substr(pos+1) << std::endl;
  return 0;
}

You may know that every program gets its executable name as first command line argument. So you can use this.

How can I recursively find all files in current and subfolders based on wildcard matching?

Use

find path/to/dir -name "*.ext1" -o -name "*.ext2"

Explanation

  1. The first parameter is the directory you want to search.
  2. By default find does recursion.
  3. The -o stands for -or. So above means search for this wildcard OR this one. If you have only one pattern then no need for -o.
  4. The quotes around the wildcard pattern are required.

How to pass extra variables in URL with WordPress

Since this is a frequently visited post i thought to post my solution in case it helps anyone. In WordPress along with using query vars you can change permalinks too like this

www.example.com?c=123 to www.example.com/c/123

For this you have to add these lines of code in functions.php or your plugin base file.

From shankhan's anwer

add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{   
    $vars[] = 'c'; // c is the name of variable you want to add       
    return $vars;
}

And additionally this snipped to add custom rewriting rules.

function custom_rewrite_basic() 
{
    add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

For the case where you need to add rewrite rules for a specifc page you can use that page slug to write a rewrite rule for that specific page. Like in the question OP has asked about

www.example.com/news?c=123 to www.example.com/news/123

We can change it to the desired behaviour by adding a little modification to our previous function.

function custom_rewrite_basic() 
{
    add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

Hoping that it becomes useful for someone.

How do I redirect in expressjs while passing some context?

 app.get('/category', function(req, res) {
  var string = query
  res.redirect('/?valid=' + string);
});

in the ejs you can directly use valid:

<% var k = valid %>

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

What is the difference between pull and clone in git?

Hmm, what's missing to see the remote branch "4.2" when I pull, as I do when I clone? Something's clearly not identical.

tmp$  mkdir some_repo

tmp$  cd some_repo

some_repo$  git init
Initialized empty Git repository in /tmp/some_repo/.git/

some_repo$  git pull https://github.ourplace.net/babelfish/some_repo.git
  :
From https://github.ourplace.net/babelfish/some_repo
 * branch            HEAD       -> FETCH_HEAD

some_repo$  git branch
* master

vs

tmp$  rm -rf some_repo

tmp$  git clone https://github.ourplace.net/babelfish/some_repo.git
Cloning into 'some_repo'...
  :
Checking connectivity... done.

tmp$  cd some_repo

some_repo$  git branch
* 4.2

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

Can I install/update WordPress plugins without providing FTP access?

You can get it very easily by typing the following command on command promt

sudo chown -R www-data:www-data your_folder_name

or copy & paste the following code in your wp-config.php file.

define('FS_METHOD', 'direct');

Where "your_folder_name" is the folder where your WordPress is installed inside this folder.

How can I count the number of elements with same class?

With jQuery you can use

$('#main-div .specific-class').length

otherwise in VanillaJS (from IE8 included) you may use

document.querySelectorAll('#main-div .specific-class').length;

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

How good is Java's UUID.randomUUID?

I play at lottery last year, and I've never won .... but it seems that there lottery has winners ...

doc : http://tools.ietf.org/html/rfc4122

Type 1 : not implemented. collision are possible if the uuid is generated at the same moment. impl can be artificially a-synchronize in order to bypass this problem.

Type 2 : never see a implementation.

Type 3 : md5 hash : collision possible (128 bits-2 technical bytes)

Type 4 : random : collision possible (as lottery). note that the jdk6 impl dont use a "true" secure random because the PRNG algorithm is not choose by developer and you can force system to use a "poor" PRNG algo. So your UUID is predictable.

Type 5 : sha1 hash : not implemented : collision possible (160 bit-2 technical bytes)

Inline labels in Matplotlib

@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:

  • it does not work in all cases
  • it requires a fair amount of extra code
  • it may vary considerably from one plot to the next

A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:

from matplotlib import pyplot as plt

for i, (x, y) in enumerate(samples):
    plt.plot(x, y)
    plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))

A variant would be to use ax.annotate.

twitter bootstrap text-center when in xs mode

@media (max-width: 767px) {
    footer .text-right, 
    footer .text-left {
        text-align: center;
    } 
}

I updated @loddn's answer, making two changes

  • max-width of xs screens in bootstrap is 767px (768px is the start of sm screens)
  • (this one is a matter of preference) I used footer instead of col-* so that if the column widths change, the CSS doesn't need to be updated.

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

Simulating Key Press C#

The easiest way to send (simulate) KeyStrokes to any window is to use the SendKeys.Send method of .NET Framework.

Checkout this very intuitive MSDN article http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx


Particularly for your case, if your browser window is in focus, sending F5 would just involve the following line of code:

SendKeys.Send("{F5}");

How to overlay image with color in CSS?

You should use rgba for overlaying your element with photos.rgba is a way to declare a color in CSS that includes alpha transparency support. you can use .row as an overlayer like this:

#header {
    background: url(../img/bg.jpg) 0 0 no-repeat fixed;
    height: 100%;
    overflow: hidden;
    color: #FFFFFF
 }

.row{
    background: rgba(39,62,84,0.82);
    overflow: hidden;
    height: 100%;
    z-index: 2;
}

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

When is TCP option SO_LINGER (0) required?

Whether you can remove the linger in your code safely or not depends on the type of your application: is it a „client“ (opening TCP connections and actively closing it first) or is it a „server“ (listening to a TCP open and closing it after the other side initiated the close)?

If your application has the flavor of a „client“ (closing first) AND you initiate & close a huge number of connections to different servers (e.g. when your app is a monitoring app supervising the reachability of a huge number of different servers) your app has the problem that all your client connections are stuck in TIME_WAIT state. Then, I would recommend to shorten the timeout to a smaller value than the default to still shutdown gracefully but free up the client connections resources earlier. I would not set the timeout to 0, as 0 does not shutdown gracefully with FIN but abortive with RST.

If your application has the flavor of a „client“ and has to fetch a huge amount of small files from the same server, you should not initiate a new TCP connection per file and end up in a huge amount of client connections in TIME_WAIT, but keep the connection open and fetch all data over the same connection. Linger option can and should be removed.

If your application is a „server“ (close second as reaction to peer‘s close), on close() your connection is shutdown gracefully and resources are freed up as you don‘t enter TIME_WAIT state. Linger should not be used. But if your sever app has a supervisory process detecting inactive open connections idleing for a long time („long“ is to be defined) you can shutdown this inactive connection from your side - see it as kind of error handling - with an abortive shutdown. This is done by setting linger timeout to 0. close() will then send a RST to the client, telling him that you are angry :-)

Git merge errors

It's worth understanding what those error messages mean - needs merge and error: you need to resolve your current index first indicate that a merge failed, and that there are conflicts in those files. If you've decided that whatever merge you were trying to do was a bad idea after all, you can put things back to normal with:

git reset --merge

However, otherwise you should resolve those merge conflicts, as described in the git manual.


Once you've dealt with that by either technique you should be able to checkout the 9-sign-in-out branch. The problem with just renaming your 9-sign-in-out to master, as suggested in wRAR's answer is that if you've shared your previous master branch with anyone, this will create problems for them, since if the history of the two branches diverged, you'll be publishing rewritten history.

Essentially what you want to do is to merge your topic branch 9-sign-in-out into master but exactly keep the versions of the files in the topic branch. You could do this with the following steps:

# Switch to the topic branch:
git checkout 9-sign-in-out

# Create a merge commit, which looks as if it's merging in from master, but is
# actually discarding everything from the master branch and keeping everything
# from 9-sign-in-out:
git merge -s ours master

# Switch back to the master branch:
git checkout master

# Merge the topic branch into master - this should now be a fast-forward
# that leaves you with master exactly as 9-sign-in-out was:
git merge 9-sign-in-out

Reverse each individual word of "Hello World" string with Java

You need to do this on each word after you split into an array of words.

public String reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
    return String.valueOf(chs);
}

Difference between webdriver.Dispose(), .Close() and .Quit()

Close() - It is used to close the browser or page currently which is having the focus.

Quit() - It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).

Dispose() - I am not aware of this method.

Concatenate two PySpark dataframes

df_concat = df_1.union(df_2)

The dataframes may need to have identical columns, in which case you can use withColumn() to create normal_1 and normal_2

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

Two models in one view in ASP MVC 3

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

_x000D_
_x000D_
List<tblproject> Plist = new List<tblproject>();_x000D_
            Plist = ps.getmanagerproject(c, id);_x000D_
_x000D_
            ViewBag.projectList = Plist.Select(x => new SelectListItem_x000D_
            {_x000D_
                Value = x.ProjectId.ToString(),_x000D_
                Text = x.Title_x000D_
            });
_x000D_
_x000D_
_x000D_

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

Get names of all keys in the collection

You could do this with MapReduce:

mr = db.runCommand({
  "mapreduce" : "my_collection",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "my_collection" + "_keys"
})

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

@Html.DropDownListFor how to set default value

SelectListItem has a Selected property. If you are creating the SelectListItems dynamically, you can just set the one you want as Selected = true and it will then be the default.

SelectListItem defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Default Item",
   Selected = true
};

For..In loops in JavaScript - key value pairs

You can use the for..in for that.

for (var key in data)
{
    var value = data[key];
}

Switch to another Git tag

As of Git v2.23.0 (August 2019), git switch is preferred over git checkout when you’re simply switching branches/tags. I’m guessing they did this since git checkout had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch, and git restore, to separate those concerns. I would predict at some point in the future, git checkout will be deprecated.

To switch to a normal branch, use git switch <branch-name>. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>, where <commitish> is the tag name or commit number.

The --detach option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>.

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Using a remote repository with non-standard port

Try this

git clone ssh://[email protected]:11111/home/git/repo.git

What are XAND and XOR

First comes the logic, then the name, possibly patterned on previous naming.

Thus 0+0=0; 0+1=1; 1+0=1; 1+1=1 - for some reason this is called OR.

Then 0-0=0; 0-1=1; 1-0=1; 1-1=0 - it looks like OR except ... let's call it XOR.

Also 0*0=0; 0*1=0; 1*0=0; 1*1=1 - for some reason this is called AND.

Then 0~0=0; 0~1=0; 1~0=0; 1~1=0 - it looks like AND except ... let's call it XAND.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)

turning it back to 1.0.7 solved the problem instantly.

have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.

anyway, this problem is fixed when using AngularJS vs 1.0.7.

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

I've been looking to answer this exact question and from my research, DiryBoy's response seems to be accurate.

I found the compact.exe program compresses files but not to create a highly compressed file (or set of files). It is similar to the option you get when right clicking on a drive letter or partition in Windows. You get the option to do cleanup (remove temp files, etc) as well as compress files. The compressed files are still accessible but are just compressed to create space on a drive that is low on space.

I also found compress.exe which I did happen to have on my computer. It isn't natively on most windows machines and is part of the 2003 resource kit. It does make a zipped file of sorts but it is really more similar to files from a windows setup disk (has the underscore as the last character of the file extension or name). And the extract.exe command extracts those files.

However, the mantra is, if it can be done natively via the GUI then there is likely a way to do it via batch, .vbs, or some other type of script within the command line. Since windows has had the 'send to' option to create a zip file, I knew there had to be a way to do it via command line and I found some options.

Here is a great link that shows how to zip a file using windows native commands.

https://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili

I tested it with a directory containing multiple nested files and folders and it worked perfectly. Just follow the format of the command line.

There is also a way to unzip the files via command line which I found as well. One way, just brings open an explorer window showing what the content of the zipped file is. Some of these also use Java which isn't necessarily native to windows but is so common that it nearly seems so.

https://superuser.com/questions/149489/does-windows-7-have-unzip-at-the-command-line-installed-by-default

How to unzip a file using the command line?

How do I compare two Integers?

I would go with x.equals(y) because that's consistent way to check equality for all classes.

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

How to make sure you don't get WCF Faulted state exception?

If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.

What is the difference between float and double?

The size of the numbers involved in the float-point calculations is not the most relevant thing. It's the calculation that is being performed that is relevant.

In essence, if you're performing a calculation and the result is an irrational number or recurring decimal, then there will be rounding errors when that number is squashed into the finite size data structure you're using. Since double is twice the size of float then the rounding error will be a lot smaller.

The tests may specifically use numbers which would cause this kind of error and therefore tested that you'd used the appropriate type in your code.

Disabling Controls in Bootstrap

No, Bootstrap does not introduce special considerations for disabling a drop-down.

<select id="xxx" name="xxx" class="input-medium" disabled>

or

<select id="xxx" name="xxx" class="input-medium" disabled="disabled">

will work. I prefer to give attributes values (as in the second form; in XHTML, attributes must have a value), but the HTML spec says:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

(from http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#boolean-attribute)

The key differences between read-only and disabled:*

The Disabled attribute

  • Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to form check boxes that are not checked.)
  • Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer 5.5 is particularly nasty about this.
  • Disabled form elements do not receive focus.
  • Disabled form elements are skipped in tabbing navigation.

The Read Only Attribute

  • Not all form elements have a readonly attribute. Most notable, the <SELECT>, <OPTION>, and <BUTTON> elements do not have readonly attributes (although thy both have disabled attributes)
  • Browsers provide no default overridden visual feedback that the form element is read only
  • Form elements with the readonly attribute set will get passed to the form processor.
  • Read only form elements can receive the focus
  • Read only form elements are included in tabbed navigation.

*-blatant plagiarism from http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/

HTTP POST with Json on Body - Flutter/Dart

this works for me

String body = json.encode(data);

http.Response response = await http.post(
  url: 'https://example.com',
  headers: {"Content-Type": "application/json"},
  body: body,
);

Reading specific XML elements from XML file

You could use linq to xml.

    var xmlStr = File.ReadAllText("fileName.xml");


    var str = XElement.Parse(xmlStr);

    var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();

    Console.WriteLine(result);

Selenium WebDriver How to Resolve Stale Element Reference Exception?

I have solved this problem with the following code.

public WebElement waitForElement(final By findBy, final int waitTime) {
    Wait<AppiumDriver> wait = new FluentWait<>((AppiumDriver) driver)
            .withTimeout(waitTime, TimeUnit.SECONDS)
            .pollingEvery(POLL_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class,StaleElementReferenceException.class);

    WebElement webElement = wait.until(new Function<AppiumDriver, WebElement>() {
        @Override
        public WebElement apply(AppiumDriver driver) {
            System.out.println("Trying to find element " + findBy.toString());                
            WebElement element = driver.findElement(findBy);
            return element;
        }
    });
    return webElement;
}

Python/Json:Expecting property name enclosed in double quotes

I've checked your JSON data

{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}

in http://jsonlint.com/ and the results were:

Error: Parse error on line 1:
{   'http://example.org/
--^
Expecting 'STRING', '}', got 'undefined'

modifying it to the following string solve the JSON error:

{
    "http://example.org/about": {
        "http://purl.org/dc/terms/title": [{
            "type": "literal",
            "value": "Anna's Homepage"
        }]
    }
}

ReactJS and images in public folder

the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

How to pass data from 2nd activity to 1st activity when pressed back? - android

Start Activity2 with startActivityForResult and use setResult method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult for updating TextView with EditText data from Activity2.

For example:

In Activity1, start Activity2 as:

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);

In Activity2, use setResult for sending data back:

Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);        
finish();

And in Activity1, receive data with onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK) {
             String strEditText = data.getStringExtra("editTextValue");
         }     
    }
} 

If you can, also use SharedPreferences for sharing data between Activities.

How to make an Android Spinner with initial text "Select One"?

XML file:

<Spinner android:id="@+id/locationSpinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:prompt="@string/select_location" />

Activity:

private Spinner featuresSelection;
private ArrayAdapter<CharSequence> featuresAdapter;
private List<CharSequence> featuresList;

onCreate:

featuresList = new ArrayList<CharSequence>();
featuresAdapter = new ArrayAdapter<CharSequence>(this,
  android.R.layout.simple_spinner_item, featuresList);
featuresAdapter.setDropDownViewResource(
  android.R.layout.simple_spinner_dropdown_item);
featuresSelection = ((Spinner) yourActivity.this
  .findViewById(R.id.locationSpinner));
featuresSelection.setAdapter(featuresAdapter);
featuresSelection.setOnItemSelectedListener(
  new MyOnItemSelectedListener());

Some function (add things to the adapter programmatically)>

featuresAdapter.add("some string");

Now you have an empty spinner and you can write code to not open the dialog if empty. Or they can press back. But you also populate it with a function or another list during run time.

How to convert a HTMLElement to a string

There's a tagName property, and a attributes property as well:

var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
    var attrib = element.attributes[i];
    openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);

See also How to iterate through all attributes in an HTML element? (I did!)

To get the contents between the open and close tags you could probably use innerHTML if you don't want to iterate over all the child elements...

alert(element.innerHTML);

... and then get the close tag again with tagName.

var closeTag = "</"+element.tagName+">";
alert(closeTag);

Command to get time in milliseconds

Here is a somehow portable hack for Linux for getting time in milliseconds:

#!/bin/sh
read up rest </proc/uptime; t1="${up%.*}${up#*.}"
sleep 3    # your command
read up rest </proc/uptime; t2="${up%.*}${up#*.}"

millisec=$(( 10*(t2-t1) ))
echo $millisec

The output is:

3010

This is a very cheap operation, which works with shell internals and procfs.

How to perform runtime type checking in Dart?

As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.

Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:

import 'dart:mirrors'; 

getTypeName(dynamic obj) {
  return reflect(obj).type.reflectedType.toString();
}

void main() {
  var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
  if (val is String) {
    print("The value is a String, but I needed "
        "to check with an explicit condition.");
  }
  var typeName = getTypeName(val);
  print("\nThe mirrored type of the value is $typeName.");
}

Passing data to a jQuery UI Dialog

I have now tried your suggestions and found that it kinda works,

  1. The dialog div is alsways written out in plaintext
  2. With the $.post version it actually works in terms that the controller gets called and actually cancels the booking, but the dialog stays open and page doesn't refresh. With the get version window.location = h.ref works great.

Se my "new" script below:

$('a.cancel').click(function() {
        var a = this;               
        $("#dialog").dialog({
            autoOpen: false,
            buttons: {
                "Ja": function() {
                    $.post(a.href);                     
                },
                "Nej": function() { $(this).dialog("close"); }
            },
            modal: true,
            overlay: {
                opacity: 0.5,

            background: "black"
        }
    });
    $("#dialog").dialog('open');
    return false;
});

});

Any clues?

oh and my Action link now looks like this:

<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new  { @class = "cancel" })%>

How to capture and save an image using custom camera in Android?

 showbookimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // create intent with ACTION_IMAGE_CAPTURE action
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                /**
 Here REQUEST_IMAGE is the unique integer value you can pass it any integer
 **/
                // start camera activity
                startActivityForResult(intent, TAKE_PICTURE);
            }

            }

        );

then u can now give the image a file name as follows and then convert it into bitmap and later on to file

 private void createImageFile(Bitmap bitmap) throws IOException {
        // Create an image file name
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        FileOutputStream stream = new FileOutputStream(image);
        stream.write(bytes.toByteArray());
        stream.close();
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        fileUri = image.getAbsolutePath();
        Picasso.with(getActivity()).load(image).into(showbookimage);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
            // get bundle
            Bundle extras = intent.getExtras();
            // get
            bitMap = (Bitmap) extras.get("data");
//            showbookimage.setImageBitmap(bitMap);
            try {
                createImageFile(bitMap);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

use picasso for images to display rather fast

what is the use of fflush(stdin) in c programming

it clears stdin buffer before reading. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

Note: This is Linux-specific, using fflush() on input streams is undefined by the standard, however, most implementations behave the same as in Linux.

How to submit an HTML form on loading the page?

You can try also using below script

<html>
<head>
<script>
function load()
{
document.frm1.submit()
}
</script>
</head>

<body onload="load()">
<form action="http://www.google.com" id="frm1" name="frm1">
<input type="text" value="" />
</form>
</body>
</html> 

Calculate a MD5 hash from a string

StringBuilder sb= new StringBuilder();
for (int i = 0; i < tmpHash.Length; i++)
{
   sb.Append(tmpHash[i].ToString("x2"));
}

SQL, How to convert VARCHAR to bigint?

an alternative would be to do something like:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

Hover and Active only when not disabled

In sass (scss):

 button {
  color: white;
  cursor: pointer;
  border-radius: 4px;

  &:disabled{
    opacity: 0.4;

    &:hover{
      opacity: 0.4;  //this is what you want
    }
  }

  &:hover{
    opacity: 0.9;
  }
}

How do I expand the output display to see more columns of a pandas DataFrame?

You can use this custom function for displaying things for pandas Dataframe.

def display_all(df):     # for any Dataframe df
   with pd.option_context('display.max_rows',1000): # change number of rows accordingly
      with pd.option_context('display.max_columns',1000): # change number of columns accordingly
          display(df)

display_all(df.head()) # pass this function to your dataframe and Voila!

You don't have use pd.set_option for whole notebook just use for single cell.

Is it possible to log all HTTP request headers with Apache?

Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats

As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Disable/turn off inherited CSS3 transitions

The use of transition: none seems to be supported (with a specific adjustment for Opera) given the following HTML:

<a href="#" class="transition">Content</a>
<a href="#" class="transition">Content</a>
<a href="#" class="noTransition">Content</a>
<a href="#" class="transition">Content</a>

...and CSS:

a {
    color: #f90;
    -webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;  
    -moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    -o-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    transition:color 0.8s ease-in, background-color 0.1s ease-in; 
}
a:hover {
    color: #f00;
    -webkit-transition:color 0.8s ease-in, background-color 0.1s ease-in ;  
    -moz-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    -o-transition:color 0.8s ease-in, background-color 0.1s ease-in;  
    transition:color 0.8s ease-in, background-color 0.1s ease-in; 
}
a.noTransition {
    -moz-transition: none;
    -webkit-transition: none;
    -o-transition: color 0 ease-in;
    transition: none;
}

JS Fiddle demo.

Tested with Chromium 12, Opera 11.x and Firefox 5 on Ubuntu 11.04.

The specific adaptation to Opera is the use of -o-transition: color 0 ease-in; which targets the same property as specified in the other transition rules, but sets the transition time to 0, which effectively prevents the transition from being noticeable. The use of the a.noTransition selector is simply to provide a specific selector for the elements without transitions.


Edited to note that @Frédéric Hamidi's answer, using all (for Opera, at least) is far more concise than listing out each individual property-name that you don't want to have transition.

Updated JS Fiddle demo, showing the use of all in Opera: -o-transition: all 0 none, following self-deletion of @Frédéric's answer.

How can I issue a single command from the command line through sql plus?

I'm able to run an SQL query by piping it to SQL*Plus:

@echo select count(*) from table; | sqlplus username/password@database

Give

@echo execute some_procedure | sqlplus username/password@databasename

a try.

window.onload vs <body onload=""/>

'so many subjective answers to an objective question. "Unobtrusive" JavaScript is superstition like the old rule to never use gotos. Write code in a way that helps you reliably accomplish your goal, not according to someone's trendy religious beliefs.

Anyone who finds:

 <body onload="body_onload();">

to be overly distracting is overly pretentious and doesn't have their priorities straight.

I normally put my JavaScript code in a separate .js file, but I find nothing cumbersome about hooking event handlers in HTML, which is valid HTML by the way.

how to create 100% vertical line in css

I use this css positioning for most of my vertical elements:

<div class="vertical-line" style="height: 250px;
width: 1px;
background-color: #81F781;
margin-left: 0px;
margin-top: -100px;
postion: absolute;
border-radius: 2px;">
</div>

Change the height and width to fit the page, or to make a horizontal line swap the height to width:

<div class="vertical-line" style="height: 250px;
width: 1px;

<div class="vertical-line" style="width: 250px;
height: 1px;   

instead of a standard html line.

What is an AssertionError? In which case should I throw it from my own code?

An assertion Error is thrown when say "You have written a code that should not execute at all costs because according to you logic it should not happen. BUT if it happens then throw AssertionError. And you don't catch it." In such a case you throw an Assertion error.

new IllegalStateException("Must not instantiate an element of this class")' // Is an Exception not error.

Note: Assertion Error comes under java.lang.Error And Errors not meant to be caught.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

__proto__ VS. prototype in JavaScript

There is only one object that is used for protypal chaining. This object obviously has a name and a value: __proto__ is its name, and prototype is its value. That's all.

to make it even easier to grasp, look at the diagram on the top of this post (Diagram by dmitry soshnikov), you'll never find __proto__ points to something else other than prototype as its value.

The gist is this: __proto__ is the name that references the prototypal object, and prototype is the actual prototypal object.

It's like saying:

let x = {name: 'john'};

x is the object name (pointer), and {name: 'john'} is the actual object (data value).

NOTE: this just a massively simplified hint on how they are related on a high level.

Update: Here is a simple concrete javascript example for better illustration:

let x = new String("testing") // Or any other javascript object you want to create

Object.getPrototypeOf(x) === x.__proto__; // true

This means that when Object.getPrototypeOf(x) gets us the actual value of x (which is its prototype), is exactly what the __proto__ of x is pointing to. Therefore __proto__ is indeed pointing to the prototype of x. Thus __proto__ references x (pointer of x), and prototype is the value of x (its prototype).

I hope it's a bit clear now.

Load jQuery with Javascript and use jQuery

Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:

I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:

<title>jQuery+RequireJS Sample Page</title>
   <script src="scripts/require.js"></script>
   <script>
   require({
       baseUrl: 'scripts',
       paths: {
           jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
       },
       priority: ['jquery']
    }, ['main']);
    </script>

SQL Server : Arithmetic overflow error converting expression to data type int

SELECT                          
    DATEPART(YEAR, dateTimeStamp) AS [Year]                         
    , DATEPART(MONTH, dateTimeStamp) AS [Month]                         
    , COUNT(*) AS NumStreams                        
    , [platform] AS [Platform]                      
    , deliverableName AS [Deliverable Name]                     
    , SUM(billableDuration) AS NumSecondsDelivered

Assuming that your quoted text is the exact text, one of these columns can't do the mathematical calculations that you want. Double click on the error and it will highlight the line that's causing the problems (if it's different than what's posted, it may not be up there); I tested your code with the variables and there was no problem, meaning that one of these columns (which we don't know more specific information about) is creating this error.

One of your expressions needs to be casted/converted to an int in order for this to go through, which is the meaning of Arithmetic overflow error converting expression to data type int.

What is a handle in C++?

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.

For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).

EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.

laravel throwing MethodNotAllowedHttpException

Laravel sometimes does not support {!! Form::open(['url' => 'posts/store']) !!} for security reasons. That's why the error has happened. You can solve this error by simply replacing the below code

{!! Form::open(array('route' => 'posts.store')) !!}




Error Code {!! Form::open(['url' => 'posts/store']) !!}

Correct Code {!! Form::open(array('route' => 'posts.store')) !!}

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

How to use Fiddler to monitor WCF service

You need to add this in your web.config

<system.net>
  <defaultProxy>
    <proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />
  </defaultProxy>
</system.net>
  1. then Start Fiddler on the WEBSERVER machine.
  2. Click Tools | Fiddler Options => Connections => adjust the port as 8888.(allow remote if you need that)
  3. Ok, then from file menu, capture the traffic.

That's all, but don't forget to remove the web.config lines after closing the fiddler, because if you don't it will make an error.

Reference : http://fiddler2.com/documentation/Configure-Fiddler/Tasks/UseFiddlerAsReverseProxy

Build error, This project references NuGet

I also had this error I took this part of code from .csproj file:

 <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
      <PropertyGroup>
        <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
      </PropertyGroup>
      <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
    </Target>

Simplest Way to Test ODBC on WIndows

Make a file SOMEFILENAME.udl then double click on it and set it up as an ODBC connection object, username, pwd, target server

How to detect if a browser is Chrome using jQuery?

This question was already discussed here: JavaScript: How to find out if the user browser is Chrome?

Please try this:

var isChromium = window.chrome;
if(isChromium){
    // is Google chrome 
} else {
    // not Google chrome 
}

But a more complete and accurate answer would be this since IE11, IE Edge, and Opera will also return true for window.chrome

So use the below:

// please note, 
// that IE11 now returns undefined again for window.chrome
// and new Opera 30 outputs true for window.chrome
// but needs to check if window.opr is not undefined
// and new IE Edge outputs to true now for window.chrome
// and if not iOS Chrome check
// so use the below updated condition
var isChromium = window.chrome;
var winNav = window.navigator;
var vendorName = winNav.vendor;
var isOpera = typeof window.opr !== "undefined";
var isIEedge = winNav.userAgent.indexOf("Edge") > -1;
var isIOSChrome = winNav.userAgent.match("CriOS");

if (isIOSChrome) {
   // is Google Chrome on IOS
} else if(
  isChromium !== null &&
  typeof isChromium !== "undefined" &&
  vendorName === "Google Inc." &&
  isOpera === false &&
  isIEedge === false
) {
   // is Google Chrome
} else { 
   // not Google Chrome 
}

Above posts advise to use jQuery.browser. But the jQuery API recommends against using this method.. (see DOCS in API). And states its functionality may be moved to a team-supported plugin in a future release of jQuery.

The jQuery API recommends to use jQuery.support.

The reason being is that 'jQuery.browser' uses the user agent which can be spoofed and it is actually deprecated in later versions of jQuery. If you really want to use $.browser.. Here is the link to the standalone jQuery plugin, since it has been removed from jQuery version 1.9.1. https://github.com/gabceb/jquery-browser-plugin

It's better to use feature object detection instead of browser detection.

Also if you use the Google Chrome inspector and go to the console tab. Type 'window' and press enter. Then you be able to view the DOM properties for the 'window object'. When you collapse the object you can view all the properties, including the 'chrome' property.

I hope this helps, even though the question was how to do with with jQuery. But sometimes straight javascript is more simple!

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

Get day of week in SQL Server 2005/2008

You can use DATEPART(dw, GETDATE()) but be aware that the result will rely on SQL server setting @@DATEFIRST value which is the first day of week setting (In Europe default value 7 which is Sunday).

If you want to change the first day of week to another value, you could use SET DATEFIRST but this may affect everywhere in your query session which you do not want.

Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST setting. You can use the following formula to achieve that when need it:

(DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1

where @WeekStartDay is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).

I have wrapped it into below function so we can reuse it easily:

CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
RETURNS INT
AS
BEGIN
    --Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
    RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1 
END

Example usage: GetDayInWeek('2019-02-04 00:00:00', 1)

It is equivalent to following (but independent to SQL server DATEFIRST setting):

SET DATEFIRST 1
DATEPART(dw, '2019-02-04 00:00:00')

Uninstall Node.JS using Linux command line?

The answer of George Bailey works fine. I would just add the following flags and use sudo if needed:

 sudo rm -rf bin/node bin/node-waf include/node lib/node lib/pkgconfig/nodejs.pc share/man/man1/node

SQL Server Installation - What is the Installation Media Folder?

For me the Issue was I didn't run the setup as Administrator, after running the setup as administrator the message go away and I was prompted to install and continue process.

What does 'const static' mean in C and C++?

This ia s global constant visible/accessible only in the compilation module (.cpp file). BTW using static for this purpose is deprecated. Better use an anonymous namespace and an enum:

namespace
{
  enum
  {
     foo = 42
  };
}

Update a dataframe in pandas while iterating row by row

Increment the MAX number from a column. For Example :

df1 = [sort_ID, Column1,Column2]
print(df1)

My output :

Sort_ID Column1 Column2
12         a    e
45         b    f
65         c    g
78         d    h

MAX = df1['Sort_ID'].max() #This returns my Max Number 

Now , I need to create a column in df2 and fill the column values which increments the MAX .

Sort_ID Column1 Column2
79      a1       e1
80      b1       f1
81      c1       g1
82      d1       h1

Note : df2 will initially contain only the Column1 and Column2 . we need the Sortid column to be created and incremental of the MAX from df1 .

Cut Java String at a number of character

StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.

How to urlencode a querystring in Python?

For Python 3 urllib3 works properly, you can use as follow as per its official docs :

import urllib3

http = urllib3.PoolManager()
response = http.request(
     'GET',
     'https://api.prylabs.net/eth/v1alpha1/beacon/attestations',
     fields={  # here fields are the query params
          'epoch': 1234,
          'pageSize': pageSize 
      } 
 )
response = attestations.data.decode('UTF-8')

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This worked for me

On the Zipped folder of the ADT you initially downloaded unzip and navigate to:

adt-bundle-windows-x86_64-20140702\eclipse\plugins

Copy all the executable jar files and paste them on the

C:\adt-bundle-windows-x86_64-20140702\adt-bundle-windows-x86_64-20140702\eclipse\plugins

directory (or wherever your adt is located).
Any executable jar files missing in the plugin folder will be added. You should be able to launch eclipse

how to create insert new nodes in JsonNode?

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Yet another possible cause:

In my case, I had a xib and was calling Bundle.main.loadNibNamed(... at which point it was crashing. All my IBOutlets and IBActions seemed fine. In the end I noticed that the nib was actually loading, but then when I tried to access the first (and only) view (nib.first), that was not working. In fact nib.count was returning a very large integer (max int?), instead of the expected 1. I tried re-adding the view, but still no luck.

In the end, I deleted the whole xib file and started again (but I kept some of the views in my clipboard so I can paste them instead of recreating them again).

This worked!

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I was unable to find the root cause of the issue but got a workaround. I started by setting my the java home variable as such.

  • vi ~/.bash_profile (this is for macs only. bash profiles are different on linux)
  • type the letter i for insert and then set the JAVA_HOME variable as such
  • export JAVA_HOME=/Applications/Android\Studio.app/Contents/jre/jdk/Contents/Home/
  • quit the vi editor with esc then type :wq
  • Restart the computer
  • Voila! Your android studio projects should build without any qualms

What does the Java assert keyword do, and when should it be used?

To recap (and this is true of many languages not just Java):

"assert" is primarily used as a debugging aid by software developers during the debugging process. Assert-messages should never appear. Many languages provide a compile-time option that will cause all "asserts" to be ignored, for use in generating "production" code.

"exceptions" are a handy way to handle all kinds of error conditions, whether or not they represent logic errors, because, if you run into an error-condition such that you cannot continue, you can simply "throw them up into the air," from wherever you are, expecting someone else out there to be ready to "catch" them. Control is transferred in one step, straight from the code that threw the exception, straight to the catcher's mitt. (And the catcher can see the complete backtrace of calls that had taken place.)

Furthermore, callers of that subroutine don't have to check to see if the subroutine succeeded: "if we're here now, it must have succeeded, because otherwise it would have thrown an exception and we wouldn't be here now!" This simple strategy makes code-design and debugging much, much easier.

Exceptions conveniently allow fatal-error conditions to be what they are: "exceptions to the rule." And, for them to be handled by a code-path that is also "an exception to the rule ... "fly ball!"

html table span entire width?

Just FYI:

html should be table & width:100%. span should be margin: auto;

Setting device orientation in Swift iOS

From ios 10.0 we need set { self.orientations = newValue } for setting up the orientation, Make sure landscape property is enabled in your project.

private var orientations = UIInterfaceOrientationMask.landscapeLeft
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    get { return self.orientations }
    set { self.orientations = newValue }
}

C++ sorting and keeping track of indexes

vector<pair<int,int> >a;

for (i = 0 ;i < n ; i++) {
    // filling the original array
    cin >> k;
    a.push_back (make_pair (k,i)); // k = value, i = original index
}

sort (a.begin(),a.end());

for (i = 0 ; i < n ; i++){
    cout << a[i].first << " " << a[i].second << "\n";
}

Now a contains both both our values and their respective indices in the sorted.

a[i].first = value at i'th.

a[i].second = idx in initial array.

CodeIgniter - accessing $config variable in view

You can do something like that:

$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');

Can I get div's background-image url?

Using just one call to replace (regex version): var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and was solved by running the following in run

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

@Autowired and static method

What you can do is @Autowired a setter method and have it set a new static field.

public class Boo {
    @Autowired
    Foo foo;

    static Foo staticFoo;   

    @Autowired
    public void setStaticFoo(Foo foo) {
        Boo.staticFoo = foo;
    }

    public static void randomMethod() {
         staticFoo.doStuff();
    }
}

When the bean gets processed, Spring will inject a Foo implementation instance into the instance field foo. It will then also inject the same Foo instance into the setStaticFoo() argument list, which will be used to set the static field.

This is a terrible workaround and will fail if you try to use randomMethod() before Spring has processed an instance of Boo.

How to write ternary operator condition in jQuery?

Here is a working example in side a function:

_x000D_
_x000D_
function setCurrency(){_x000D_
   var returnCurrent;_x000D_
   $("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';_x000D_
   _x000D_
   return returnCurrent;_x000D_
}
_x000D_
_x000D_
_x000D_

In your case. Change the selector and the return values

_x000D_
_x000D_
$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";
_x000D_
_x000D_
_x000D_

lastly, to know what is the value used by the browser run the following in the console:

_x000D_
_x000D_
$("#blackbox").css('background-color')
_x000D_
_x000D_
_x000D_

and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.

Disabling browser caching for all browsers from ASP.NET

I've tried various combinations and had them fail in FireFox. It has been a while so the answer above may work fine or I may have missed something.

What has always worked for me is to add the following to the head of each page, or the template (Master Page in .net).

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function () {   
        // This function does nothing.  It won't spawn a confirmation dialog   
        // But it will ensure that the page is not cached by the browser.
    }  
</script>

This has disabled all caching in all browsers for me without fail.

Reading values from DataTable

I think it will work

for (int i = 1; i <= broj_ds; i++ ) 
  { 

     QuantityInIssueUnit_value = dr_art_line_2[i]["Column"];
     QuantityInIssueUnit_uom  = dr_art_line_2[i]["Column"];

  }

Make HTML5 video poster be same size as video itself

My solution combines user2428118 and Veiko Jääger's answers, allowing for preloading but without requiring a separate transparent image. We use a base64 encoded 1px transparent image instead.

<style type="text/css" >
    video{
        background: transparent url("poster.jpg") 50% 50% / cover no-repeat ;
    }
</style>
<video controls poster="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" >
    <source src="movie.mp4" type="video/mp4">
    <source src="movie.ogg" type="video/ogg">
</video>

Laravel 5.4 redirection to custom url after login

The way I've done it by using AuthenticatesUsers trait.

\App\Http\Controllers\Auth\LoginController.php

Add this method to that controller:

/**
 * Check user's role and redirect user based on their role
 * @return 
 */
public function authenticated()
{
    if(auth()->user()->hasRole('admin'))
    {
        return redirect('/admin/dashboard');
    } 

    return redirect('/user/dashboard');
}

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Using sudo with Python script

subprocess.Popen creates a process and opens pipes and stuff. What you are doing is:

  • Start a process sudo -S
  • Start a process mypass
  • Start a process mount -t vboxsf myfolder /home/myuser/myfolder

which is obviously not going to work. You need to pass the arguments to Popen. If you look at its documentation, you will notice that the first argument is actually a list of the arguments.

YouTube: How to present embed video with sound muted

Just pass mute=1.

For example:

<iframe id="myVideo" src="https://www.youtube.com/embed/k0DN-BZrM4o?rel=0&amp;autoplay=1;mute=1" width="100%" height="600" frameborder="0" allowfullscreen></iframe>

Auto-center map with multiple markers in Google Maps API v3

There's an easier way, by extending an empty LatLngBounds rather than creating one explicitly from two points. (See this question for more details)

Should look something like this, added to your code:

//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();    

for (i = 0; i < locations.length; i++) {  
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  //extend the bounds to include each marker's position
  bounds.extend(marker.position);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);

//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(3);
    google.maps.event.removeListener(listener);
});

This way, you can use an arbitrary number of points, and don't need to know the order beforehand.

Demo jsFiddle here: http://jsfiddle.net/x5R63/

How to get complete month name from DateTime

You can do as mservidio suggested, or even better, keep track of your culture using this overload:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

Swift - How to hide back button in navigation item?

Here is a version of the answer in

Swift 5

that you can use it from the storyboard:

// MARK: - Hiding Back Button

extension UINavigationItem {

    /// A Boolean value that determines whether the back button is hidden.
    ///
    /// When set to `true`, the back button is hidden when this navigation item
    /// is the top item. This is true regardless of the value in the
    /// `leftItemsSupplementBackButton` property. When set to `false`, the back button
    /// is shown if it is still present. (It can be replaced by values in either
    /// the `leftBarButtonItem` or `leftBarButtonItems` properties.) The default value is `false`.
    @IBInspectable var hideBackButton: Bool {
        get { hidesBackButton }
        set { hidesBackButton = newValue }
    }
}

Every navigation item of a view controller will have this new property in the top section of attributes inspector

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

Convert string to date in Swift

  • Convert the ISO8601 string to date

    let isoDate = "2016-04-14T10:44:00+0000"
    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!
    
  • Get the date components for year, month, day and hour from the date

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
    
  • Finally create a new Date object and strip minutes and seconds

    let finalDate = calendar.date(from:components)
    

Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

Creating temporary files in Android

Do it in simple. According to documentation https://developer.android.com/training/data-storage/files

String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
        picFile = new File(ProfileActivity.this.getCacheDir(),imageName);

and delete it after usage

picFile.delete()

What is the native keyword in Java for?

NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.

When should I use Kruskal as opposed to Prim (and vice versa)?

Use Prim's algorithm when you have a graph with lots of edges.

For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.

Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.

How can I group by date time column without taking time into consideration

Cast/Convert the values to a Date type for your group by.

GROUP BY CAST(myDateTime AS DATE)

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

Empty responseText from XMLHttpRequest

Had a similar problem to yours. What we had to do is use the document.domain solution found here:

Ways to circumvent the same-origin policy

We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:

https://developer.mozilla.org/En/HTTP_access_control

How to Get True Size of MySQL Database?

From S. Prakash, found at the MySQL forum:

SELECT table_schema "database name",
    sum( data_length + index_length ) / 1024 / 1024 "database size in MB",
    sum( data_free )/ 1024 / 1024 "free space in MB"
FROM information_schema.TABLES
GROUP BY table_schema; 

Or in a single line for easier copy-pasting:

SELECT table_schema "database name", sum( data_length + index_length ) / 1024 / 1024 "database size in MB", sum( data_free )/ 1024 / 1024 "free space in MB" FROM information_schema.TABLES GROUP BY table_schema; 

Attach IntelliJ IDEA debugger to a running Java process

Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).

  • Go to Java tab:

    enter image description here

  • Set your Java properties, for example:

    Java virtual machine

    C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll

    Java virtual machine

    C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar

    Java Options:

    -Dcatalina.home=C:\tomcat

    -Dcatalina.base=C:\tomcat

    -Djava.io.tmpdir=C:\tomcat\temp

    -Djava.util.logging.config.file=C:\tomcat\conf\logging.properties

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000

    Java 9 options:

    --add-opens=java.base/java.lang=ALL-UNNAMED

    --add-opens=java.base/java.io=ALL-UNNAMED

    --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

In a separate terminal, connect your device to the computer and run the following commands:

react-native start 
cd user/Library/Android/sdk/platform-tools/
./adb reverse tcp:8081 tcp:8081

Application terminal:

react-native run-android 
install apk on your device from this location android/app/build/outputs/apk/app-debug.apk

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

In my case a switch from openjdk7 to openjdk6 helped. Afterwards I changed the compliance level to 1.6 and all compiled fine.

Socket accept - "Too many open files"

There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.

You can check the following:

cat /proc/sys/fs/file-max

That will give you the system wide limits of file descriptors.

On the shell level, this will tell you your personal limit:

ulimit -n

This can be changed in /etc/security/limits.conf - it's the nofile param.

However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.