Programs & Examples On #Array intersect

PHP's array_intersect() function accepts the array with master values to check, an array to compare values against and a variable list of arrays to compare. It returns an array containing all of the values in master array whose values exist in all of the parameters.

Django: Calling .update() on a single model instance retrieved by .get()?

I am using the following code in such cases:

obj, created = Model.objects.get_or_create(id=some_id)

if not created:
   resp= "It was created"
else:
   resp= "OK"
   obj.save()

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

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

AFNetworking for Android:

Fast Android Networking is here

Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH

Fast Android Networking Library supports downloading any type of file

Fast Android Networking Library supports uploading any type of file (supports multipart upload)

Fast Android Networking Library supports cancelling a request

Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)

Fast Android Networking Library supports RxJava

As it uses OkHttp as a networking layer, it supports:

Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket

Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)

Transparent GZIP shrinks download sizes

Fast Android Networking Library supports response caching which avoids the network completely for repeat requests

Thanks: The library is created by me

IP to Location using Javascript

You can use this google service free IP geolocation webservice

update

the link is broken, I put here other link that include @NickSweeting in the comments:

ip-api.com

and you can get the data in json format:

http://ip-api.com/docs/api:json

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

The C# Replace method usually works for me:

foo = "http://maps.google.com/?q=" + address.Text.Replace(" ","+");

Case insensitive comparison NSString

Converting Jason Coco's answer to Swift for the profoundly lazy :)

if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
  // Strings are equal.
}

How can I capitalize the first letter of each word in a string?

The .title() method can't work well,

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

Try string.capwords() method,

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

From the Python documentation on capwords:

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

set initial viewcontroller in appdelegate - swift

Swift 3, Swift 4:

Change first line to

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

the rest is same.

Swift 5+:

Instantiate root view controller from storyboard:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        // In project directory storyboard looks like Main.storyboard,
        // you should use only part before ".storyboard" as its name,
        // so in this example name is "Main".
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        
        // controller identifier sets up in storyboard utilities
        // panel (on the right), it is called 'Storyboard ID'
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

        self.window?.rootViewController = viewController
        self.window?.makeKeyAndVisible()        
        return true
    }

If you want to use UINavigationController as root:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // this line is important
        self.window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
        let navigationController = UINavigationController.init(rootViewController: viewController)
        self.window?.rootViewController = navigationController

        self.window?.makeKeyAndVisible()        
        return true
    }

Instantiate root view controller from xib:

It is almost the same, but instead of lines

let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController

you'll have to write

let viewController = YourViewController(nibName: "YourViewController", bundle: nil)

How to clear exisiting dropdownlist items when its content changes?

Please use the following

ddlCity.Items.Clear();

How to show a confirm message before delete?

function del_confirm(msg,url)
        {
            if(confirm(msg))
            {
                window.location.href=url
            }
            else
            {
                false;
            }

        }



<a  onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>

Jquery function BEFORE form submission

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here
});

JSON Array iteration in Android/Java

I have done it two different ways,

1.) make a Map

        HashMap<String, String> applicationSettings = new HashMap<String,String>();
        for(int i=0; i<settings.length(); i++){
            String value = settings.getJSONObject(i).getString("value");
            String name = settings.getJSONObject(i).getString("name");
            applicationSettings.put(name, value);
        }

2.) make a JSONArray of names

    JSONArray names = json.names();
    JSONArray values = json.toJSONArray(names);
    for(int i=0; i<values.length(); i++){
        if (names.getString(i).equals("description")){
            setDescription(values.getString(i));
        }
        else if (names.getString(i).equals("expiryDate")){
            String dateString = values.getString(i);
            setExpiryDate(stringToDateHelper(dateString)); 
        }
        else if (names.getString(i).equals("id")){
            setId(values.getLong(i));
        }
        else if (names.getString(i).equals("offerCode")){
            setOfferCode(values.getString(i));
        }
        else if (names.getString(i).equals("startDate")){
            String dateString = values.getString(i);
            setStartDate(stringToDateHelper(dateString));
        }
        else if (names.getString(i).equals("title")){
            setTitle(values.getString(i));
        }
    }

Check object empty

You can't do it directly, you should provide your own way to check this. Eg.

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.

Password masking console application

This masks the password with a red square, then reverts back to the original colours once the password has been entered.

It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.

Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;

Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;

string Password = Console.ReadLine(); // read the password

Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;

How do you change the size of figures drawn with matplotlib?

If you've already got the figure created you can quickly do this:

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)

To propagate the size change to an existing gui window add forward=True

fig.set_size_inches(18.5, 10.5, forward=True)

How can I have same rule for two locations in NGINX config?

Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:

error_page 418 = @common_location;
location /first/location/ {
    return 418;
}
location /second/location/ {
    return 418;
}
location @common_location {
    # The common configuration...
}

There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.

The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.

Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:

location /specialpages/ {
    # some config
    location /specialpages/static/ {
        try_files $uri $uri/ =404;
    }
    location /specialpages/dynamic/ {
        proxy_pass http://127.0.0.1;
    }
}

How to send objects through bundle

I came across this question when I was looking for a way to pass a Date object. In my case, as was suggested among the answers, I used Bundle.putSerializable() but that wouldn't work for a complex thing as the described DataManager in the original post.

My suggestion that will give a very similar result to putting said DataManager in the Application or make it a Singleton is to use Dependency Injection and bind the DataManager to a Singleton scope and inject the DataManager wherever it is needed. Not only do you get the benefit of increased testability but you'll also get cleaner code without all of the boiler plate "passing dependencies around between classes and activities" code. (Robo)Guice is very easy to work with and the new Dagger framework looks promising as well.

React won't load local images

I faced the same issue, and I found out the problem was the location of my images. Instead of saving them into the src folder, you should store them in the public directory and have direct access.

Kudos.

error: command 'gcc' failed with exit status 1 on CentOS

How i solved

# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv

I hope it will help Someone to resolve "gcc" issue.

Saving image to file

You can try with this code

Image.Save("myfile.png", ImageFormat.Png)

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

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

How do I fire an event when a iframe has finished loading in jQuery?

Using both jquery Load and Ready neither seemed to really match when the iframe was TRULY ready.

I ended up doing something like this

$('#iframe').ready(function () {
    $("#loader").fadeOut(2500, function (sender) {
        $(sender).remove();
    });
});

Where #loader is an absolutely positioned div over top the iframe with a spinner gif.

jQuery event for images loaded

imagesLoaded Plugin is way to go ,if you need a crossbrowser solution

 $("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
 if($broken.length > 0){
 //Error CallBack
 console.log('Error');
 }
 else{
 // Load CallBack
 console.log('Load');
 }
 });

If You Just Need a IE WorkAround,This Will Do

 var img = $("<img>", {
    error: function() {console.log('error'); },
    load: function() {console.log('load');}
    });
  img.attr('src','image.jpg');

How do I get the current time zone of MySQL?

My PHP framework uses

SET LOCAL time_zone='Whatever'

on after connect, where 'Whatever' == date_default_timezone_get()

Not my solution, but this ensures SYSTEM timezone of MySQL server is always the same as PHP's one

So, yes, PHP is strongly envolved and can affect it

Use component from another module

(Angular 2 - Angular 7)

Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:

  1. Export the component in the other module
  2. Import the other module, into the current module

1st Module:

Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.

@NgModule({
declarations: [
    FirstPage,
    ImportantCopmonent // <-- Enable using the component html tag in current module
],
imports: [
  IonicPageModule.forChild(NotImportantPage),
  TranslateModule.forChild(),
],
exports: [
    FirstPage,
    ImportantCopmonent // <--- Enable using the component in other modules
  ]
})
export class FirstPageModule { }

2nd Module:

Reuses the "ImportantCopmonent", by importing the FirstPageModule

