Programs & Examples On #Perfect hash

A perfect hash function for a set S is a hash function that maps distinct elements in S to a set of integers, with no collisions.

How to resize Twitter Bootstrap modal dynamically based on the content

I simply override the css:

.modal-dialog {
    max-width: 1000px;
}

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

How to zero pad a sequence of integers in bash so that all have the same width?

Use awk like this:

awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'

OUTPUT:

00001
00002
00003
00004
00005
00006
00007
00008
00009
00010

Update:

As pure bash alternative you can do this to get same output:

for i in {1..10}
do
   printf "%05d\n" $i
done

This way you can avoid using an external program seq which is NOT available on all the flavors of *nix.

Failed to start mongod.service: Unit mongod.service not found

For Ubuntu 16.04.5, it is noticed that MongoDB installations does not auto enable the mongod.service file after installation in my case after I have installed on several servers, so we need to enable it like below:

Issue below to check whether mongod is enabled

systemctl list-unit-files --type=service

If it shows as "disabled", then you need to enable it.

sudo systemctl enable mongod.service

If we want to see whether mongod.service file exists in case this file is missing, check in

ls /lib/systemd/system

You will see a file

/lib/systemd/system/mongod.service

Is arr.__len__() the preferred way to get the length of an array in Python?

Python uses duck typing: it doesn't care about what an object is, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.

For a complete list of interfaces, have a look here: http://docs.python.org/reference/datamodel.html#basic-customization

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

Select column to drop:

ALTER TABLE my_table
DROP column_to_be_deleted;

However, some databases (including SQLite) have limited support, and you may have to create a new table and migrate the data over:

https://www.sqlite.org/faq.html#q11

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

jobs:
 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Get the same error while sending from outlook because of ssl. Tried setting EnableSSL = false resolved the issue.

example:

var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",                   
                    Port = 587,
                    EnableSsl = false,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,                   
                    Credentials = new NetworkCredential("[email protected]", "xxxxx")
                };

return in for loop or outside loop

Since there is no issue with GC. I prefer this.

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;
}

Intent.putExtra List

 //To send from the activity that is calling another activity via myIntent

    myIntent.putExtra("id","10");
    startActivity(myIntent);

    //To receive from another Activity

            Bundle bundle = getIntent().getExtras();
            String id=bundle.getString("id");

How do I remove objects from a JavaScript associative array?

All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:

alert(myObj["SomeProperty"]);
alert(myObj.SomeProperty);

And, as already indicated, you "remove" a property from an object via the delete keyword, which you can use in two ways:

delete myObj["SomeProperty"];
delete myObj.SomeProperty;

Hope the extra info helps...

How to make a phone call programmatically?

Solved..! September 5, 2020.

It is working very well. In this way, you do not need to have permission from user. You can open directly phone calling part.

Trick point, use ACTION_DIAL instead of ACTION_CALL.

private void callPhoneNumber() {
    String phone = "03131693169";
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.setData(Uri.parse("tel:" + phone));
    startActivity(callIntent);
}

For more question, ask me on Instagram: @canerkaseler

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

.Net: How do I find the .NET version?

Here is the Power Shell script which I used by taking the reference of:

https://stackoverflow.com/a/3495491/148657

$Lookup = @{
    378389 = [version]'4.5'
    378675 = [version]'4.5.1'
    378758 = [version]'4.5.1'
    379893 = [version]'4.5.2'
    393295 = [version]'4.6'
    393297 = [version]'4.6'
    394254 = [version]'4.6.1'
    394271 = [version]'4.6.1'
    394802 = [version]'4.6.2'
    394806 = [version]'4.6.2'
    460798 = [version]'4.7'
    460805 = [version]'4.7'
    461308 = [version]'4.7.1'
    461310 = [version]'4.7.1'
    461808 = [version]'4.7.2'
    461814 = [version]'4.7.2'
    528040 = [version]'4.8'
    528049 = [version]'4.8'
}

# For One True framework (latest .NET 4x), change the Where-Oject match 
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
  Get-ItemProperty -name Version, Release -EA 0 |
  Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}}, 
@{name = "Product"; expression = {$Lookup[$_.Release]}}, 
Version, Release

The above script makes use of the registry and gives us the Windows update number along with .Net Framework installed on a machine.

Reference: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#to-find-net-framework-versions-by-querying-the-registry-in-code-net-framework-45-and-later

Here are the results for the same when running that script on two different machines

  1. Where .NET 4.7.2 was already installed:

enter image description here

  1. Where .NET 4.7.2 was not installed:

enter image description here

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Jinja2 template variable if None Object set a default value

Use the none test (not to be confused with Python's None object!):

{% if p is not none %}   
    {{ p.User['first_name'] }}
{% else %}
    NONE
{% endif %}

or:

{{ p.User['first_name'] if p is not none else 'NONE' }}

or if you need an empty string:

{{ p.User['first_name'] if p is not none }}

What is w3wp.exe?

  • A worker process runs as an executables file named W3wp.exe
  • A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.

  • The worker process is controlled by the www service.

  • worker processes also run application code, Such as ASP .NET applications and XML web Services.

  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.

  • When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.htmlenter image description here

Registry key Error: Java version has value '1.8', but '1.7' is required

As for me on win7 64bit.

Copy the java.exe javaw.exe javaws.exe in the folder C:\Program Files\Java\jre1.8.0_91\bin to the C:\Windows\System32.

and then open cmd, type java -version.

C:\Users\HEcom>java -version
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)

Before the above make sure the Registry's CurrentVersion is 1.8

In the START menu type "regedit" to open the Registry editor

  1. Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu
  2. Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries
  3. Click "JavaSoft" within the "SOFTWARE" registries
  4. Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java
  5. Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) make sure the version is "1.8"

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Redefine tab as 4 spaces

Add line
set ts=4
in
~/.vimrc file for per user
or
/etc/vimrc file for system wide

What is the significance of 1/1/1753 in SQL Server?

This is whole story how date problem was and how Big DBMSs handled these problems.

During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.

When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.

Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?

This is how the Big DBMSs handle these questions:

  • Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
  • Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
  • Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)

Source 1 and 2

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

How to detect orientation change?

If you want to do something AFTER the rotation is complete, you can use the UIViewControllerTransitionCoordinator completion handler like this

public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    // Hook in to the rotation animation completion handler
    coordinator.animate(alongsideTransition: nil) { (_) in
        // Updates to your UI...
        self.tableView.reloadData()
    }
}

Resizing UITableView to fit content

Swift 5 Solution

Follow these four steps:

  1. Set the height constraint for the tableview from the storyboard.

  2. Drag the height constraint from the storyboard and create @IBOutlet for it in the view controller file.

    @IBOutlet var tableViewHeightConstraint: NSLayoutConstraint!
    
  3. Add an observer for the contentSize property on the override func viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
 
    }

  1. Then you can change the height for the table dynamicaly using this code:

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
         if(keyPath == "contentSize"){
             if let newvalue = change?[.newKey]
             {
                 DispatchQueue.main.async {
                 let newsize  = newvalue as! CGSize
                 self.tableViewHeightConstraint.constant = newsize.height
                 }
    
             }
         }
     }
    

How to obtain Certificate Signing Request

Follow these steps to create CSR (Code Signing Identity):

  1. On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'

    enter image description here

  2. Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?

    enter image description here

  3. Fill out the information in the Certificate Information window as specified below and click "Continue."
    • In the User Email Address field, enter the email address to identify with this certificate
    • In the Common Name field, enter your name
    • In the Request group, click the "Saved to disk" option ?

    enter image description here

  4. Save the file to your hard drive.

    enter image description here


Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.

Convert an integer to a float number

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

Which means that you need to use float64(integer_value).

Passing data into "router-outlet" child components

Yes, you can set inputs of components displayed via router outlets. Sadly, you have to do it programmatically, as mentioned in other answers. There's a big caveat to that when observables are involved (described below).

Here's how:

(1) Hook up to the router-outlet's activate event in the parent template:

<router-outlet (activate)="onOutletLoaded($event)"></router-outlet>

(2) Switch to the parent's typescript file and set the child component's inputs programmatically each time they are activated:

onOutletLoaded(component) {
    component.node = 'someValue';
} 

Done.

However, the above version of onOutletLoaded is simplified for clarity. It only works if you can guarantee all child components have the exact same inputs you are assigning. If you have components with different inputs, use type guards:

onChildLoaded(component: MyComponent1 | MyComponent2) {
  if (component instanceof MyComponent1) {
    component.someInput = 123;
  } else if (component instanceof MyComponent2) {
    component.anotherInput = 456;
  }
}

Why may this method be preferred over the service method?

Neither this method nor the service method are "the right way" to communicate with child components (both methods step away from pure template binding), so you just have to decide which way feels more appropriate for the project.

This method, however, avoids the tight coupling associated with the "create a service for communication" approach (i.e., the parent needs the service, and the children all need the service, making the children unusable elsewhere). Decoupling is usually preferred.

In many cases this method also feels closer to the "angular way" because you can continue passing data to your child components through @Inputs (thats the decoupling part - this enables re-use elsewhere). It's also a good fit for already existing or third-party components that you don't want to or can't tightly couple with your service.

On the other hand, it may feel less like the angular way when...

Caveat

The caveat with this method is that since you are passing data in the typescript file, you no longer have the option of using the pipe-async pattern used in templates (e.g. {{ myObservable$ | async }}) to automagically use and pass on your observable data to child components.

Instead, you'll need to set up something to get the current observable values whenever the onChildLoaded function is called. This will likely also require some teardown in the parent component's onDestroy function. This is nothing too unusual, there are often cases where this needs to be done, such as when using an observable that doesn't even get to the template.

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

A scan of the @SpringBootApplication show that it includes the following annotations:

@Configuration
@ComponentScan
@EnableAutoConfiguration

So you could do this too:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
       SpringApplication.run(ScheduledTasks.class, args);
    }
}

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

How to fix System.NullReferenceException: Object reference not set to an instance of an object

If the problem is 100% here

EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);

There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.

EDIT after several hours

There were some problems:

  • MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.

  • several event handlers weren't wired up to control events

Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.

JavaScript check if value is only undefined, null or false

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}

How can jQuery deferred be used?

The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases. jQuery.when() handles a non-Promise/Deferred as a Completed one, immediately executing any .done() or .then() on the chain.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Another real world example using the $.when helper:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

Fastest way to list all primes below N

The simplest way I've found of doing this is:

primes = []
for n in range(low, high + 1):
    if all(n % i for i in primes):
        primes.append(n)

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

For me it was complaining like that on Windows 7 x64 when I had another process already listening on that same port.

It is possible to see currently occupied (bound) ports by running

netstat -ban

Setting mime type for excel document

For .xls use the following content-type

application/vnd.ms-excel

For Excel 2007 version and above .xlsx files format

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Creating a ZIP archive in memory using System.IO.Compression

Set the position of the stream to the 0 before copying it to the zip stream.

using (var memoryStream = new MemoryStream())
{
 using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
 {
  var demoFile = archive.CreateEntry("foo.txt");

  using (var entryStream = demoFile.Open())
  using (var streamWriter = new StreamWriter(entryStream))
  {
     streamWriter.Write("Bar!");
  }
 }

 using (var fileStream = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
   {
     memoryStream.Position=0;
     memoryStream.WriteTo(fileStream);
   }
 }

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

If you will apply security="none" then no csrf token will be generated. The page will not pass through security filter. Use role ANONYMOUS.

I have not gone in details, but it is working for me.

 <http auto-config="true" use-expressions="true">
   <intercept-url pattern="/login.jsp" access="hasRole('ANONYMOUS')" />
   <!-- you configuration -->
   </http>

Is there a simple way to delete a list element by value?

If you know what value to delete, here's a simple way (as simple as I can think of, anyway):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

You'll get [0, 0, 2, 3, 4]

Count cells that contain any text

You can pass "<>" (including the quotes) as the parameter for criteria. This basically says, as long as its not empty/blank, count it. I believe this is what you want.

=COUNTIF(A1:A10, "<>") 

Otherwise you can use CountA as Scott suggests

Creating an empty Pandas DataFrame, then filling it?

Here's a couple of suggestions:

Use date_range for the index:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']

Note: we could create an empty DataFrame (with NaNs) simply by writing:

df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs

To do these type of calculations for the data, use a numpy array:

data = np.array([np.arange(10)]*3).T

Hence we can create the DataFrame:

In [10]: df = pd.DataFrame(data, index=index, columns=columns)

In [11]: df
Out[11]: 
            A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

Converting JSON to XML in Java

Underscore-java library has static method U.jsonToXml(jsonstring). I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";  
        System.out.println(json); 
        String xml = U.jsonToXml(json);  
        System.out.println(xml); 
    }
}

Output:

{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <name>JSON</name>
  <integer number="true">1</integer>
  <double number="true">2.0</double>
  <boolean boolean="true">true</boolean>
  <nested>
    <id number="true">42</id>
  </nested>
  <array number="true">1</array>
  <array number="true">2</array>
  <array number="true">3</array>
</root>

spark submit add multiple jars in classpath

You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .

spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*

Javascript Thousand Separator / string format

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}

Method call if not null in C#

What you're looking for is the Null-Conditional (not "coalescing") operator: ?.. It's available as of C# 6.

Your example would be obj?.SomeMethod();. If obj is null, nothing happens. When the method has arguments, e.g. obj?.SomeMethod(new Foo(), GetBar()); the arguments are not evaluated if obj is null, which matters if evaluating the arguments would have side effects.

And chaining is possible: myObject?.Items?[0]?.DoSomething()

C++ where to initialize static const

Only integral values (e.g., static const int ARRAYSIZE) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.

How do I execute cmd commands through a batch file?

I know DOS and cmd prompt DOES NOT LIKE spaces in folder names. Your code starts with

cd c:\Program files\IIS Express

and it's trying to go to c:\Program in stead of C:\"Program Files"

Change the folder name and *.exe name. Hope this helps

How to switch position of two items in a Python list?

you can use for example:

>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',
                 'last_name', 'next', 'newsletter']
>>> reorder_func = lambda x: x.insert(x.index('password2'),  x.pop(x.index('password2')+1))
>>> reorder_func(test_list)
>>> test_list
... ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']

How to use a calculated column to calculate another column in the same view

You could use a nested query:

Select
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC as calccolumn2
From (
  Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from t42
);

With a row with values 3, 4, 5 that gives:

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4

You can also just repeat the first calculation, unless it's really doing something expensive (via a function call, say):

Select
  ColumnA,
  ColumnB,
  ColumnA + ColumnB As calccolumn1,
  (ColumnA + ColumnB) / ColumnC As calccolumn2
from t42; 

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2
---------- ---------- ----------- -----------
         3          4           7         1.4 

Get current folder path

1.

Directory.GetCurrentDirectory();

2.

Thread.GetDomain().BaseDirectory

3.

Environment.CurrentDirectory

What is the Ruby <=> (spaceship) operator?

I will explain with simple example

  1. [1,3,2] <=> [2,2,2]

    Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

  2. [2,3,2] <=> [2,2,2]

    As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

How to convert an address into a Google Maps Link (NOT MAP)

I had a similar issue where I needed to accomplish this for every address on the site (each wrapped in an address tag). This bit of jQuery worked for me. It'll grab each <address> tag and wrap it in a google maps link with the address the tag contains contains!

$("address").each(function(){

    var address = $(this).text().replace(/\,/g, '');
    var url = address.replace(/\ /g, '%20');

    $(this).wrap('<a href="http://maps.google.com/maps?q=' + url +'"></a>');

}); 

Working example --> https://jsfiddle.net/f3kx6mzz/1/

Coerce multiple columns to factors at once

and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if:

data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
              data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)     

factoredData = data %>% mutate_if(is.character,funs(factor(.)))

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

How to add time to DateTime in SQL

For me, this code looks more explicit:

CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime)

Duplicate line in Visual Studio Code

Mac:

Duplicate Line Down :shift + option + ?

Duplicate Line Up:shift + option + ?

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

Modify SVG fill color when being served as Background-Image

I needed something similar and wanted to stick with CSS. Here are LESS and SCSS mixins as well as plain CSS that can help you with this. Unfortunately, it's browser support is a bit lax. See below for details on browser support.

LESS mixin:

.element-color(@color) {
  background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="@{color}" ... /></g></svg>');
}

LESS usage:

.element-color(#fff);

SCSS mixin:

@mixin element-color($color) {
  background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="#{$color}" ... /></g></svg>');
}

SCSS usage:

@include element-color(#fff);

CSS:

// color: red
background-image: url('data:image/svg+xml;utf8,<svg ...><g stroke="red" ... /></g></svg>');

Here is more info on embedding the full SVG code into your CSS file. It also mentioned browser compatibility which is a bit too small for this to be a viable option.

Adding a regression line on a ggplot

In general, to provide your own formula you should use arguments x and y that will correspond to values you provided in ggplot() - in this case x will be interpreted as x.plot and y as y.plot. You can find more information about smoothing methods and formula via the help page of function stat_smooth() as it is the default stat used by geom_smooth().

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data=mean_cl_normal) + 
  geom_smooth(method='lm', formula= y~x)

If you are using the same x and y values that you supplied in the ggplot() call and need to plot the linear regression line then you don't need to use the formula inside geom_smooth(), just supply the method="lm".

ggplot(data,aes(x.plot, y.plot)) +
  stat_summary(fun.data= mean_cl_normal) + 
  geom_smooth(method='lm')

Recommended way to get hostname in Java

If you're not against using an external dependency from maven central, I wrote gethostname4j to solve this problem for myself. It just uses JNA to call libc's gethostname function (or gets the ComputerName on Windows) and returns it to you as a string.

https://github.com/mattsheppard/gethostname4j

Rebasing remote branches in Git

It comes down to whether the feature is used by one person or if others are working off of it.

You can force the push after the rebase if it's just you:

git push origin feature -f

However, if others are working on it, you should merge and not rebase off of master.

git merge master
git push origin feature

This will ensure that you have a common history with the people you are collaborating with.

On a different level, you should not be doing back-merges. What you are doing is polluting your feature branch's history with other commits that don't belong to the feature, making subsequent work with that branch more difficult - rebasing or not.

This is my article on the subject called branch per feature.

Hope this helps.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

Efficient way to add spaces between characters in a string

s = "BINGO"
print(" ".join(s))

Should do it.

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

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

You can simply access it like an array i.e. v[i] = v[i] - some_num;

How to Call Controller Actions using JQuery in ASP.NET MVC

You can easily call any controller's action using jQuery AJAX method like this:

Note in this example my controller name is Student

Controller Action

 public ActionResult Test()
 {
     return View();
 }

In Any View of this above controller you can call the Test() action like this:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Use LINQ to get items in one List<>, that are not in another List<>

If you override the equality of People then you can also use:

peopleList2.Except(peopleList1)

Except should be significantly faster than the Where(...Any) variant since it can put the second list into a hashtable. Where(...Any) has a runtime of O(peopleList1.Count * peopleList2.Count) whereas variants based on HashSet<T> (almost) have a runtime of O(peopleList1.Count + peopleList2.Count).

Except implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.

Or if you want fast code but don't want to override the equality:

var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));

This variant does not remove duplicates.

How can I list all cookies for the current page with Javascript?

No.

The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain name only.

Accessing all cookies for current domain is done via document.cookie.

How can I write variables inside the tasks file in ansible

NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.

Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.


ORIGINAL ANSWER

Use set_fact before your task to set facts which seem interchangeable with variables:

- name: Set Apache URL
  set_fact:
    apache_url: 'http://example.com/apache'

- name: Download Apache
  shell: wget {{ apache_url }}

See http://docs.ansible.com/set_fact_module.html for the official word.

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

Centering Bootstrap input fields

Well in my case the following work fine

<div class="card-body p-2">
  <div class="d-flex flex-row justify-content-center">
     <div style="margin: auto;">
        <input type="text" autocomplete="off"
          style="max-width:150px!important; "
          class="form-control form-control-sm font-weight-bold align-self-center w-25" id="dtTechState">
     </div>
  </div>
</div>

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

How to rename JSON key

In this case it would be easiest to use string replace. Serializing the JSON won't work well because _id will become the property name of the object and changing a property name is no simple task (at least not in most langauges, it's not so bad in javascript). Instead just do;

jsonString = jsonString.replace("\"_id\":", "\"id\":");

Python: Convert timedelta to int in a dataframe

The Series class has a pandas.Series.dt accessor object with several useful datetime attributes, including dt.days. Access this attribute via:

timedelta_series.dt.days

You can also get the seconds and microseconds attributes in the same way.

Unable to import path from django.urls

You need Django version 2

pip install --upgrade django
pip3 install --upgrade django

python -m django --version # 2.0.2
python3 -m django --version # 2.0.2

Are there dictionaries in php?

Associative array in PHP actually considered as a dictionary.

An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.

Git Remote: Error: fatal: protocol error: bad line length character: Unab

Maybe you have a statement in the server's .bashrc that produces output. I, for example had this:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use ruby-1.9.3-p194@rails32

In this case the output from the rvm use will be (wrongly) interpreted as coming from git. So replace it by:

rvm use ruby-1.9.3-p194@rails32 > /dev/null

How do I access the $scope variable in browser's console using AngularJS?

Inspect the element, then use this in the console

s = $($0).scope()
// `s` is the scope object if it exists

Re-doing a reverted merge in Git

I would suggest you to follow below steps to revert a revert, say SHA1.

git checkout develop #go to develop branch
git pull             #get the latest from remote/develop branch
git branch users/yourname/revertOfSHA1 #having HEAD referring to develop
git checkout users/yourname/revertOfSHA1 #checkout the newly created branch
git log --oneline --graph --decorate #find the SHA of the revert in the history, say SHA1
git revert SHA1
git push --set-upstream origin users/yourname/revertOfSHA1 #push the changes to remote

Now create PR for the branch users/yourname/revertOfSHA1

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

MySQL Select Date Equal to Today

Sounds like you need to add the formatting to the WHERE:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE DATE_FORMAT(users.signup_date, '%Y-%m-%d') = CURDATE()

See SQL Fiddle with Demo

passing form data to another HTML page

If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.

In the form, add a method="GET" attribute:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

When they submit this form, the user will be directed to an address which includes the serialNumber value as a parameter. Something like:

http://www.example.com/display.html?serialNumber=XYZ

You should then be able to parse the query string - which will contain the serialNumber parameter value - from JavaScript, using the window.location.search value:

// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
                                                                     // the query string to extract the
                                                                     // parameter you need

See also JavaScript query string.


The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html page loads.

See also How to use JavaScript to fill a form on another page.

WAMP won't turn green. And the VCRUNTIME140.dll error

As Oriol said, you need the following redistributables before installing WAMP.

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

How can I check whether an array is null / empty?

You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.

int[] k = new int[3];
if(k.length == 0)
{
//do something
}

Lightweight XML Viewer that can handle large files

I have tried dozens of XML editors hoping to find one which would be able to do some kind of visualization. The best lightweight viewer for windows I have found was XMLMarker - too bad the project has been dead for some years now. It is not so useful as an editor, but it does a good job of displaying flat XML data as tables.

There are tons of free editors that do XML syntax highlighting, including vim, emacs, scite, eclipse (J2EE edition), jedit, notepad++.

For heavyweight XML features, like XPath support, XSLT editing and debugging, SOAP/WSDL there are some good commercial tools like, XMLSpy, Oxygen, StylusStudio.

JEdit is open-source and also has plugins for XML, XPath and XSLT.