@NgModule({
declarations: [
    SecondPage,
    Example2ndComponent,
    Example3rdComponent
],
imports: [
  IonicPageModule.forChild(SecondPage),
  TranslateModule.forChild(),
  FirstPageModule // <--- this Imports the source module, with its exports
], 
exports: [
    SecondPage,
]
})
export class SecondPageModule { }

How to accept Date params in a GET request to Spring MVC Controller?

Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
    public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
        //Content goes here
    }

Yes, it's simple. Just add the DateTimeFormat annotation.

htmlentities() vs. htmlspecialchars()

You probably want to use some Unicode character encoding, for example UTF-8, and htmlspecialchars. Because there isn't any need to generate "HTML entities" for "all [the] applicable characters" (that is what htmlentities does according to the documentation) if it's already in your character set.

No plot window in matplotlib

Try this:

import matplotlib
matplotlib.use('TkAgg') 

BEFORE import pylab

display: flex not working on Internet Explorer

Internet Explorer doesn't fully support Flexbox due to:

Partial support is due to large amount of bugs present (see known issues).

enter image description here Screenshot and infos taken from caniuse.com

Notes

Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.

Known issues

  • IE 11 requires a unit to be added to the third argument, the flex-basis property see MSFT documentation.
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property. See bug.
  • In IE10 the default value for flex is 0 0 auto rather than 0 1 auto as defined in the latest spec.
  • IE 11 does not vertically align items correctly when min-height is used. See bug.

Workarounds

Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.

  1. Minimum content sizing of flex items not honored
  2. Column flex items set to align-items: center overflow their container
  3. min-height on a flex container won't apply to its flex items
  4. flex shorthand declarations with unitless flex-basis values are ignored
  5. Column flex items don't always preserve intrinsic aspect ratios
  6. The default flex value has changed
  7. flex-basis doesn't account for box-sizing: border-box
  8. flex-basis doesn't support calc()
  9. Some HTML elements can't be flex containers
  10. align-items: baseline doesn't work with nested flex containers
  11. Min and max size declarations are ignored when wrapping flex items
  12. Inline elements are not treated as flex-items
  13. Importance is ignored on flex-basis when using flex shorthand
  14. Shrink-to-fit containers with flex-flow: column wrap do not contain their items
  15. Column flex items ignore margin: auto on the cross axis
  16. flex-basis cannot be animated
  17. Flex items are not correctly justified when max-width is used

Gaussian fit for Python

After losing hours trying to find my error, the problem is your formula:

sigma = sum(y*(x-mean)**2)/n

This previous formula is wrong, the correct formula is the square root of this!;

sqrt(sum(y*(x-mean)**2)/n)

Hope this helps

Reference alias (calculated in SELECT) in WHERE clause

It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.

SELECT
    vars.BalanceDue
FROM
    Entity e
OUTER APPLY (
    SELECT
        -- variables   
        BalanceDue = e.EntityTypeId,
        Variable2 = ...some..long..complex..expression..etc...
    ) vars
WHERE
    vars.BalanceDue > 0

Kudos to Syed Mehroz Alam.

Set JavaScript variable = null, or leave undefined?

There are two features of null we should understand:

  1. null is an empty or non-existent value.
  2. null must be assigned.

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.

example:-

 let a = null;
 console.log(a); //null

byte[] to file in Java

File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}

Moving average or running mean

I know this is an old question, but here is a solution that doesn't use any extra data structures or libraries. It is linear in the number of elements of the input list and I cannot think of any other way to make it more efficient (actually if anyone knows of a better way to allocate the result, please let me know).

NOTE: this would be much faster using a numpy array instead of a list, but I wanted to eliminate all dependencies. It would also be possible to improve performance by multi-threaded execution

The function assumes that the input list is one dimensional, so be careful.

### Running mean/Moving average
def running_mean(l, N):
    sum = 0
    result = list( 0 for x in l)

    for i in range( 0, N ):
        sum = sum + l[i]
        result[i] = sum / (i+1)

    for i in range( N, len(l) ):
        sum = sum - l[i-N] + l[i]
        result[i] = sum / N

    return result

Example

Assume that we have a list data = [ 1, 2, 3, 4, 5, 6 ] on which we want to compute a rolling mean with period of 3, and that you also want a output list that is the same size of the input one (that's most often the case).

The first element has index 0, so the rolling mean should be computed on elements of index -2, -1 and 0. Obviously we don't have data[-2] and data[-1] (unless you want to use special boundary conditions), so we assume that those elements are 0. This is equivalent to zero-padding the list, except we don't actually pad it, just keep track of the indices that require padding (from 0 to N-1).

So, for the first N elements we just keep adding up the elements in an accumulator.

result[0] = (0 + 0 + 1) / 3  = 0.333    ==   (sum + 1) / 3
result[1] = (0 + 1 + 2) / 3  = 1        ==   (sum + 2) / 3
result[2] = (1 + 2 + 3) / 3  = 2        ==   (sum + 3) / 3

From elements N+1 forwards simple accumulation doesn't work. we expect result[3] = (2 + 3 + 4)/3 = 3 but this is different from (sum + 4)/3 = 3.333.

The way to compute the correct value is to subtract data[0] = 1 from sum+4, thus giving sum + 4 - 1 = 9.

This happens because currently sum = data[0] + data[1] + data[2], but it is also true for every i >= N because, before the subtraction, sum is data[i-N] + ... + data[i-2] + data[i-1].

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?

Or this will work too the same way but without a save as choice:

<!DOCTYPE html>
<html>
<head>


<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
  };


  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

}//]]> 

</script>


</head>

<body>
  <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>


  <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent){
    window.parent.parent.postMessage(["resultsFrame", {
      height: document.body.getBoundingClientRect().height,
      slug: "qm5AG"
    }], "*")
  }
</script>

</body>

</html>

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How to select and change value of table cell with jQuery?

i was looking for changing second row html and you can do cascading selector

$('#tbox1 tr:nth-child(2) td').html(11111)

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Importing packages in Java

Here is the right way to do imports in Java.

import Dan.Vik;
class Kab
{
public static void main(String args[])
{
    Vik Sam = new Vik();
    Sam.disp();
}
}

You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

Ruby on Rails: how to render a string as HTML?

Or you can try CGI.unescapeHTML method.

CGI.unescapeHTML "&lt;p&gt;This is a Paragraph.&lt;/p&gt;"
=> "<p>This is a Paragraph.</p>"

Bootstrap: How do I identify the Bootstrap version?

To expound more on @vrian's answer

To view the bootstrap version of a website in your web browser, do the following:

First Method:

  • Open the website on your favourite browser
  • Press Ctrl + U to view the web page source
  • Look at the head section for a file named boostrap.min.js or boostrap.min.css. It should look like this <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
  • Then click it to open the source file
  • This will display the bootstrap version of the website. It should look like this: Bootstrap v4.4.1 (https://getbootstrap.com/)

Second Method:

  • Open the website on your favourite browser
  • Press Ctrl + Shift + I to inspect the webpage element
  • In the inspect console, click on the Style Editor tab
  • And then click on boostrap.min.css
  • This will display the bootstrap version of the website. It should look like this: Bootstrap v4.4.1 (https://getbootstrap.com/)

Bootstrap version in console

That's all

I hope this helps

Session 'app': Error Launching activity

it occured when I changed the applicationId in app gradle file. It works for me after I sync gradle.

How do I prevent and/or handle a StackOverflowException?

If you application depends on 3d-party code (in Xsl-scripts) then you have to decide first do you want to defend from bugs in them or not. If you really want to defend then I think you should execute your logic which prone to external errors in separate AppDomains. Catching StackOverflowException is not good.

Check also this question.

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

How to overwrite the output directory in spark

If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.

Have a look at the following classes: FileOutputFormat, FileOutputCommitter

In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.

I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.

The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.

How do I allow HTTPS for Apache on localhost?

I've just attempted this - I needed to test some development code on my localhost Apache on Windows. This was WAAAY more difficult than it should be. But here are the steps that managed to work after much hairpulling...

I found that my Apache install comes with openssl.exe which is helpful. If you don't have a copy, you'll need to download it. My copy was in Apache2\bin folder which is how I reference it below.

Steps:

  1. Ensure you have write permissions to your Apache conf folder
  2. Open a command prompt in Apache2\conf folder
  3. Type
    ..\bin\openssl req -config openssl.cnf -new -out blarg.csr -keyout blarg.pem
  4. You can leave all questions blank except:

    • PEM Passphrase: a temporary password such as "password"
    • Common Name: the hostname of your server

  5. When that completes, type
    ..\bin\openssl rsa -in blarg.pem -out blarg.key

  6. Generate your self-signed certificate by typing:
    ..\bin\openssl x509 -in blarg.csr -out blarg.cert -req -signkey blarg.key -days 365

  7. Open Apache's conf\httpd.conf file and ensure SSL module is enabled - there should be no hash at the start of this line:
    LoadModule ssl_module modules/mod_ssl.so

  8. Some Apache installations place the SSL config in a separate file. If so, ensure that the SSL conf file is being included. In my case I had to uncomment this line:
    Include conf/extra/httpd-ssl.conf

  9. In the SSL config httpd-ssl.conf I had to update the following lines:

    • Update
      SSLSessionCache "shmcb:C:\Program Files (x86)\Zend\Apache2/logs/ssl_scache(512000)"
      to
      SSLSessionCache "shmcb:C:/Progra\~2/Zend/Apache2/logs/ssl_scache(512000)"
      (The brackets in the path confuse the module, so we need to escape them)
    • DocumentRoot - set this to the folder for your web files
    • ServerName - the server's hostname
    • SSLCertificateFile "conf/blarg.cert"
    • SSLCertificateKeyFile "conf/blarg.key"

  10. Restart Apache.

  11. Try loading https://localhost/ in your browser.

Hopefully you made it this far. Feel free to update this post with any other helpful info.

(Screenshots courtesy of Neil Obremski and his helpful article - although now quite out-of-date.)

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

Managing jQuery plugin dependency in webpack

This works for me on the webpack.config.js

    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
    }),

in another javascript or into HTML add:

global.jQuery = require('jquery');

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

NameError: global name 'xrange' is not defined in Python 3

I solved the issue by adding this import
More info

from past.builtins import xrange

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

Run an OLS regression with Pandas Data Frame

I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas' optional dependencies before pandas' version 0.20.0 (it was used for a few things in pandas.stats.)

>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept    14.952480
B             0.401182
C             0.000352
dtype: float64
>>> print(result.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      A   R-squared:                       0.579
Model:                            OLS   Adj. R-squared:                  0.158
Method:                 Least Squares   F-statistic:                     1.375
Date:                Thu, 14 Nov 2013   Prob (F-statistic):              0.421
Time:                        20:04:30   Log-Likelihood:                -18.178
No. Observations:                   5   AIC:                             42.36
Df Residuals:                       2   BIC:                             41.19
Df Model:                           2                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept     14.9525     17.764      0.842      0.489       -61.481    91.386
B              0.4012      0.650      0.617      0.600        -2.394     3.197
C              0.0004      0.001      0.650      0.583        -0.002     0.003
==============================================================================
Omnibus:                          nan   Durbin-Watson:                   1.061
Prob(Omnibus):                    nan   Jarque-Bera (JB):                0.498
Skew:                          -0.123   Prob(JB):                        0.780
Kurtosis:                       1.474   Cond. No.                     5.21e+04
==============================================================================

Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.

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

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Is there a way to follow redirects with command line cURL?

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

How do I redirect with JavaScript?

To redirect to another page, you can use:

window.location = "http://www.yoururl.com";

SQL datetime format to date only

if you are using SQL Server use convert

e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate

more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

How to go to a specific element on page?

document.getElementById("elementID").scrollIntoView();

Same thing, but wrapping it in a function:

function scrollIntoView(eleID) {
   var e = document.getElementById(eleID);
   if (!!e && e.scrollIntoView) {
       e.scrollIntoView();
   }
}

This even works in an IFrame on an iPhone.

Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid

Access denied for root user in MySQL command-line

I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu

Fragment onResume() & onPause() is not called on backstack

The fragments onResume() or onPause() will be called only when the Activities onResume() or onPause() is called. They are tightly coupled to the Activity.

Read the Handling the Fragment Lifecycle section of this article.

How to check the maximum number of allowed connections to an Oracle database?

There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.

The number of sessions the database was configured to allow

SELECT name, value 
  FROM v$parameter
 WHERE name = 'sessions'

The number of sessions currently active

SELECT COUNT(*)
  FROM v$session

As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

How to create a batch file to run cmd as administrator

this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.

@echo off
mkdir C:\Users\cmdfolder

if echo=="Access is denied." (goto :1A) else (goto :A4)

:A1
cls 
color 0d
echo restart this program as administator

:A4
pause

"A lambda expression with a statement body cannot be converted to an expression tree"

Is objects a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database. Try this

Arr[] myArray = objects.Select(o => new Obj() { 
    Var1 = o.someVar,
    Var2 = o.var2 
}).ToArray();

Transfer files to/from session I'm logged in with PuTTY

If it is only one file, you can use following procedure (in putty):

  1. vi filename.extension (opens new file name in active folder on server),
  2. copy + mouse right click while over putty (copy and paste),
  3. edit and save. =>vi editor commands

Edit file permission with next command: chmod u+x filename.extension

What, exactly, is needed for "margin: 0 auto;" to work?

Off the top of my head, it needs a width. You need to specify the width of the container you are centering (not the parent width).

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Case insensitive string compare in LINQ-to-SQL

I tried this using Lambda expression, and it worked.

List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

How do I parse a string to a float or int?

If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:

>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Firefox 'Cross-Origin Request Blocked' despite headers

If you don't have a 'real' certificate (and thus using a self-signed one), in Firefox you can go to:

Options > Privacy & Security > (scroll to the bottom) View Certificates > Servers > Add Exception...

There, fill in the location, eg: https://www.myserver:myport

How can I compare two dates in PHP?

I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types

SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName

Why isn't .ico file defined when setting window's icon?

I had the same problem too, but I found a solution.

root.mainloop()

from tkinter import *
    
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
    
root.mainloop()

In the example, what python needed is an icon file, so when you dowload an icon as .png it won't work cause it needs an .ico file. So you need to find converters to convert your icon from png to ico.

What is the difference between YAML and JSON?

Differences:

  1. YAML, depending on how you use it, can be more readable than JSON
  2. JSON is often faster and is probably still interoperable with more systems
  3. It's possible to write a "good enough" JSON parser very quickly
  4. Duplicate keys, which are potentially valid JSON, are definitely invalid YAML.
  5. YAML has a ton of features, including comments and relational anchors. YAML syntax is accordingly quite complex, and can be hard to understand.
  6. It is possible to write recursive structures in yaml: {a: &b [*b]}, which will loop infinitely in some converters. Even with circular detection, a "yaml bomb" is still possible (see xml bomb).
  7. Because there are no references, it is impossible to serialize complex structures with object references in JSON. YAML serialization can therefore be more efficient.
  8. In some coding environments, the use of YAML can allow an attacker to execute arbitrary code.

Observations:

  1. Python programmers are generally big fans of YAML, because of the use of indentation, rather than bracketed syntax, to indicate levels.
  2. Many programmers consider the attachment of "meaning" to indentation a poor choice.
  3. If the data format will be leaving an application's environment, parsed within a UI, or sent in a messaging layer, JSON might be a better choice.
  4. YAML can be used, directly, for complex tasks like grammar definitions, and is often a better choice than inventing a new language.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

The following are some of the reasons for the hibernate.dialect not set issue. Most of these exceptions are shown in the startup log which is finally followed by the mentioned issue.

Example: In Spring boot app with Postgres DB

1. Check if the database is actually installed and its server is started.

  • org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  • java.net.ConnectException: Connection refused: connect
  • org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

2. Check if the database name is correctly mentioned.

  • org.postgresql.util.PSQLException: FATAL: database "foo" does not exist

    In application.properties file,

    spring.datasource.url = jdbc:postgresql://localhost:5432/foo
    

    but foo didn't exist. So I created the database from pgAdmin for postgres

    CREATE DATABASE foo;
    

3. Check if the host name and server port is accessible.

  • org.postgresql.util.PSQLException: Connection to localhost:5431 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  • java.net.ConnectException: Connection refused: connect

4. Check if the database credentials are correct.

  • as @Pankaj mentioned
  • org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"

    spring.datasource.username= {DB USERNAME HERE}

    spring.datasource.password= {DB PASSWORD HERE}

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

Java8: sum values from specific field of the objects in a list

You can do

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();

or (using Method reference)

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();

How do you change the value inside of a textfield flutter?

You can use the text editing controller to manipulate the value inside a textfield.

var textController = new TextEditingController();

Now, create a new textfield and set textController as the controller for the textfield as shown below.

 new TextField(controller: textController)

Now, create a RaisedButton anywhere in your code and set the desired text in the onPressed method of the RaisedButton.

new RaisedButton(
       onPressed: () {
          textController.text = "New text";
       }
    ),

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

How to find the duration of difference between two dates in java?

You can create a method like

public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}