Word-2003 is fairly good for visualizing (but don't use it for editing). Excel-2003 and up also does a good job at visualizing flat XML data and can apply XSL transformations (again, no good as an editor).

Determine distance from the top of a div to top of window with javascript

Vanilla:

window.addEventListener('scroll', function(ev) {

   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;

   console.log(distanceToTop);
});

Open your browser console and scroll your page to see the distance.

How can I find the first and last date in a month using PHP?

If you want to find the first day and last day from the specified date variable then you can do this like below:

$date    =    '2012-02-12';//your given date

$first_date_find = strtotime(date("Y-m-d", strtotime($date)) . ", first day of this month");
echo $first_date = date("Y-m-d",$first_date_find);

$last_date_find = strtotime(date("Y-m-d", strtotime($date)) . ", last day of this month");
echo $last_date = date("Y-m-d",$last_date_find);

For the current date just simple use this

$first_date = date('Y-m-d',strtotime('first day of this month'));
$last_date = date('Y-m-d',strtotime('last day of this month'));

Python's equivalent of && (logical-and) in an if-statement

I'm getting an error in the IF conditional. What am I doing wrong?

There reason that you get a SyntaxError is that there is no && operator in Python. Likewise || and ! are not valid Python operators.

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or. Likewise the logical negation operator ! is called not.

So you could just write:

if len(a) % 2 == 0 and len(b) % 2 == 0:

or even:

if not (len(a) % 2 or len(b) % 2):

Some additional information (that might come in handy):

I summarized the operator "equivalents" in this table:

+------------------------------+---------------------+
|  Operator (other languages)  |  Operator (Python)  |
+==============================+=====================+
|              &&              |         and         |
+------------------------------+---------------------+
|              ||              |         or          |
+------------------------------+---------------------+
|              !               |         not         |
+------------------------------+---------------------+

See also Python documentation: 6.11. Boolean operations.

Besides the logical operators Python also has bitwise/binary operators:

+--------------------+--------------------+
|  Logical operator  |  Bitwise operator  |
+====================+====================+
|        and         |         &          |
+--------------------+--------------------+
|         or         |         |          |
+--------------------+--------------------+

There is no bitwise negation in Python (just the bitwise inverse operator ~ - but that is not equivalent to not).

See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.

The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn't evaluated at all.

To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:

>>> def print_and_return(value):
...     print(value)
...     return value

>>> res = print_and_return(False) and print_and_return(True)
False

As you can see only one print statement is executed, so Python really didn't even look at the right operand.

This is not the case for the binary operators. Those always evaluate both operands:

>>> res = print_and_return(False) & print_and_return(True);
False
True

But if the first operand isn't enough then, of course, the second operator is evaluated:

>>> res = print_and_return(True) and print_and_return(False);
True
False

To summarize this here is another Table:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

The True and False represent what bool(left-hand-side) returns, they don't have to be True or False, they just need to return True or False when bool is called on them (1).

So in Pseudo-Code(!) the and and or functions work like these:

def and(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return evaluate(expr2)
    else:
        return left

def or(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return left
    else:
        return evaluate(expr2)

Note that this is pseudo-code not Python code. In Python you cannot create functions called and or or because these are keywords. Also you should never use "evaluate" or if bool(...).

Customizing the behavior of your own classes

This implicit bool call can be used to customize how your classes behave with and, or and not.

To show how this can be customized I use this class which again prints something to track what is happening:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        print('__bool__ called on {!r}'.format(self))
        return bool(self.value)

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

So let's see what happens with that class in combination with these operators:

>>> if Test(True) and Test(False):
...     pass
__bool__ called on Test(True)
__bool__ called on Test(False)

>>> if Test(False) or Test(False):
...     pass
__bool__ called on Test(False)
__bool__ called on Test(False)

>>> if not Test(True):
...     pass
__bool__ called on Test(True)

If you don't have a __bool__ method then Python also checks if the object has a __len__ method and if it returns a value greater than zero. That might be useful to know in case you create a sequence container.

See also 4.1. Truth Value Testing.

NumPy arrays and subclasses

Probably a bit beyond the scope of the original question but in case you're dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool call will raise the dreaded ValueError:

>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In these cases you can use the logical and function from NumPy which performs an element-wise and (or or):

>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False,  True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False,  True,  True])

If you're dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:

>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False,  True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False,  True,  True])

(1)

That the bool call on the operands has to return True or False isn't completely correct. It's just the first operand that needs to return a boolean in it's __bool__ method:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        return self.value

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)

That's because and actually returns the first operand if the first operand evaluates to False and if it evaluates to True then it returns the second operand:

>>> x1
Test(10)
>>> x2
Test(False)

Similarly for or but just the other way around:

>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)

However if you use them in an if statement the if will also implicitly call bool on the result. So these finer points may not be relevant for you.

How to toggle font awesome icon on click?

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li> </ul>

//Jquery

$(document).ready(function() {
    $('li').click(function() {
      $('i').toggleClass('fa-plus-square fa-minus-square');
    });
  }); 

JSFiddle

Dynamically creating keys in a JavaScript associative array

In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).

A quick Google search brings up hash tables in JavaScript.

Example code for looping over values in a hash (from the aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

How to draw circle in html page?

As of 2015, you can make it and center the text with as few as 15 lines of CSS (Fiddle):

_x000D_
_x000D_
body {_x000D_
  background-color: #fff;_x000D_
}_x000D_
#circle {_x000D_
  position: relative;_x000D_
  background-color: #09f;_x000D_
  margin: 20px auto;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 200px;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  color: #fff;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <title>circle with text</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="circle">_x000D_
    <div id="text">Text in the circle</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Without any -webkit-s, this works on IE11, Firefox, Chrome and Opera, and it is valid HTML5 (experimental) and CSS3.

Same on MS Edge (2020).

Trigger css hover with JS

If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().

What are you trying to accomplish?

Passing variables through handlebars partial

This can also be done in later versions of handlebars using the key=value notation:

 {{> mypartial foo='bar' }}

Allowing you to pass specific values to your partial context.

Reference: Context different for partial #182

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

let value = 100;
console.log(`The size is ${ value }`);

How do I give ASP.NET permission to write to a folder in Windows 7?

I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.

It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.

Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".

These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.

Hope that helps

How to give a time delay of less than one second in excel vba?

Otherwise you can create your own function then call it. It is important to use Double

Function sov(sekunder As Double) As Double

starting_time = Timer

Do
DoEvents
Loop Until (Timer - starting_time) >= sekunder

End Function

Python, HTTPS GET with basic authentication

In Python 3 the following will work. I am using the lower level http.client from the standard library. Also check out section 2 of rfc2617 for details of basic authorization. This code won't check the certificate is valid, but will set up a https connection. See the http.client docs on how to do that.

from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it 
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' %  userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()  

How to pass variable as a parameter in Execute SQL Task SSIS?

The EXCEL and OLED DB connection managers use the parameter names 0 and 1.

I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot.

SQL Server - boolean literal?

I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!

Make a number a percentage

((portion/total) * 100).toFixed(2) + '%'

Why is document.write considered a "bad practice"?

  • A simple reason why document.write is a bad practice is that you cannot come up with a scenario where you cannot find a better alternative.
  • Another reason is that you are dealing with strings instead of objects (it is very primitive).
  • It does only append to documents.
  • It has nothing of the beauty of for instance the MVC (Model-View-Controller) pattern.
  • It is a lot more powerful to present dynamic content with ajax+jQuery or angularJS.

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.

CSS

.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;
}

HTML

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>
</ul>

Message Queue vs. Web Services?

Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.

Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.

Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.

Date only from TextBoxFor()

Or use the untyped helpers:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>

Use jQuery to get the file input's selected filename without the path

We can also remove it using match

var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Getting the 'external' IP address in Java

System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

What version of JBoss I am running?

JBoss has an MBean called Server. That reports the build and version of JBoss itself. Once you know the version, you can see what components are involved. It is not that well cataloged, but you can see it in the release notes.

How can I wait for set of asynchronous callback functions?

You haven't been very specific with your code, so I'll make up a scenario. Let's say you have 10 ajax calls and you want to accumulate the results from those 10 ajax calls and then when they have all completed you want to do something. You can do it like this by accumulating the data in an array and keeping track of when the last one has finished:

Manual Counter

var ajaxCallsRemaining = 10;
var returnedData = [];

for (var i = 0; i < 10; i++) {
    doAjax(whatever, function(response) {
        // success handler from the ajax call

        // save response
        returnedData.push(response);

        // see if we're done with the last ajax call
        --ajaxCallsRemaining;
        if (ajaxCallsRemaining <= 0) {
            // all data is here now
            // look through the returnedData and do whatever processing 
            // you want on it right here
        }
    });
}

Note: error handling is important here (not shown because it's specific to how you're making your ajax calls). You will want to think about how you're going to handle the case when one ajax call never completes, either with an error or gets stuck for a long time or times out after a long time.


jQuery Promises

Adding to my answer in 2014. These days, promises are often used to solve this type of problem since jQuery's $.ajax() already returns a promise and $.when() will let you know when a group of promises are all resolved and will collect the return results for you:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push($.ajax(...));
}
$.when.apply($, promises).then(function() {
    // returned data is in arguments[0][0], arguments[1][0], ... arguments[9][0]
    // you can process it here
}, function() {
    // error occurred
});