This method will return the number of days between the 2 days.

Undefined reference to pthread_create in Linux

Both answers to this question so far are incorrect.
For Linux the correct command is:

gcc -pthread -o term term.c

In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. On a system with only libpthread.a installed,

gcc -lpthread ...

will fail to link.

can't multiply sequence by non-int of type 'float'

You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i to rate and using that instead. See the updated code below:

def nestEgVariable(salary, save, growthRates):
    SavingsRecord = []
    fund = 0
    depositPerYear = salary * save * 0.01
    #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
    for rate in growthRates:  
        #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
        fund = fund * (1 + 0.01 * rate) + depositPerYear
        SavingsRecord += [fund,]
    return SavingsRecord 


print nestEgVariable(10000,10,[3,4,5,0,3])

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the issue is resolved by adding domain name in user name as follow:

string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer; 
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);

Capturing count from an SQL query

Use SqlCommand.ExecuteScalar() and cast it to an int:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Mockito: Inject real objects into private @Autowired fields

In Addition to @Dev Blanked answer, if you want to use an existing bean that was created by Spring the code can be modified to:

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {

    @Inject
    private ApplicationContext ctx;

    @Spy
    private SomeService service;

    @InjectMocks
    private Demo demo;

    @Before
    public void setUp(){
        service = ctx.getBean(SomeService.class);
    }

    /* ... */
}

This way you don't need to change your code (add another constructor) just to make the tests work.

fatal: git-write-tree: error building trees

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

What is a tracking branch?

TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".

So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.

In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".

It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.

Let's rephrase your question to this:

What is a "Remote-tracking-branch?"

The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.


To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).

The following is an introduction/overview, but you might find this excellent article also informative.


WHAT GIT IS, AND WHAT IT'S FOR

A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.

A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.

The basic idea is to create a book so we can easily look backwards in time,

  • to compare past times, with now, or other moments in time, and
  • to re-create the past.

When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.


SNAPSHOTS AND TRACKING

tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)

In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.

Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.

Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.

One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.

For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.

This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.


COMMITS

A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:

  • an address or fixed place where we can find this commit, similar to its page number,
  • one snapshot of your project (of your file directory tree) at a given moment in time,
  • a caption or comment saying what the snapshot is of, or for,
  • the date and time of that snapshot,
  • who took the snapshot, and finally,
  • one, or more, links backwards in time to previous, related snapshots like to yesterday's snapshot, or to our parent or parents. In other words "links" are similar to pointers to the page numbers of other, older photos of myself, or when I am born to my immediate parents.

A commit is the most important part of a well organized photo album.


THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES

Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.

The git family tree structure is modeled on our own, human family trees.

In what follows to help understand links in a simple way, I'll refer to:

  • a parent-commit as simply a "parent", and
  • a child-commit as simply a "child" or "children" if plural.

You should understand this instinctively, as it is based on the tree of life:

  • A parent might have one or more children pointing back in time at them, and
  • children always have one or more parents they point to.

Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.

  • With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.

  • With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.

Line diagram of a simple, single parent chain linking backwards in time:

(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)

BRANCHES

branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)

A git branch also refers to two things:

  • a name given to a growing tip, (an identifier), and
  • the actual branch in the graph of links between commits.

More than one child pointing --at a--> parent, is what git calls "branching".

NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.

The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".

In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.

Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)

ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.

The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)

(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)

So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".

So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.

The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".

The master branch always exists.

Line diagram of: Commit1 with 2 children (or what we call a git "branch"):

                parent      children

                        +-- Commit <-- Commit <-- Commit (Branch named 'Tom')
                       /
                      v
(older) ... <-- Commit1 <-- Commit                       (Branch named 'master')    

Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.

So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.


MERGING

Children have one or more parents.

  • With just one parent this is just a simple parent <-- child commit.

  • With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.

Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):

                parents     child

           ... <-- Commit
                        v
                         \
(older) ... <-- Commit1 <-- Commit2  

REMOTE

This word is also used to mean 2 different things:

  • a remote repository, and
  • the local alias name for a remote repository, i.e. a name which points using a URL to a remote repository.

remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)

(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.

A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)

You can setup multiple remotes if you want to pull or push to multiple remote repositories.

Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).

origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)

Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.

upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia

upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)

This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.

REMOTE TRACKING BRANCH

A remote-tracking-branch is first, just a branch name, like any other branch name.

It points at a local growing tip, i.e. a recent commit in your local git repository.

But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.

remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)

Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.

Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.


TRACKING IN ACTION

First we begin tracking a file with git.

enter image description here

Here are the basic commands involved with file tracking:

$ mkdir mydir &&  cd mydir &&  git init             # create a new git repository

$ git branch                                        # this initially reports no branches
                                                    #  (IMHO this is a bug!)

$ git status -bs       # -b = branch; -s = short    # master branch is empty
## No commits yet on master

# ...
$ touch foo                                         # create a new file

$ vim foo                                           # modify it (OPTIONAL)


$ git add         foo; commit -m 'your description'  # start tracking foo 
$ git rm  --index foo; commit -m 'your description'  # stop  tracking foo 
$ git rm          foo; commit -m 'your description'  # stop  tracking foo & also delete foo

REMOTE TRACKING IN ACTION

$ git pull    # Essentially does:  get fetch; git merge    # to update our clone

There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.

Android: upgrading DB version and adding new table

1. About onCreate() and onUpgrade()

onCreate(..) is called whenever the app is freshly installed. onUpgrade is called whenever the app is upgraded and launched and the database version is not the same.

2. Incrementing the db version

You need a constructor like:

MyOpenHelper(Context context) {
   super(context, "dbname", null, 2); // 2 is the database version
}

IMPORTANT: Incrementing the app version alone is not enough for onUpgrade to be called!

3. Don't forget your new users!

Don't forget to add

database.execSQL(DATABASE_CREATE_color);

to your onCreate() method as well or newly installed apps will lack the table.

4. How to deal with multiple database changes over time

When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion:

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   switch(oldVersion) {
   case 1:
       db.execSQL(DATABASE_CREATE_color);
       // we want both updates, so no break statement here...
   case 2:
       db.execSQL(DATABASE_CREATE_someothertable); 
   }
}

This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)

5. Keeping your revision numbers under control while developing

And finally... calling

adb uninstall <yourpackagename>

totally uninstalls the app. When you install again, you are guaranteed to hit onCreate which keeps you from having to keep incrementing the database version into the stratosphere as you develop...

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Key hash for Android-Facebook app

The simplest solution I have found is this:

  • Open up Log Cat
  • Try and access Facebook with the Android SDK
  • Look for the line in the log that looks like this:

    04-24 01:14:08.605: I/System.out(31395): invalid_key:Android key mismatch. 
    Your key "abcdefgHIJKLMN+OPqrstuvwzyz" does not match the allowed keys specified in your
    application settings. Check your application settings at 
    http://www.facebook.com/developers
    
  • Copy "abcdefgHIJKLMN+OPqrstuvwzyz" and paste it into the Facebook Android Key Hash area.

How to get year/month/day from a date object?

Here is a cleaner way getting Year/Month/Day with template literals:

_x000D_
_x000D_
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
_x000D_
_x000D_

How to get input type using jquery?

You could do the following:

var inputType = $('#inputid').attr('type');

Node.js + Nginx - What now?

The best and simpler setup with Nginx and Nodejs is to use Nginx as an HTTP and TCP load balancer with proxy_protocol enabled. In this context, Nginx will be able to proxy incoming requests to nodejs, and also terminate SSL connections to the backend Nginx server(s), and not to the proxy server itself. (SSL-PassThrough)

In my opinion, there is no point in giving non-SSL examples, since all web apps are (or should be) using secure environments.

Example config for the proxy server, in /etc/nginx/nginx.conf

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
  upstream webserver-http {
    server 192.168.1.4; #use a host port instead if using docker
    server 192.168.1.5; #use a host port instead if using docker
  }
  upstream nodejs-http {
    server 192.168.1.4:8080; #nodejs listening port
    server 192.168.1.5:8080; #nodejs listening port
  }
  server {
    server_name example.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Connection "";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://webserver-http$request_uri;
    }
  }
  server {
    server_name node.example.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      add_header       X-Upstream $upstream_addr;
      proxy_redirect     off;
      proxy_connect_timeout  300;
      proxy_http_version 1.1;
      proxy_buffers 16 16k;
      proxy_buffer_size 16k;
      proxy_cache_background_update on;
      proxy_pass http://nodejs-http$request_uri;
    }
  }
}
stream {
  upstream webserver-https {
    server 192.168.1.4:443; #use a host port instead if using docker
    server 192.168.1.5:443; #use a host port instead if using docker
  }

  server {
    proxy_protocol on;
    tcp_nodelay on;
    listen 443;
    proxy_pass webserver-https;
  }
  log_format proxy 'Protocol: $protocol - $status $bytes_sent $bytes_received $session_time';
  access_log  /var/log/nginx/access.log proxy;
  error_log /var/log/nginx/error.log debug;
}

Now, let's handle the backend webserver. /etc/nginx/nginx.conf:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
load_module /etc/nginx/modules/ngx_http_geoip2_module.so; # GeoIP2
events {
    worker_connections  1024;
}
http {
    variables_hash_bucket_size 64;
    variables_hash_max_size 2048;
    server_tokens off;
    sendfile    on;
    tcp_nopush  on;
    tcp_nodelay on;
    autoindex off;
    keepalive_timeout  30;
    types_hash_bucket_size 256;
    client_max_body_size 100m;
    server_names_hash_bucket_size 256;
    include         mime.types;
    default_type    application/octet-stream;
    index  index.php index.html index.htm;
    # GeoIP2
    log_format  main    'Proxy Protocol Address: [$proxy_protocol_addr] '
                        '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

    # GeoIP2
    log_format  main_geo    'Original Client Address: [$realip_remote_addr]- Proxy Protocol Address: [$proxy_protocol_addr] '
                            'Proxy Protocol Server Address:$proxy_protocol_server_addr - '
                            '"$request" $remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '$geoip2_data_country_iso $geoip2_data_country_name';

    access_log  /var/log/nginx/access.log  main_geo; # GeoIP2
#===================== GEOIP2 =====================#
    geoip2 /usr/share/geoip/GeoLite2-Country.mmdb {
        $geoip2_metadata_country_build  metadata build_epoch;
        $geoip2_data_country_geonameid  country geoname_id;
        $geoip2_data_country_iso        country iso_code;
        $geoip2_data_country_name       country names en;
        $geoip2_data_country_is_eu      country is_in_european_union;
    }
    #geoip2 /usr/share/geoip/GeoLite2-City.mmdb {
    #   $geoip2_data_city_name city names en;
    #   $geoip2_data_city_geonameid city geoname_id;
    #   $geoip2_data_continent_code continent code;
    #   $geoip2_data_continent_geonameid continent geoname_id;
    #   $geoip2_data_continent_name continent names en;
    #   $geoip2_data_location_accuracyradius location accuracy_radius;
    #   $geoip2_data_location_latitude location latitude;
    #   $geoip2_data_location_longitude location longitude;
    #   $geoip2_data_location_metrocode location metro_code;
    #   $geoip2_data_location_timezone location time_zone;
    #   $geoip2_data_postal_code postal code;
    #   $geoip2_data_rcountry_geonameid registered_country geoname_id;
    #   $geoip2_data_rcountry_iso registered_country iso_code;
    #   $geoip2_data_rcountry_name registered_country names en;
    #   $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
    #   $geoip2_data_region_geonameid subdivisions 0 geoname_id;
    #   $geoip2_data_region_iso subdivisions 0 iso_code;
    #   $geoip2_data_region_name subdivisions 0 names en;
   #}

#=================Basic Compression=================#
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/css text/xml text/plain application/javascript image/jpeg image/png image/gif image/x-icon image/svg+xml image/webp application/font-woff application/json application/vnd.ms-fontobject application/vnd.ms-powerpoint;
    gzip_static on;
    
    include /etc/nginx/sites-enabled/example.com-https.conf;
}

Now, let's configure the virtual host with this SSL and proxy_protocol enabled config at /etc/nginx/sites-available/example.com-https.conf:

server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name 192.168.1.4; #Your current server ip address. It will redirect to the domain name.
    listen 80;
    listen 443 ssl http2;
    listen [::]:80;
    listen [::]:443 ssl http2;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name  example.com;
    listen       *:80;
    return 301   https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name www.example.com;
    listen 80;
    listen 443 http2;
    listen [::]:80;
    listen [::]:443 ssl http2 ;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    return 301 https://example.com$request_uri;
}
server {
    real_ip_header proxy_protocol;
    set_real_ip_from 192.168.1.1; #proxy server ip address
    #set_real_ip_from proxy; #proxy container hostname if you are using docker
    server_name example.com;
    listen 443 proxy_protocol ssl http2;
    listen [::]:443 proxy_protocol ssl http2;
    root /var/www/html;
    charset UTF-8;
    add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy no-referrer;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    keepalive_timeout   70;
    ssl_buffer_size 1400;
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=86400;
    resolver_timeout 10;
    ssl_certificate     /etc/nginx/certs/example.com.crt;
    ssl_certificate_key /etc/nginx/certs/example.com.key;
    ssl_trusted_certificate /etc/nginx/certs/example.com.crt;
location ~* \.(jpg|jpe?g|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm|htc|css|js|otf|eot|svg|ttf|woff|woff2)(\?ver=[0-9.]+)?$ {
    expires modified 1M;
    add_header Access-Control-Allow-Origin '*';
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    access_log off;
    }
    location ~ /.well-known { #For issuing LetsEncrypt Certificates
        allow all;
    }
location / {
    index index.php;
    try_files $uri $uri/ /index.php?$args;
    }
error_page  404    /404.php;

location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_index   index.php;
    fastcgi_pass    unix:/tmp/php7-fpm.sock;
    #fastcgi_pass    php-container-hostname:9000; (if using docker)
    fastcgi_pass_request_headers on;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_ignore_client_abort off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_request_buffering on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    include fastcgi_params;
}
location = /robots.txt {
    access_log off;
    log_not_found off;
    }