ES6 Standard Promises

As specified in kba's answer: if you have an environment with native promises built-in (modern browser or node.js or using babeljs transpile or using a promise polyfill), then you can use ES6-specified promises. See this table for browser support. Promises are supported in pretty much all current browsers, except IE.

If doAjax() returns a promise, then you can do this:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
    // returned data is in arguments[0], arguments[1], ... arguments[n]
    // you can process it here
}, function(err) {
    // error occurred
});

If you need to make a non-promise async operation into one that returns a promise, you can "promisify" it like this:

function doAjax(...) {
    return new Promise(function(resolve, reject) {
        someAsyncOperation(..., function(err, result) {
            if (err) return reject(err);
            resolve(result);
        });
    });
}

And, then use the pattern above:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
    // returned data is in arguments[0], arguments[1], ... arguments[n]
    // you can process it here
}, function(err) {
    // error occurred
});

Bluebird Promises

If you use a more feature rich library such as the Bluebird promise library, then it has some additional functions built in to make this easier:

 var doAjax = Promise.promisify(someAsync);
 var someData = [...]
 Promise.map(someData, doAjax).then(function(results) {
     // all ajax results here
 }, function(err) {
     // some error here
 });

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

What is the difference between lower bound and tight bound?

Big O is the upper bound, while Omega is the lower bound. Theta requires both Big O and Omega, so that's why it's referred to as a tight bound (it must be both the upper and lower bound).

For example, an algorithm taking Omega(n log n) takes at least n log n time, but has no upper limit. An algorithm taking Theta(n log n) is far preferential since it takes at least n log n (Omega n log n) and no more than n log n (Big O n log n).

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

The error is coming because of the parser you are using. In general, if you have HTML file/code then you need to use html5lib(documentation can be found here) & in-case you have XML file/data then you need to use lxml(documentation can be found here). You can use lxml for HTML file/code also but sometimes it gives an error as above. So, better to choose the package wisely based on the type of data/file. You can also use html_parser which is built-in module. But, this also sometimes do not work.

For more details regarding when to use which package you can see the details here

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

How can I tell what edition of SQL Server runs on the machine?

select @@version

Sample Output

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )

If you just want to get the edition, you can use:

select serverproperty('Edition')

To use in an automated script, you can get the edition ID, which is an integer:

select serverproperty('EditionID')
  • -1253826760 = Desktop
  • -1592396055 = Express
  • -1534726760 = Standard
  • 1333529388 = Workgroup
  • 1804890536 = Enterprise
  • -323382091 = Personal
  • -2117995310 = Developer
  • 610778273 = Enterprise Evaluation
  • 1044790755 = Windows Embedded SQL
  • 4161255391 = Express with Advanced Services

How to use GROUP_CONCAT in a CONCAT in MySQL

SELECT ID, GROUP_CONCAT(CONCAT_WS(':', NAME, VALUE) SEPARATOR ',') AS Result 
FROM test GROUP BY ID

How to animate CSS Translate

I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.

I put it all together in a jQuery plugin

https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0

You would use the code like this:

$("#myElement").animateTransform("rotate(180deg)", 750, function(){
  console.log("animation completed after 750ms");
});

Word count from a txt file program

The funny symbols you're encountering are a UTF-8 BOM (Byte Order Mark). To get rid of them, open the file using the correct encoding (I'm assuming you're on Python 3):

file = open(r"D:\zzzz\names2.txt", "r", encoding="utf-8-sig")

Furthermore, for counting, you can use collections.Counter:

from collections import Counter
wordcount = Counter(file.read().split())

Display them with:

>>> for item in wordcount.items(): print("{}\t{}".format(*item))
...
snake   1
lion    2
goat    2
horse   3

Load arrayList data into JTable

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
        
    rows = table.getRowCount();

    cols = table.getColumnCount();

    for (int i = 0; i < rows ; i++) {

            for ( int k  = 0; k < cols ; k++) {
            
            for (int h = 0; h < list1.size(); h++) {
                
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();
                
            }
        }
    }
}

How to change column datatype from character to numeric in PostgreSQL 8.4

You can try using USING:

The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

So this might work (depending on your data):

alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);

This will fail if you have anything in code that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.

Two dimensional array in python

You try to append to second element in array, but it does not exist. Create it.

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr.append([])
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")

Remove characters from NSString?

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return str;
}

Hope this will help you out.

Setting selection to Nothing when programming Excel

I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson's site: http://www.cpearson.com/excel/UnSelect.aspx.

UnSelectActiveCell

This procedure will remove the Active Cell from the Selection.

Sub UnSelectActiveCell()
    Dim R As Range
    Dim RR As Range
    For Each R In Selection.Cells
        If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then
            If RR Is Nothing Then
                Set RR = R
            Else
                Set RR = Application.Union(RR, R)
            End If
        End If
    Next R
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub

UnSelectCurrentArea

This procedure will remove the Area containing the Active Cell from the Selection.

Sub UnSelectCurrentArea()
    Dim Area As Range
    Dim RR As Range

    For Each Area In Selection.Areas
        If Application.Intersect(Area, ActiveCell) Is Nothing Then
            If RR Is Nothing Then
                Set RR = Area
            Else
                Set RR = Application.Union(RR, Area)
            End If
        End If
    Next Area
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

How to disable Hyper-V in command line?

The OP had the best answer for me and it appears that others have figured out the -All addition as well. I set up two batch files, then shortcuts to those so you can set the Run As Admin permissions on them, easy-peasy.

Batch Off

Call dism.exe /Online /Disable-Feature:Microsoft-Hyper-V-All

Batch On

Call dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All

Right-click -> create desktop shortcut. Right-click the shortcut -> properties -> under the shortcut tab -> Advanced -> Run as admin

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Extract time from date String

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

How do I execute a Shell built-in command with a C function?

You can use the excecl command

int execl(const char *path, const char *arg, ...);

Like shown here

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>

int main (void) {

   return execl ("/bin/pwd", "pwd", NULL);

}

The second argument will be the name of the process as it will appear in the process table.

Alternatively, you can use the getcwd() function to get the current working directory:

#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#define MAX 255

int main (void) {
char wd[MAX];
wd[MAX-1] = '\0';

if(getcwd(wd, MAX-1) == NULL) {
  printf ("Can not get current working directory\n");
}
else {
  printf("%s\n", wd);
}
  return 0;
}

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Oracle: is there a tool to trace queries, like Profiler for sql server?

There is a commercial tool FlexTracer which can be used to trace Oracle SQL queries

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I had a case with 3 levels a'la _MainLayout.cshtml <--- _Middle.cshtml <--- Page.cshtml. Even though doing like this:

_MainLayout.cshtml

<head>
   @RenderSection("head", false)
</head>

_Middle.cshtml

@section head {
    @RenderSection("head")
}

and in Page.cshtml defining

@section head {
   ***content***
}

I would still get the error

The following sections have been defined but have not been rendered for the layout page “~/Views/Shared/_Middle.cshtml”: "head".

Turned out, the error was for the Middle.cshtml to rely on /Views/_ViewStart.cshtml to resolve it's parent layout. The problem was resolved by defining this in Middle.cshtml explicitly:

@{
Layout = "~/Views/_Shared/_MainLayout.cshtml";
}

Can't decide whether this would be by-design or a bug in MVC 4 - anyhow, problem was solved :)

GitHub "fatal: remote origin already exists"

facing same error while add repository to git hun using git bash on windows

 git remote add origin https://github.com/axaysushir/netflix_page_clone.git

fatal: remote origin already exists.

fatal: remote origin already exists.

 ! [rejected]        master -> master (fetch first)

error: failed to push some refs to 'https://github.com/axaysushir/meditation_app_using_js.git'

Update repository by following command

$ git remote set-url origin https://github.com/axaysushir/netflix_page_clone.git

then add repository using git remote add github instead git remote add origin

$ git remote add github https://github.com/axaysushir/netflix_page_clone.git

And then write following command instead of git push origin master this will upload your repository to github

$ git push github master

Why is “while ( !feof (file) )” always wrong?

It's wrong because (in the absence of a read error) it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.

Consider the following code:

/* WARNING: demonstration of bad coding technique!! */

#include <stdio.h>
#include <stdlib.h>

FILE *Fopen(const char *path, const char *mode);