location ~ /\. {
    deny  all;
    access_log off;
    log_not_found off;
    }
}

And lastly, a sample of 2 nodejs webservers: First server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.4");
console.log('Server running at http://192.168.1.4:8080/');

Second server:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.5");
console.log('Server running at http://192.168.1.5:8080/');

Now everything should be perfectly working and load-balanced.

A while back i wrote about How to set up Nginx as a TCP load balancer in Docker. Check it out if you are using Docker.

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

Setting selected option in laravel form

Just Simply paste this code you will get the desired output that you needed.

 {{ Form::select ('myselect', ['1' => 'Item 1', '2' => 'Item 2'], 2 , ['id' =>'myselect']) }}` `

C - freeing structs

free is not enough, free just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL after free.

Ex:

if (testPerson) {
    free(testPerson);
    testPerson = NULL;
}

struct is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0 so the address of first struct's member is same as the address of struct.

C# Creating an array of arrays

I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.

How to show full column content in a Spark Dataframe?

Within Databricks you can visualize the dataframe in a tabular format. With the command:

display(results)

It will look like

enter image description here

Safest way to convert float to integer in python?

Combining two of the previous results, we have:

int(round(some_float))

This converts a float to an integer fairly dependably.

What does <T> (angle brackets) mean in Java?

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

Best way to check for null values in Java?

  • Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
  • Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.

jQuery animated number counter from zero to value

You can get the element itself in .each(), try this instead of using this

$('.Count').each(function (index, value) {
    jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            value.text(Math.ceil(this.Counter));
        }
    });
});

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

How to remove non-alphanumeric characters?

Regular expression is your answer.

$str = preg_replace('/[^a-z\d ]/i', '', $str);
  • The i stands for case insensitive.
  • ^ means, does not start with.
  • \d matches any digit.
  • a-z matches all characters between a and z. Because of the i parameter you don't have to specify a-z and A-Z.
  • After \d there is a space, so spaces are allowed in this regex.

python time + timedelta equivalent

This is a bit nasty, but:

from datetime import datetime, timedelta

now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()

Detecting arrow key presses in JavaScript

That's shorter.

function IsArrows (e) { return (e.keyCode >= 37 && e.keyCode <= 40); }

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I ran into a same problem. I was running portable version of android studio so downloaded a package from https://developer.android.com/studio/#downloads and installed it, and like that, done!

VS Code - Search for text in all files in a directory

If you have a directory open in VSCode, and want to search a subdirectory, then either:

  • ctrl-shift-F then in the files to include field enter the path with a leading ./,

or

  • ctrl-shift-E to open the Explorer, right click the directory you want to search, and select the Find in Folder... option.

Compression/Decompression string with C#

The code to compress/decompress a string

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

static void Main(string[] args) {
    byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
    string r2 = Unzip(r1);
}

Remember that Zip returns a byte[], while Unzip returns a string. If you want a string from Zip you can Base64 encode it (for example by using Convert.ToBase64String(r1)) (the result of Zip is VERY binary! It isn't something you can print to the screen or write directly in an XML)

The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo.

IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose() of the GZipStream before inspecting the output stream (e.g., mso.ToArray()). This is done with the using() { } block above. Note that the GZipStream is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose() of the GZipStream before attempting to access the data.

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

If you are using cPanel you should just click the wee box that allows you to send to external servers by SMTP.

Login to CPanel > Tweak Settings > All> "Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak)"

As answered here:

"Password not accepted from server: 535 Incorrect authentication data" when sending with GMail and phpMailer

source command not found in sh shell

In Bourne shell(sh), use the . command to source a file

. filename

Declaring a variable and setting its value from a SELECT query in Oracle

Not entirely sure what you are after but in PL/SQL you would simply

DECLARE
  v_variable INTEGER;
BEGIN
  SELECT mycolumn
    INTO v_variable
    FROM myTable;
END;

Ollie.

How do I duplicate a line or selection within Visual Studio Code?

This keymap will duplicate the current line if nothing is selected or duplicate the selected words.

  1. Access:

    File/Preferences/Keyboard shortcuts

  2. In the right top corner, click on Open Keyboard Shortcuts (JSON).

  3. Insert this keymap:

     {
       "key": "shift+alt+d",
       "command": "editor.action.duplicateSelection"
     }
    
  4. Use alt+arrows up/down to move the line (Default behaviour of VS Code).

Column calculated from another column?

MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.

https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns

How to center form in bootstrap 3

The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.

Convert pem key to ssh-rsa format

I did with

ssh-keygen -i -f $sshkeysfile >> authorized_keys

Credit goes here

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

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

Is the problem with SUM(billableDuration)? To find out, try commenting out that line and see if it works.

It could be that the sum is exceeding the maximum int. If so, try replacing it with SUM(CAST(billableDuration AS BIGINT)).

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

Is it possible to animate scrollTop with jQuery?

But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles

How to list the properties of a JavaScript object?

This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

Defining constant string in Java?

Typically you'd define this toward the top of a class:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

Of course, use the appropriate member visibility (public/private/protected) based on where you use this constant.

img src SVG changing the styles with CSS

Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No javascript needed

How to parse an RSS feed using JavaScript?

For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.

Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:

Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.

My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.

Why java.security.NoSuchProviderException No such provider: BC?

My experience with this was that when I had this in every execution it was fine using the provider as a string like this

Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");

But when I optimized and put the following in the constructor:

   if(bounctCastleProvider == null) {
      bounctCastleProvider = new BouncyCastleProvider();
    }

    if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
      Security.addProvider(bouncyCastleProvider);
    }

Then I had to use provider like this or I would get the above error:

new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);

I am using bcpkix-jdk15on version 1.65

For each row in an R dataframe

You can use the by() function:

by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)

But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

I am working with Visual studio 2010, if you would like to split your files to .h and .cpp, include your cpp header at the end of the .h file

PHP Notice: Undefined offset: 1 with array when reading data

This is a "PHP Notice", so you could in theory ignore it. Change php.ini:

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

To

error_reporting = E_ALL & ~E_NOTICE

This show all errors, except for notices.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Python 101: Can't open file: No such file or directory

From your question, you are running python2.7 and Cygwin.

Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.

Set the Python Environmental variables appropriately , for instance in my case:

PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib

In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows

/usr/bin/pydoc

Replace /usr/bin/pydoc with

#! /bin/bash
 /cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat

Then add this to $PY_HOME/Scripts/pydoc.bat

rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*

Now when you type in the cygwin bash prompt you should see:

$ pydoc
 pydoc - the Python documentation tool

 pydoc.py <name> ...
   Show text documentation on something.  <name> 
   may be the name of a Python keyword, topic,
   function, module, or package, or a dotted
   reference to a class or function within a
   module or module in a package.
...

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

Get the difference between two dates both In Months and days in sql

MsSql Syntax : DATEDIFF ( datepart , startdate , enddate )

Oracle: This will returns number of days

    select
  round(Second_date - First_date)  as Diff_InDays,round ((Second_date - First_date) / (30),1)  as Diff_InMonths,round ((Second_date - First_date) * (60*24),2)  as TimeIn_Minitues