int main(int argc, char **argv)
{
    FILE *in;
    unsigned count;

    in = argc > 1 ? Fopen(argv[1], "r") : stdin;
    count = 0;

    /* WARNING: this is a bug */
    while( !feof(in) ) {  /* This is WRONG! */
        fgetc(in);
        count++;
    }
    printf("Number of characters read: %u\n", count);
    return EXIT_SUCCESS;
}

FILE * Fopen(const char *path, const char *mode)
{
    FILE *f = fopen(path, mode);
    if( f == NULL ) {
        perror(path);
        exit(EXIT_FAILURE);
    }
    return f;
}

This program will consistently print one greater than the number of characters in the input stream (assuming no read errors). Consider the case where the input stream is empty:

$ ./a.out < /dev/null
Number of characters read: 1

In this case, feof() is called before any data has been read, so it returns false. The loop is entered, fgetc() is called (and returns EOF), and count is incremented. Then feof() is called and returns true, causing the loop to abort.

This happens in all such cases. feof() does not return true until after a read on the stream encounters the end of file. The purpose of feof() is NOT to check if the next read will reach the end of file. The purpose of feof() is to determine the status of a previous read function and distinguish between an error condition and the end of the data stream. If fread() returns 0, you must use feof/ferror to decide whether an error occurred or if all of the data was consumed. Similarly if fgetc returns EOF. feof() is only useful after fread has returned zero or fgetc has returned EOF. Before that happens, feof() will always return 0.

It is always necessary to check the return value of a read (either an fread(), or an fscanf(), or an fgetc()) before calling feof().

Even worse, consider the case where a read error occurs. In that case, fgetc() returns EOF, feof() returns false, and the loop never terminates. In all cases where while(!feof(p)) is used, there must be at least a check inside the loop for ferror(), or at the very least the while condition should be replaced with while(!feof(p) && !ferror(p)) or there is a very real possibility of an infinite loop, probably spewing all sorts of garbage as invalid data is being processed.

So, in summary, although I cannot state with certainty that there is never a situation in which it may be semantically correct to write "while(!feof(f))" (although there must be another check inside the loop with a break to avoid a infinite loop on a read error), it is the case that it is almost certainly always wrong. And even if a case ever arose where it would be correct, it is so idiomatically wrong that it would not be the right way to write the code. Anyone seeing that code should immediately hesitate and say, "that's a bug". And possibly slap the author (unless the author is your boss in which case discretion is advised.)

Android studio Gradle icon error, Manifest Merger

It seems to be the fault of the mainfest Merger tool for gradle.

http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger

Solved it by adding to my manifest tag xmlns:tools="http://schemas.android.com/tools"

Then added tools:replace="android:icon,android:theme" to the application tag

This tells the merger to use my manifest icon and theme and not of other libraries

Hope it helps thanks

Best practice for instantiating a new Android Fragment

I'm lately here. But somethings I just known that might help you a bit.

If you are using Java, there is nothing much to change. But for kotlin developers, here is some following snippet I think that can make you a basement to run on:

  • Parent fragment:
inline fun <reified T : SampleFragment> newInstance(text: String): T {
    return T::class.java.newInstance().apply {
        arguments = Bundle().also { it.putString("key_text_arg", text) }
    }
}
  • Normal call
val f: SampleFragment = SampleFragment.newInstance("ABC")
// or val f = SampleFragment.newInstance<SampleFragment>("ABC")
  • You can extend the parent init operation in child fragment class by:
fun newInstance(): ChildSampleFragment {
    val child = UserProfileFragment.newInstance<ChildSampleFragment>("XYZ")
    // Do anything with the current initialized args bundle here
    // with child.arguments = ....
    return child
}

Happy coding.

jQuery, simple polling example

function doPoll(){
    $.post('ajax/test.html', function(data) {
        alert(data);  // process results here
        setTimeout(doPoll,5000);
    });
}

Multiple linear regression in Python

Just to clarify, the example you gave is multiple linear regression, not multivariate linear regression refer. Difference:

The very simplest case of a single scalar predictor variable x and a single scalar response variable y is known as simple linear regression. The extension to multiple and/or vector-valued predictor variables (denoted with a capital X) is known as multiple linear regression, also known as multivariable linear regression. Nearly all real-world regression models involve multiple predictors, and basic descriptions of linear regression are often phrased in terms of the multiple regression model. Note, however, that in these cases the response variable y is still a scalar. Another term multivariate linear regression refers to cases where y is a vector, i.e., the same as general linear regression. The difference between multivariate linear regression and multivariable linear regression should be emphasized as it causes much confusion and misunderstanding in the literature.

In short:

  • multiple linear regression: the response y is a scalar.
  • multivariate linear regression: the response y is a vector.

(Another source.)

Textarea that can do syntax highlighting on the fly?

Here is the response I've done to a similar question (Online Code Editor) on programmers:

First, you can take a look to this article:
Wikipedia - Comparison of JavaScript-based source code editors.

For more, here is some tools that seem to fit with your request:

  • EditArea - Demo as FileEditor who is a Yii Extension - (Apache Software License, BSD, LGPL)

    Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).

  • CodePress - Demo of Joomla! CodePress Plugin - (LGPL) - It doesn't work in Chrome and it looks like development has ceased.

    CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.

  • CodeMirror - One of the many demo - (MIT-style license + optional commercial support)

    CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content - computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation

  • Ace Ajax.org Cloud9 Editor - Demo - (Mozilla tri-license (MPL/GPL/LGPL))

    Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.

How to create Custom Ratings bar in Android

I investigated the original source,
and here is my result.

styles.xml (res/values)

<!-- RatingBar -->
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar_full</item>
    <item name="android:indeterminateDrawable">@drawable/ratingbar_full</item>
    <item name="android:minHeight">13.4dp</item>
    <item name="android:maxHeight">13.4dp</item>
</style>

ratingbar_full.xml (res/drawable)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/progress" android:drawable="@drawable/btn_rating_star_on_normal" />
</layer-list>

btn_rating_star_off_normal.png (res/drawable-xxhdpi)

enter image description here

btn_rating_star_on_normal.png (res/drawable-xxhdpi)

enter image description here

activity_ratingbar.xml (res/layout)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/ratingbar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="13.4dp"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="2.6"
        android:secondaryProgressTint="#00000000"
        android:stepSize="0.1" />
</FrameLayout>

This is the result.

enter image description here

  • Note that I added the actual height(13.4dp) of ratingbar in layout_height property, because if it is wrap_content it will draw lines below stars. (in my case only in a preview of Android Studio)

Processing Symbol Files in Xcode

xCode just copy all crashes logs. If you want to speed-up: delete number of crash reports after you analyze it, directly in this window.

Devices -> View Device Logs -> All Logs

screenshot

How to specify jackson to only use fields - preferably globally

If you use Spring Boot, you can configure Jackson globally as follows:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonObjectMapperConfiguration implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY);
    }

}

AngularJS $location not changing the path

In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.

Usually, when the $location doesn't work it means that something was not implemented the angular way.

In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.

The old code:

taskService.createTask(data).then(function(code){
            $location.path("task/" + code);
        }, function(error){});

Note: taskService.createTask returns a promise.

$q - the angular way to use promises:

let dataPromises = [taskService.createTask(data)];
        $q.all(dataPromises).then(function(response) {
                let code = response[0];
                $location.path("task/" + code);
            }, 
            function(error){});

Using $q to resolve the promise solved the redirection problem.

More on the $q service: https://docs.angularjs.org/api/ng/service/$q

Conda activate not working?

Have you tried with Anaconda command prompt or, cmd it works for me. Giving no error and activation is not working in PowerShell may be some path issue.

Verify host key with pysftp

If You try to connect by pysftp to "normal" FTP You have to set hostkey to None.

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None 
with pysftp.Connection(host='****',username='****',password='***',port=22,cnopts=cnopts) as sftp:
    print('DO SOMETHING')

Center a H1 tag inside a DIV

Started a jsFiddle here.

It seems the horizontal alignment works with a text-align : center. Still trying to get the vertical align to work; might have to use absolute positioning and something like top: 50% or a pre-calculated padding from the top.

Set up a scheduled job?

Look at Django Poor Man's Cron which is a Django app that makes use of spambots, search engine indexing robots and alike to run scheduled tasks in approximately regular intervals