from
  (
  select
    to_date('01/01/2012 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as First_date
   ,to_date('05/02/2012 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as Second_date
  from
    dual
  ) result;

Demo : http://sqlfiddle.com/#!4/c26e8/36

Add common prefix to all cells in Excel

Option 1: select the cell(s), under formatting/number/custom formatting, type in

"BOB" General

now you have a prefix "BOB" next to numbers, dates, booleans, but not next to TEXTs

Option2: As before, but use the following format

_ "BOB" @_

now you have a prefix BOB, this works even if the cell contained text

Cheers, Sudhi

Is string in array?

If you don't want to or simply can't use Linq you can also use the static Array.Exists(...); function:

https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

var arr = new string[]{"bird","foo","cat","dog"};

var catInside = Array.Exists( 
  arr, // your Array
  (s)=>{ return s == "cat"; } // the Predicate
);

When the Predicate do return true once catInside will be true as well.

Instant run in Android Studio 2.0 (how to turn off)

I had the same exact isuue with the latest Android Studio 2.3.2 and Instant Run.

here what I did : (I'll give you two ways to achive that one disable for specefic project, and second for whole android studio):

  1. if you want to disable instant-run ONLY for the project that is not compatible (i.e the one with SugarORM lib)

on root of your projct open gradle-->gradle-wrapper.properties then change the value distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

and on your project build.gradle change the value

classpath 'com.android.tools.build:gradle:2.2.3'

enter image description here

  1. If you want to disable instant-run for all project (Across Android Studio)

in older version of AS settings for instant run is

File -> Other Settings -> Default Settings ->Build,Execution,Deployment

However In most recent version of Android Studio i.e 2.3.2 , instant run settings is:

  • for Android Studio Installed on Apple devices -> Preferences... (see following image)
  • for Android Studio Installed on Linux or Windows -> in File-> Settings...

enter image description here

enter image description here


Edited: If for any reason the Instant-run settings is greyed out do this :

Help-> Find Action... 

enter image description here

and then type 'enable isntant run' and click (now you should be able to change the value in Preferences... or file->Settings... , if that was the case then this is an Android Studio bug :-)

enter image description here

What Language is Used To Develop Using Unity

Unity supports:
1. UnityScript(Is known as Javascript but includes more functionality for the Unity game engine. I think this could be very easy to learn)
2. Boo (No experience)
3. C# (I prefer this as it is useful to learn and you will be able to use this outside of unity as well. I also think it is easy to get used to)

How to set delay in android?

You can use CountDownTimer which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long) method

Have a look at this example showing a 30seconds countdown

   new CountDownTimer(30000, 1000) {
         public void onFinish() {
             // When timer is finished 
             // Execute your code here
     }

     public void onTick(long millisUntilFinished) {
              // millisUntilFinished    The amount of time until finished.
     }
   }.start();

Examples for string find in Python

you can use str.index too:

>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

How to create a foreign key in phpmyadmin

You can do it the old fashioned way... with an SQL statement that looks something like this

ALTER TABLE table_name
    ADD CONSTRAINT fk_foreign_key_name
    FOREIGN KEY (foreign_key_name)
    REFERENCES target_table(target_key_name);

This assumes the keys already exist in the relevant table

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

How to fix warning from date() in PHP"

You need to set the default timezone smth like this :

date_default_timezone_set('Europe/Bucharest');

More info about this in http://php.net/manual/en/function.date-default-timezone-set.php

Or you could use @ in front of date to suppress the warning however as the warning states it's not safe to rely on the servers default timezone

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string,

:)

How do I install boto?

Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command:

sudo apt-get install python-boto

Or you can download the boto code from their site and move into the unzipped directory to run

python setup.py install

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

How do I convert Word files to PDF programmatically?

Just wanted to add that I used Microsoft.Interop libraries, specifically ExportAsFixedFormat function which I did not see used in this thread.

using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Office.Core;

Application app;

public string CreatePDF(string path, string exportDir)
{
    Application app = new Application();
    app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
    app.Visible = true;

    var objPresSet = app.Documents;
    var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);

    var pdfFileName = Path.ChangeExtension(path, ".pdf");
    var pdfPath = Path.Combine(exportDir, pdfFileName);

    try
    {
        objPres.ExportAsFixedFormat(
            pdfPath,
            WdExportFormat.wdExportFormatPDF,
            false,
            WdExportOptimizeFor.wdExportOptimizeForPrint,
            WdExportRange.wdExportAllDocument
        );
    }
    catch
    {
        pdfPath = null;
    }
    finally
    {
        objPres.Close();
    }
    return pdfPath;
}

Convert an image to grayscale in HTML/CSS

You don't need use so many prefixes for full use, because if you choose prefix for old firefox, you don't need use prefix for new firefox.

So for full use, enough use this code:

img.grayscale {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
    filter: gray; /* IE6-9 */
    -webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */
}

img.grayscale.disabled {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
    filter: none;
    -webkit-filter: grayscale(0%);
}

SQL multiple column ordering

You can use multiple ordering on multiple condition,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

How to start mongodb shell?

In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:

$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>

Once you get > symbol in the terminal, you have entered into the MongoDB shell.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

jquery count li elements inside ul -> length?

Warning: Answers above only work most of the time!

In jQuery version 3.3.1 (haven't tested other versions)

$("#myList li").length; 

works only if your list items don't wrap. If your items wrap in the list then this code counts the number of lines occupied not the number of <li> elements.

$("#myList").children().length;

gets the actual number of <li> elements in your list not the number of lines that are occupied.

JavaScript and getElementById for multiple elements with the same ID

Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:

function whywouldyoudothis() {
    var n = document.getElementById("non-unique-id");
    var a = [];
    var i;
    while(n) {
        a.push(n);
        n.id = "a-different-id";
        n = document.getElementById("non-unique-id");
    }

    for(i = 0;i < a.length; ++i) {
        a[i].id = "non-unique-id";      
    }
    return a;
}

However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.

EDIT: Given a valid document, the same effect could be achieved thus:

function getElementsById(id) {
  return [document.getElementById(id)];
}

Multiple argument IF statement - T-SQL

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

Adding value labels on a matplotlib bar chart

Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:

# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]

freq_series = pd.Series(frequencies)

y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read

rects = ax.patches

# For each bar: Place a label
for rect in rects:
    # Get X and Y placement of label from rect.
    x_value = rect.get_width()
    y_value = rect.get_y() + rect.get_height() / 2

    # Number of points between bar and label. Change to your liking.
    space = 5
    # Vertical alignment for positive values
    ha = 'left'

    # If value of bar is negative: Place label left of bar
    if x_value < 0:
        # Invert space to place label to the left
        space *= -1
        # Horizontally align label at right
        ha = 'right'

    # Use X value as label and format number with one decimal place
    label = "{:.1f}".format(x_value)

    # Create annotation
    plt.annotate(
        label,                      # Use `label` as label
        (x_value, y_value),         # Place label at end of the bar
        xytext=(space, 0),          # Horizontally shift label by `space`
        textcoords="offset points", # Interpret `xytext` as offset in points
        va='center',                # Vertically center label
        ha=ha)                      # Horizontally align label differently for
                                    # positive and negative values.

plt.savefig("image.png")

horizontal bar plot with annotations

Type safety: Unchecked cast

The solution to avoid the unchecked warning:

class MyMap extends HashMap<String, String> {};
someMap = (MyMap)getApplicationContext().getBean("someMap");

Python equivalent of a given wget command

I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...

Here's what I came up with:

python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"

That's the one-liner, here's it a little more readable:

import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)

This worked for downloading a tarball. I was able to extract the package and download it after downloading.

EDIT:

To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint package, but this was tested on my machine and works fine:

#!/usr/bin/env python

from clint.textui import progress
import requests

fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname

r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
    total_length = int(r.headers.get('content-length'))
    for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
        if chunk:
            f.write(chunk)
            f.flush()

Creating a 3D sphere in Opengl using Visual C++

Here's the code:

glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();

Android: ScrollView vs NestedScrollView

In addition to the nested scrolling NestedScrollView added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener. Adding a OnScrollChangeListener to the original ScrollView below API 23 required subclassing ScrollView or messing around with the ViewTreeObserver of the ScrollView which often means even more work than subclassing. With NestedScrollView it can be done using the build-in setter.

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

Sum all values in every column of a data.frame in R

You can use function colSums() to calculate sum of all values. [,-1] ensures that first column with names of people is excluded.

 colSums(people[,-1])
Height Weight 
   199    425

Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:

colSums(Filter(is.numeric, people))

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using windows 7 64-bit version, then the solution is found here: http://pypi.python.org/pypi/setuptools

namely, you need to download a python script, run it, and then easy_install will work normally from commandline.

P.S. I agree with the original poster saying that this should work out of the box.

Visual Studio "Could not copy" .... during build

Make sure u close all instances wcfSvcHost and try again. It worked for me!

Git merge errors

my issue was (master|REBASE 1/1)

this command worked for me

 git rebase --skip

What is the simplest way to convert array to vector?

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

or

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.

How to capture no file for fs.readFileSync()?

I use an immediately invoked lambda for these scenarios:

const config = (() => {
  try {
    return JSON.parse(fs.readFileSync('config.json'));
  } catch (error) {
    return {};
  }
})();

async version:

const config = await (async () => {
  try {
    return JSON.parse(await fs.readFileAsync('config.json'));
  } catch (error) {
    return {};
  }
})();

What does "publicPath" in Webpack do?

in my case, i have a cdn,and i am going to place all my processed static files (js,imgs,fonts...) into my cdn,suppose the url is http://my.cdn.com/

so if there is a js file which is the orginal refer url in html is './js/my.js' it should became http://my.cdn.com/js/my.js in production environment

in that case,what i need to do is just set publicpath equals http://my.cdn.com/ and webpack will automatic add that prefix

How do I convert an object to an array?

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

$array = json_decode(json_encode($response->response->docs), true);

How to set encoding in .getJSON jQuery

Use this function to regain the utf-8 characters

function decode_utf8(s) { 
  return decodeURIComponent(escape(s)); 
}

Example: var new_Str=decode_utf8(str);

Starting the week on Monday with isoWeekday()

Here is a more generic solution for any given weekday. Working demo on jsfiddle

var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.

var startOfPeriod = moment("2013-06-23T00:00:00"),

// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
    moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
    7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;

// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);

Understanding slice notation

I got a little frustrated in not finding an online source, or Python documentation that describes precisely what slicing does.

I took Aaron Hall's suggestion, read the relevant parts of the CPython source code, and wrote some Python code that performs slicing similarly to how it's done in CPython. I've tested my code in Python 3 on millions of random tests on integer lists.

You may find the references in my code to the relevant functions in CPython helpful.

# Return the result of slicing list x
# See the part of list_subscript() in listobject.c that pertains
# to when the indexing item is a PySliceObject
def slicer(x, start=None, stop=None, step=None):
    # Handle slicing index values of None, and a step value of 0.
    # See PySlice_Unpack() in sliceobject.c, which
    # extracts start, stop, step from a PySliceObject.
    maxint = 10000000       # A hack to simulate PY_SSIZE_T_MAX
    if step == None:
        step = 1
    elif step == 0:
        raise ValueError('slice step cannot be zero')

    if start == None:
        start = maxint if step < 0 else 0
    if stop == None:
        stop = -maxint if step < 0 else maxint

    # Handle negative slice indexes and bad slice indexes.
    # Compute number of elements in the slice as slice_length.
    # See PySlice_AdjustIndices() in sliceobject.c
    length = len(x)
    slice_length = 0

    if start < 0:
        start += length
        if start < 0:
            start = -1 if step < 0 else 0
    elif start >= length:
        start = length - 1 if step < 0 else length

    if stop < 0:
        stop += length
        if stop < 0:
            stop = -1 if step < 0 else 0
    elif stop > length:
        stop = length - 1 if step < 0 else length

    if step < 0:
        if stop < start:
            slice_length = (start - stop - 1) // (-step) + 1
    else:
        if start < stop:
            slice_length = (stop - start - 1) // step + 1

    # Cases of step = 1 and step != 1 are treated separately
    if slice_length <= 0:
        return []
    elif step == 1:
        # See list_slice() in listobject.c
        result = []
        for i in range(stop - start):
            result.append(x[i+start])
        return result
    else:
        result = []
        cur = start
        for i in range(slice_length):
            result.append(x[cur])
            cur += step
        return result

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

logger configuration to log to file and print to stdout

Just get a handle to the root logger and add the StreamHandler. The StreamHandler writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler as well. Then all my logs go to both places (which is what it sounds like you want).

import logging
logging.getLogger().addHandler(logging.StreamHandler())

If you want to output to stdout instead of stderr, you just need to specify it to the StreamHandler constructor.

import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))

You could also add a Formatter to it so all your log lines have a common header.

ie:

import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

Prints to the format of:

2012-12-05 16:58:26,618 [MainThread  ] [INFO ]  my message

How to Detect Browser Back Button event - Cross Browser

My variant:

const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )

How to get child element by index in Jquery?

If you know the child element you're interested in is the first:

 $('.second').children().first();

Or to find by index:

 var index = 0
 $('.second').children().eq(index);

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Try this:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // comboBox1 is readonly
        e.SuppressKeyPress = true;
    }

Is an HTTPS query string secure?

Yes, it is. But using GET for sensitive data is a bad idea for several reasons:

  • Mostly HTTP referrer leakage (an external image in the target page might leak the password[1])
  • Password will be stored in server logs (which is obviously bad)
  • History caches in browsers

Therefore, even though Querystring is secured it's not recommended to transfer sensitive data over querystring.

[1] Although I need to note that RFC states that browser should not send referrers from HTTPS to HTTP. But that doesn't mean a bad 3rd party browser toolbar or an external image/flash from an HTTPS site won't leak it.

How do you determine the size of a file in C?

I have a function that works well with only stdio.h. I like it a lot and it works very well and is pretty concise:

size_t fsize(FILE *File) {
    size_t FSZ;
    fseek(File, 0, 2);
    FSZ = ftell(File);
    rewind(File);
    return FSZ;
}

Waiting for Target Device to Come Online

Tools - Android - Sdk manager - tab Sdk tools - install emulator 25.3.1

How to create a timeline with LaTeX?

Tim Storer wrote a more flexible and nicer looking timeline.sty (Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:

\begin{timeline}{2008}{2010}{50}{250}
  \MonthAndYearEvent{4}{2008}{First Podcast}
  \MonthAndYearEvent{7}{2008}{Private Beta}
  \MonthAndYearEvent{9}{2008}{Public Beta}
  \YearEvent{2009}{IPO?}
\end{timeline}

produces a timeline that looks like this:

2008                              2010
 · · April, 2008 First Podcast    ·
       · July, 2008 Private Beta
           · September, 2008 Public Beta
                · 2009 IPO?

Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100)) 

to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

How do I update a formula with Homebrew?

I prefer to upgrade all homebrew formulae and homebrew cask formulae.

I added a Bourne shell function to my environment for this one (I load a .bashrc)

function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
  • set -x for transparency: So that the terminal outputs whatever Homebrew is doing in the background.
  • brew update to update homebrew formulas
  • brew cleanup to remove any change left over after installations
  • brew cask upgrade --greedy will install all casks; both those with versioning information and those without

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Remove the string on the beginning of an URL

Try the following

var original = 'www.test.com';
var stripped = original.substring(4);