See: http://code.google.com/p/django-poormanscron/

Easiest way to detect Internet connection on iOS?

Here is a good solution for checking connectivity using Swift, without using Reachability. I found it on this blog.

Create a new Swift file in your project called Network.swift (for example). Paste this code inside that file:

import Foundation

public class Network {

    class func isConnectedToNetwork()->Bool{

        var Status:Bool = false
        let url = NSURL(string: "http://google.com/")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "HEAD"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response: NSURLResponse?

        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                Status = true
            }
        }

        return Status
    }
}

You can then check for connectivity anywhere in your project by using:

if Network.isConnectedToNetwork() == true {
    println("Internet connection OK")
} else {
    println("Internet connection FAILED")
}

'App not Installed' Error on Android

In case, you have your app's older version installed from Google Play and you want to test the newer release version of your app:

  1. Open Google Play Console

  2. Upload the newer release version of your app to Alpha / Beta, but do not release it yet!

enter image description here

  1. You can now download the derived apk:
    enter image description here

Install the downloaded derived apk on your phone now. The derived apk is re-signed by Google Play with a different key from the release app Android Studio generates.

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

Remove an item from array using UnderscoreJS

Underscore has a _without() method perfect for removing an item from an array, especially if you have the object to remove.

Returns a copy of the array with all instances of the values removed.

_.without(["bob", "sam", "fred"], "sam");

=> ["bob", "fred"]

Works with more complex objects too.

var bob = { Name: "Bob", Age: 35 };
var sam = { Name: "Sam", Age: 19 };
var fred = { Name: "Fred", Age: 50 };

var people = [bob, sam, fred]

_.without(people, sam);

=> [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];

If you don't have the item to remove, just a property of it, you can use _.findWhere and then _.without.

How to synchronize a static variable among threads running different instances of a class in Java?

There are several ways to synchronize access to a static variable.

  1. Use a synchronized static method. This synchronizes on the class object.

    public class Test {
        private static int count = 0;
    
        public static synchronized void incrementCount() {
            count++;
        }
    } 
    
  2. Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    
  3. Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    

Method 3 is the best in many cases because the lock object is not exposed outside of your class.

Super-simple example of C# observer/observable with delegates

Something like this:

// interface implementation publisher
public delegate void eiSubjectEventHandler(eiSubject subject);

public interface eiSubject
{
    event eiSubjectEventHandler OnUpdate;

    void GenereteEventUpdate();

}

// class implementation publisher
class ecSubject : eiSubject
{
    private event eiSubjectEventHandler _OnUpdate = null;
    public event eiSubjectEventHandler OnUpdate
    {
        add
        {
            lock (this)
            {
                _OnUpdate -= value;
                _OnUpdate += value;
            }
        }
        remove { lock (this) { _OnUpdate -= value; } }
    }

    public void GenereteEventUpdate()
    {
        eiSubjectEventHandler handler = _OnUpdate;

        if (handler != null)
        {
            handler(this);
        }
    }

}

// interface implementation subscriber
public interface eiObserver
{
    void DoOnUpdate(eiSubject subject);

}

// class implementation subscriber
class ecObserver : eiObserver
{
    public virtual void DoOnUpdate(eiSubject subject)
    {
    }
}

. observer pattern C# with event . link to the repository

MySQL > Table doesn't exist. But it does (or it should)

I had this problem after upgrading WAMP but having no database backup.

This worked for me:

  1. Stop new WAMP

  2. Copy over database directories you need and ibdata1 file from old WAMP installation

  3. Delete ib_logfile0 and ib_logfile1

  4. Start WAMP

You should now be able to make backups of your databases. However after your server restarts again you will still have problems. So now reinstall WAMP and import your databases.

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

How to split a string of space separated numbers into integers?

Just use strip() to remove empty spaces and apply explicit int conversion on the variable.

Ex:

a='1  ,  2, 4 ,6 '
f=[int(i.strip()) for i in a]

How to grep (search) committed code in the Git history

Okay, twice just today I've seen people wanting a closer equivalent for hg grep, which is like git log -pS but confines its output to just the (annotated) changed lines.

Which I suppose would be handier than /pattern/ in the pager if you're after a quick overview.

So here's a diff-hunk scanner that takes git log --pretty=%h -p output and spits annotated change lines. Put it in diffmarkup.l, say e.g. make ~/bin/diffmarkup, and use it like

git log --pretty=%h -pS pattern | diffmarkup | grep pattern
%option main 8bit nodefault
        // vim: tw=0
%top{
        #define _GNU_SOURCE 1
}
%x commitheader
%x diffheader
%x hunk
%%
        char *afile=0, *bfile=0, *commit=0;
        int aline,aremain,bline,bremain;
        int iline=1;

<hunk>\n        ++iline; if ((aremain+bremain)==0) BEGIN diffheader;
<*>\n   ++iline;

<INITIAL,commitheader,diffheader>^diff.*        BEGIN diffheader;
<INITIAL>.*     BEGIN commitheader; if(commit)free(commit); commit=strdup(yytext);
<commitheader>.*

<diffheader>^(deleted|new|index)" ".*   {}
<diffheader>^"---".*            if (afile)free(afile); afile=strdup(strchrnul(yytext,'/'));
<diffheader>^"+++".*            if (bfile)free(bfile); bfile=strdup(strchrnul(yytext,'/'));
<diffheader,hunk>^"@@ ".*       {
        BEGIN hunk; char *next=yytext+3;
        #define checkread(format,number) { int span; if ( !sscanf(next,format"%n",&number,&span) ) goto lostinhunkheader; next+=span; }
        checkread(" -%d",aline); if ( *next == ',' ) checkread(",%d",aremain) else aremain=1;
        checkread(" +%d",bline); if ( *next == ',' ) checkread(",%d",bremain) else bremain=1;
        break;
        lostinhunkheader: fprintf(stderr,"Lost at line %d, can't parse hunk header '%s'.\n",iline,yytext), exit(1);
        }
<diffheader>. yyless(0); BEGIN INITIAL;

<hunk>^"+".*    printf("%s:%s:%d:%c:%s\n",commit,bfile+1,bline++,*yytext,yytext+1); --bremain;
<hunk>^"-".*    printf("%s:%s:%d:%c:%s\n",commit,afile+1,aline++,*yytext,yytext+1); --aremain;
<hunk>^" ".*    ++aline, ++bline; --aremain; --bremain;
<hunk>. fprintf(stderr,"Lost at line %d, Can't parse hunk.\n",iline), exit(1);

How do you obtain a Drawable object from a resource id in android package?

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

You should use the following code from the support library instead:

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

Is it possible to append Series to rows of DataFrame without making a list first?

Something like this could work...

mydf.loc['newindex'] = myseries

Here is an example where I used it...

stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()

stats
Out[32]: 
          bp_prob   ICD9_prob   meds_prob  regex_prob
count  171.000000  171.000000  171.000000  171.000000
mean     0.179946    0.059071    0.067020    0.126812
std      0.271546    0.142681    0.152560    0.207014
min      0.000000    0.000000    0.000000    0.000000
25%      0.000000    0.000000    0.000000    0.000000
50%      0.000000    0.000000    0.000000    0.013116
75%      0.309019    0.065248    0.066667    0.192954
max      1.000000    1.000000    1.000000    1.000000

medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()

stats.loc['median'] = medians

stats
Out[36]: 
           bp_prob   ICD9_prob   meds_prob  regex_prob
count   171.000000  171.000000  171.000000  171.000000
mean      0.179946    0.059071    0.067020    0.126812
std       0.271546    0.142681    0.152560    0.207014
min       0.000000    0.000000    0.000000    0.000000
25%       0.000000    0.000000    0.000000    0.000000
50%       0.000000    0.000000    0.000000    0.013116
75%       0.309019    0.065248    0.066667    0.192954
max       1.000000    1.000000    1.000000    1.000000
median    0.000000    0.000000    0.000000    0.013116

Git commit in terminal opens VIM, but can't get back to terminal

Simply doing the vim "save and quit" command :wq should do the trick.

In order to have Git open it in another editor, you need to change the Git core.editor setting to a command which runs the editor you want.

git config --global core.editor "command to start sublime text 2"

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Should IBOutlets be strong or weak under ARC?

One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:

https://developer.apple.com/videos/play/wwdc2015/407/

Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.

This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8

As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4

As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57

As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6

As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5

As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23

All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)

Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.

I hope this clarifies the subject a bit better!

Take care.

How to handle AccessViolationException

Add the following in the config file, and it will be caught in try catch block. Word of caution... try to avoid this situation, as this means some kind of violation is happening.

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

Bash script processing limited number of commands in parallel

You can run 20 processes and use the command:

wait

Your script will wait and continue when all your background jobs are finished.

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

How to append in a json file in Python?

json_obj=json.dumps(a_dict, ensure_ascii=False)

Can you change a path without reloading the controller in AngularJS?

Though this post is old and has had an answer accepted, using reloadOnSeach=false does not solve the problem for those of us who need to change actual path and not just the params. Here's a simple solution to consider:

Use ng-include instead of ng-view and assign your controller in the template.

<!-- In your index.html - instead of using ng-view -->
<div ng-include="templateUrl"></div>

<!-- In your template specified by app.config -->
<div ng-controller="MyController">{{variableInMyController}}</div>

//in config
$routeProvider
  .when('/my/page/route/:id', { 
    templateUrl: 'myPage.html', 
  })

//in top level controller with $route injected
$scope.templateUrl = ''

$scope.$on('$routeChangeSuccess',function(){
  $scope.templateUrl = $route.current.templateUrl;
})

//in controller that doesn't reload
$scope.$on('$routeChangeSuccess',function(){
  //update your scope based on new $routeParams
})

Only down-side is that you cannot use resolve attribute, but that's pretty easy to get around. Also you have to manage the state of the controller, like logic based on $routeParams as the route changes within the controller as the corresponding url changes.

Here's an example: http://plnkr.co/edit/WtAOm59CFcjafMmxBVOP?p=preview

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

Testing if a checkbox is checked with jQuery

You can get value (true/false) by these two method

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");

How to stop/shut down an elasticsearch node?

The Head plugin for Elasticsearch provides a great web based front end for Elasticsearch administration, including shutting down nodes. It can run any Elasticsearch commands as well.

Vertical align text in block element

You can also try

a {
  height:100px;
  line-height:100px;
}

How to convert a 3D point into 2D perspective projection?

enter image description here

Looking at the screen from the top, you get x and z axis.
Looking at the screen from the side, you get y and z axis.

Calculate the focal lengths of the top and side views, using trigonometry, which is the distance between the eye and the middle of the screen, which is determined by the field of view of the screen. This makes the shape of two right triangles back to back.

hw = screen_width / 2

hh = screen_height / 2

fl_top = hw / tan(?/2)

fl_side = hh / tan(?/2)


Then take the average focal length.

fl_average = (fl_top + fl_side) / 2


Now calculate the new x and new y with basic arithmetic, since the larger right triangle made from the 3d point and the eye point is congruent with the smaller triangle made by the 2d point and the eye point.

x' = (x * fl_top) / (z + fl_top)

y' = (y * fl_top) / (z + fl_top)


Or you can simply set

x' = x / (z + 1)

and

y' = y / (z + 1)

Changing Tint / Background color of UITabBar

[[self tabBar] insertSubview:v atIndex:0]; works perfectly for me.

Prevent form redirect OR refresh on submit?

It looks like you're missing a return false.

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

How do I obtain a Query Execution Plan in SQL Server?

There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.

Method 1 - Using SQL Server Management Studio

SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.

Include Action Execution Plan menu item

If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:

exec p_Example 42

When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.

Screenshot of an Execution Plan

From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.

Method 2 - Using SHOWPLAN options

This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.

Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:

SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use

These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.

Once you are done you can turn this option off with the following statement:

SET <<option>> OFF

Comparison of execution plan formats

Unless you have a strong preference my recommendation is to use the STATISTICS XML option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.

  • SHOWPLAN_TEXT - Displays a basic text based estimated execution plan, without executing the query
  • SHOWPLAN_ALL - Displays a text based estimated execution plan with cost estimations, without executing the query
  • SHOWPLAN_XML - Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.
  • STATISTICS PROFILE - Executes the query and displays a text based actual execution plan.
  • STATISTICS XML - Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 3 - Using SQL Server Profiler

If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.

Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!

  1. Open SQL Server Profiler and create a new trace connecting to the desired database against which you wish to record the trace.
  2. Under the "Events Selection" tab check "Show all events", check the "Performance" -> "Showplan XML" row and run the trace.
  3. While the trace is running, do whatever it is you need to do to get the slow running query to run.
  4. Wait for the query to complete and stop the trace.
  5. To save the trace right click on the plan xml in SQL Server Profiler and select "Extract event data..." to save the plan to file in XML format.

The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 4 - Inspecting the query cache

If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.

We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.

SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)

Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.

Notes:

Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).

You can't capture an execution plan for encrypted stored procedures.

"actual" vs "estimated" execution plans

An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).

How do I interpret a query execution plan?

This is a topic worthy enough for a (free) book in its own right.

See also:

Editor does not contain a main type in Eclipse

Right click on Sample.java file and delete it. Now go to File -> New -> Class , enter name of program (i.e. hello) , click on finish . It will create file hello.java. Enter source code of program and finallly press ctrl + F11

click here to see screenshot1

click here to see screenshot2

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

I realize that this question is quite old, but I had a similar problem, except my string had spaces included in it. For those that need to know how to separate a string with more than just commas:

string str = "Tom, Scott, Bob";
  IList<string> names = str.Split(new string[] {","," "},
  StringSplitOptions.RemoveEmptyEntries);

The StringSplitOptions removes the records that would only be a space char...

What and When to use Tuple?

A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.

Usually though you should create a class as this allows you to give useful names to each property. Code that extensively uses tuples will quickly become unreadable because the properties are called Item1, Item2, Item3, etc..

Why isn't textarea an input[type="textarea"]?

So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in 
        my textarea without any problems.
    </textarea>
</body>
</html>

How do I auto-hide placeholder text upon focus using css or jquery?

To augment @casey-chu's and pirate rob's answer, here's a more cross browser compatible way:

    /* WebKit browsers */
input:focus::-webkit-input-placeholder { color:transparent; }

    /* Mozilla Firefox 4 to 18 */
input:focus:-moz-placeholder { color:transparent; }

    /* Mozilla Firefox 19+ */
input:focus::-moz-placeholder { color:transparent; }

    /* Internet Explorer 10+ */
input:focus:-ms-input-placeholder { color:transparent; }

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it

Number of rows affected by an UPDATE in PL/SQL

Please try this one..


create table client (
  val_cli integer
 ,status varchar2(10)
);

---------------------
begin
insert into client
select 1, 'void' from dual
union all
select 4, 'void' from dual
union all
select 1, 'void' from dual
union all
select 6, 'void' from dual
union all
select 10, 'void' from dual;
end;

---------------------
select * from client;

---------------------
declare
  counter integer := 0;
begin
  for val in 1..10
    loop
      update client set status = 'updated' where val_cli = val;
      if sql%rowcount = 0 then
        dbms_output.put_line('no client with '||val||' val_cli.');
      else
        dbms_output.put_line(sql%rowcount||' client updated for '||val);
        counter := counter + sql%rowcount;
      end if;
  end loop;
   dbms_output.put_line('Number of total lines affected update operation: '||counter);
end;

---------------------
select * from client;

--------------------------------------------------------

Result will be like below:


2 client updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10
Number of total lines affected update operation: 5


How do I set browser width and height in Selenium WebDriver?

This works both with headless and non-headless, and will start the window with the specified size instead of setting it after:

from selenium.webdriver import Firefox, FirefoxOptions

opts = FirefoxOptions()
opts.add_argument("--width=2560")
opts.add_argument("--height=1440")

driver = Firefox(options=opts)

How to delete all the rows in a table using Eloquent?

I wasn't able to use Model::truncate() as it would error:

SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint

And unfortunately Model::delete() doesn't work (at least in Laravel 5.0):

Non-static method Illuminate\Database\Eloquent\Model::delete() should not be called statically, assuming $this from incompatible context

But this does work:

(new Model)->newQuery()->delete()

That will soft-delete all rows, if you have soft-delete set up. To fully delete all rows including soft-deleted ones you can change to this:

(new Model)->newQueryWithoutScopes()->forceDelete()

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed