Programs & Examples On #Pocketpc

A Pocket PC, abbreviated P/PC or PPC, is also known by Microsoft as a 'Windows Mobile Classic device'. It is a hardware specification for a handheld-sized computer (Personal digital assistant) that runs the Microsoft 'Windows Mobile Classic' operating system. It has some of the capabilities of modern desktop PCs.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

The data members and function members that operate on the instance of the type are called instance members. The int’s ToString method (for example) are examples of instance members. By default, members are instance members. Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.

App store link for "rate/review this app"

EDIT: iOS 11 Solution

This is the solution to my original answer (see below). When using the iOS 11 the following link format will work:

https://itunes.apple.com/us/app/appName/idAPP_ID?mt=8&action=write-review

Simply replace APP_ID with your specific app ID. The key to make the link work is the country code. The link above uses the us code but it actually doesn't matter which code is used. The user will automatically be redirected to his store.

iOS 11 Update:

It seems that none of the solutions presented in the other answers to get directly to the Review Page works on iOS 11.

The problem most likely is, that an app page in the iOS 11 App Store app does NOT have a Review Tab anymore. Instead the reviews are now located directly below the description and the screenshots. Of course it could still be possible to reach this section directly (e.g. with some kind of anchor), but it seems that this is not supported / intended by Apple.

Using one of the following links does not work anymore. They still bring the users to the App Store app but only to a blank page:

itms-apps://itunes.apple.com/app/idYOUR_APP_ID?action=write-review
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=YOUR_APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software

Everyone how still uses these links should update their apps ASAP, because referring the users to a blank App Store page is most likely not what you intended.

Links which do not refer to the Review page but to the App page, still work however, e.g.

itms-apps://itunes.apple.com/app/idYOUR_APP_ID   (same as above, but without write-review parameter)

So, you can still get the users to your apps Store page, but not directly to the review section anymore. Users now have to scroll down to the review section manually to leave their feedback.

Without a question this a "great and awesome benefit for User Experience and will help developers to engage users to leave high quality reviews without annoying them". Well done Apple...

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

Can you find all classes in a package using reflection?

Aleksander Blomskøld's solution did not work for me for parameterized tests @RunWith(Parameterized.class) when using Maven. The tests were named correctly and also where found but not executed:

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running some.properly.named.test.run.with.maven.SomeTest
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.123 sec

A similar issue has been reported here.

In my case @Parameters is creating instances of each class in a package. The tests worked well when run locally in the IDE. However, when running Maven no classes where found with Aleksander Blomskøld's solution.

I did make it work with the following snipped which was inspired by David Pärsson's comment on Aleksander Blomskøld's answer:

Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
            .addUrls(ClasspathHelper.forJavaClassPath()) 
            .filterInputsBy(new FilterBuilder()
            .include(FilterBuilder.prefix(basePackage))));

Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class);

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

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

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

Javascript/jQuery: Set Values (Selection) in a multiple Select

this is error in some answers for replace |

var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);

this correction is correct but the | In the end it should look like this \|

var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

Finding last occurrence of substring in string, replacing that

I would use a regex:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]

Python matplotlib multiple bars

I know that this is about matplotlib, but using pandas and seaborn can save you a lot of time:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

enter image description here

Get the list of stored procedures created and / or modified on a particular date?

SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
     OR DATEDIFF(D,create_date, GETDATE()) < 7)

java.lang.RuntimeException: Unable to start activity ComponentInfo

    <activity
        android:name="MyBookActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.ALTERNATIVE" />
        </intent-filter>
    </activity>

where is your dot before MyBookActivity?

How to var_dump variables in twig templates?

You can edit

/vendor/twig/twig/lib/Twig/Extension/Debug.php

and change the var_dump() functions to \Doctrine\Common\Util\Debug::dump()

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

I ran into the same issue, for whatever reason Visual Studio did not update the web config when I first added the service. I found that updating the Service Reference also fixed this issue.

Steps:

  1. Navigate to the Service Reference Folder
  2. Expand it
  3. Right Click and Select update Service Reference
  4. Observe web Config be updated

How to use string.substr() function?

Possible solution without using substr()

#include<iostream>
#include<string>

using namespace std;


int main() {
    string c="12345";
    int p=0;

    for(int i=0;i<c.length();i++) {
        cout<<c[i];
        p++;

        if (p % 2 == 0 && i != c.length()-1) {
            cout<<" "<<c[i];
            p++;
        }
    }
}

How to scroll to top of the page in AngularJS?

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

Check if a row exists using old mysql_* API

$result = mysql_query("select if(exists (SELECT * FROM  preditors_assigned WHERE lecture_name='$lectureName'),'Assigned', 'Available')");

How might I convert a double to the nearest integer value?

I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.

When converting to int, simply add .5 to your value before downcasting. As downcasting to int always drops to the lower number (e.g. (int)1.7 == 1), if your number is .5 or higher, adding .5 will bring it up into the next number and your downcast to int should return the correct value. (e.g. (int)(1.8 + .5) == 2)

javascript clear field value input

Here is one solution with jQuery for browsers that don't support the placeholder attribute.

$('[placeholder]').focus(function() {
  var input = $(this);

  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = $(this);

  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur();

Found here: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

How can I check for IsPostBack in JavaScript?

You could put a hidden input on the page, and after the page loads, give it a value. Then you can check that field, if it was in the post data, it's a postback, otherwise it is not.

There were two solutions that used server side code (ASP.NET specific) posted as responses. I think it is worth pointing out that this solution is technology agnostic since it uses client side features only, which are available in all major browsers.

Mac SQLite editor

MesaSQLite is the best I've found so far.

www.desertsandsoftware.com

Looks very promising indeed.

Python ImportError: No module named wx

If you do not have wx installed on windows you can use :

 pip install wx

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

What you need is the svn 'export' command. With this you can put a file or entire directory tree in the state of another revision in another branch.

So something like

rm file #without 'svn' in front!
svn export myrepo/path/to/file@<revision> .
svn commit

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Equivalent to AssemblyInfo in dotnet core/csproj

I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this

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

did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.

I solved this by adding an entry to the existing ItemGroup

<ItemGroup>
   <Compile Remove="Common\**" />
   <Content Remove="Common\**" />
   <EmbeddedResource Remove="Common\**" />
   <None Remove="Common\**" />
   <!-- new added item -->
   <None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile action that usually comes with Assembly Info entry in proj files.

C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'

How to check Grants Permissions at Run-Time?

For Location runtime Permission

ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("yes","yes");

            } else {
                Log.d("yes","no");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}

moving changed files to another branch for check-in

Sadly this happens to me quite regularly as well and I use git stash if I realized my mistake before git commit and use git cherry-pick otherwise, both commands are explained pretty well in other answers

I want to add a clarification for git checkout targetBranch: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally

@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch

However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch (clean and throwaway changes) or git stage + git checkout targetBranch (clean and save changes), simply running git checkout targetBranch will give an error:

error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting

How to replace a string in a SQL Server Table Column

all answers are great but I just want to give you a good example

select replace('this value from table', 'table',  'table but updated')

this SQL statement will replace the existence of the word "table" (second parameter) inside the given statement(first parameter) with the third parameter

the initial value is this value from table but after executing replace function it will be this value from table but updated

and here is a real example

UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'

for example if we have this value

10.7440/perifrasis.2010.1.issue-1

it will become

10.25025/perifrasis.2010.1.issue-1

hope this gives you better visualization

What are Aggregates and PODs and how/why are they special?

POD in C++11 was basically split into two different axes here: triviality and layout. Triviality is about the relationship between an object's conceptual value and the bits of data within its storage. Layout is about... well, the layout of an object's subobjects. Only class types have layout, while all types have triviality relationships.

So here is what the triviality axis is about:

  1. Non-trivially copyable: The value of objects of such types may be more than just the binary data that are stored directly within the object.

    For example, unique_ptr<T> stores a T*; that is the totality of the binary data within the object. But that's not the totality of the value of a unique_ptr<T>. A unique_ptr<T> stores either a nullptr or a pointer to an object whose lifetime is managed by the unique_ptr<T> instance. That management is part of the value of a unique_ptr<T>. And that value is not part of the binary data of the object; it is created by the various member functions of that object.

    For example, to assign nullptr to a unique_ptr<T> is to do more than just change the bits stored in the object. Such an assignment must destroy any object managed by the unique_ptr. To manipulate the internal storage of a unique_ptr without going through its member functions would damage this mechanism, to change its internal T* without destroying the object it currently manages, would violate the conceptual value that the object possesses.

  2. Trivially copyable: The value of such objects are exactly and only the contents of their binary storage. This is what makes it reasonable to allow copying that binary storage to be equivalent to copying the object itself.

    The specific rules that define trivial copyability (trivial destructor, trivial/deleted copy/move constructors/assignment) are what is required for a type to be binary-value-only. An object's destructor can participate in defining the "value" of an object, as in the case with unique_ptr. If that destructor is trivial, then it doesn't participate in defining the object's value.

    Specialized copy/move operations also can participate in an object's value. unique_ptr's move constructor modifies the source of the move operation by null-ing it out. This is what ensures that the value of a unique_ptr is unique. Trivial copy/move operations mean that such object value shenanigans are not being played, so the object's value can only be the binary data it stores.

  3. Trivial: This object is considered to have a functional value for any bits that it stores. Trivially copyable defines the meaning of the data store of an object as being just that data. But such types can still control how data gets there (to some extent). Such a type can have default member initializers and/or a default constructor that ensures that a particular member always has a particular value. And thus, the conceptual value of the object can be restricted to a subset of the binary data that it could store.

    Performing default initialization on a type that has a trivial default constructor will leave that object with completely uninitialized values. As such, a type with a trivial default constructor is logically valid with any binary data in its data storage.

The layout axis is really quite simple. Compilers are given a lot of leeway in deciding how the subobjects of a class are stored within the class's storage. However, there are some cases where this leeway is not necessary, and having more rigid ordering guarantees is useful.

Such types are standard layout types. And the C++ standard doesn't even really do much with saying what that layout is specifically. It basically says three things about standard layout types:

  1. The first subobject is at the same address as the object itself.

  2. You can use offsetof to get a byte offset from the outer object to one of its member subobjects.

  3. unions get to play some games with accessing subobjects through an inactive member of a union if the active member is (at least partially) using the same layout as the inactive one being accessed.

Compilers generally permit standard layout objects to map to struct types with the same members in C. But there is no statement of that in the C++ standard; that's just what compilers feel like doing.

POD is basically a useless term at this point. It is just the intersection of trivial copyability (the value is only its binary data) and standard layout (the order of its subobjects is more well-defined). One can infer from such things that the type is C-like and could map to similar C objects. But the standard has no statements to that effect.


can you please elaborate following rules:

I'll try:

a) standard-layout classes must have all non-static data members with the same access control

That's simple: all non-static data members must all be public, private, or protected. You can't have some public and some private.

The reasoning for them goes to the reasoning for having a distinction between "standard layout" and "not standard layout" at all. Namely, to give the compiler the freedom to choose how to put things into memory. It's not just about vtable pointers.

Back when they standardized C++ in 98, they had to basically predict how people would implement it. While they had quite a bit of implementation experience with various flavors of C++, they weren't certain about things. So they decided to be cautious: give the compilers as much freedom as possible.

That's why the definition of POD in C++98 is so strict. It gave C++ compilers great latitude on member layout for most classes. Basically, POD types were intended to be special cases, something you specifically wrote for a reason.

When C++11 was being worked on, they had a lot more experience with compilers. And they realized that... C++ compiler writers are really lazy. They had all this freedom, but they didn't do anything with it.

The rules of standard layout are more or less codifying common practice: most compilers didn't really have to change much if anything at all to implement them (outside of maybe some stuff for the corresponding type traits).

Now, when it came to public/private, things are different. The freedom to reorder which members are public vs. private actually can matter to the compiler, particularly in debugging builds. And since the point of standard layout is that there is compatibility with other languages, you can't have the layout be different in debug vs. release.

Then there's the fact that it doesn't really hurt the user. If you're making an encapsulated class, odds are good that all of your data members will be private anyway. You generally don't expose public data members on fully encapsulated types. So this would only be a problem for those few users who do want to do that, who want that division.

So it's no big loss.

b) only one class in the whole inheritance tree can have non-static data members,

The reason for this one comes back to why they standardized standard layout again: common practice.

There's no common practice when it comes to having two members of an inheritance tree that actually store things. Some put the base class before the derived, others do it the other way. Which way do you order the members if they come from two base classes? And so on. Compilers diverge greatly on these questions.

Also, thanks to the zero/one/infinity rule, once you say you can have two classes with members, you can say as many as you want. This requires adding a lot of layout rules for how to handle this. You have to say how multiple inheritance works, which classes put their data before other classes, etc. That's a lot of rules, for very little material gain.

You can't make everything that doesn't have virtual functions and a default constructor standard layout.

and the first non-static data member cannot be of a base class type (this could break aliasing rules).

I can't really speak to this one. I'm not educated enough in C++'s aliasing rules to really understand it. But it has something to do with the fact that the base member will share the same address as the base class itself. That is:

struct Base {};
struct Derived : Base { Base b; };

Derived d;
static_cast<Base*>(&d) == &d.b;

And that's probably against C++'s aliasing rules. In some way.

However, consider this: how useful could having the ability to do this ever actually be? Since only one class can have non-static data members, then Derived must be that class (since it has a Base as a member). So Base must be empty (of data). And if Base is empty, as well as a base class... why have a data member of it at all?

Since Base is empty, it has no state. So any non-static member functions will do what they do based on their parameters, not their this pointer.

So again: no big loss.

Insert a line break in mailto body

Curiously in gmail for android %0D%0A doesn't work and <br> works:

<a href="mailto:[email protected]?subject=This%20is%20Subject&body=First line<br>Second line">
   click here to mail me
</a>

What is the use of the init() usage in JavaScript?

JavaScript doesn't have a built-in init() function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init() function for initialisation stuff.

A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.

What any given init() does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.

function init() {
  // initialisation stuff here
}

// elsewhere in code
init();

Escape double quotes for JSON in Python

Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes

How to open a PDF file in an <iframe>?

Do it like this: Remember to close iframe tag.

<iframe src="http://samplepdf.com/sample.pdf" width="800" height="600"></iframe>

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.

Provide an image for WhatsApp link sharing

I would like to draw attention to the fact that a simple <meta property="og:image" content="image.png" />, as suggested somewhere above, does not work for me (this in fact had me in a loop for weeks now). What works is either an absolute URL:
<meta property="og:image" content="https://domainname.com/image.png" />

or starting out with a slash (if the image is in the root directory):
<meta property="og:image" content="/image.png" />

(I would have added this as a comment, but I'm not allowed to yet. Moderators feel free to move this if more appropriate.)

Difference between "process.stdout.write" and "console.log" in node.js?

I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.write and console.log and I just want to mention it.

As Mauvis Leford and TK-421 pointed out, the console.log adds a line-break character at the end of the line (\n) but that's not all what it does.

The code has not changed since at least 0.10.X version and now we have a a 5.X version.

Here is the code:

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

As you can see, there is a part that says .apply(this, arguments) and that makes a big difference on functionality. It is easier to explain that with examples:

process.stdout.write has a very basic functionality, you can just write something in there, like this:

process.stdout.write("Hello World\n"); 

If you don't put the break line at the end you will get a weird character after your string, something like this:

process.stdout.write("Hello World"); //Hello World% 

(I think that means something like "the end of the program", so you will see it only if you process.stdout.write was used at the end of your file and you didn't add the break line)

On the other hand, console.log can do more.

  1. You can use it in the same way

    console.log("Hello World"); //You don't need the break line here because it was already formated and also that weird character did disappear

  2. You can write more than one string

    console.log("Hello", "World");

  3. You can make associations

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

An that's it, that added functionality is given thanks to the util.format.apply part (I could talk a lot about what exactly this does but you get my point, you can read more here).

I hope somebody find this information useful.

Location of my.cnf file on macOS

For MySQL 5.7 on Mac OS X El Capitan: /usr/local/mysql/etc/my.cnf

Copy default conf from /usr/local/mysql/support-files/my-default.cnf

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

How to determine if a list of polygon points are in clockwise order?

Another solution for this;

const isClockwise = (vertices=[]) => {
    const len = vertices.length;
    const sum = vertices.map(({x, y}, index) => {
        let nextIndex = index + 1;
        if (nextIndex === len) nextIndex = 0;

        return {
            x1: x,
            x2: vertices[nextIndex].x,
            y1: x,
            y2: vertices[nextIndex].x
        }
    }).map(({ x1, x2, y1, y2}) => ((x2 - x1) * (y1 + y2))).reduce((a, b) => a + b);

    if (sum > -1) return true;
    if (sum < 0) return false;
}

Take all the vertices as an array like this;

const vertices = [{x: 5, y: 0}, {x: 6, y: 4}, {x: 4, y: 5}, {x: 1, y: 5}, {x: 1, y: 0}];
isClockwise(vertices);

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Generic deep diff between two objects

Using Underscore, a simple diff:

var o1 = {a: 1, b: 2, c: 2},
    o2 = {a: 2, b: 1, c: 2};

_.omit(o1, function(v,k) { return o2[k] === v; })

Results in the parts of o1 that correspond but with different values in o2:

{a: 1, b: 2}

It'd be different for a deep diff:

function diff(a,b) {
    var r = {};
    _.each(a, function(v,k) {
        if(b[k] === v) return;
        // but what if it returns an empty object? still attach?
        r[k] = _.isObject(v)
                ? _.diff(v, b[k])
                : v
            ;
        });
    return r;
}

As pointed out by @Juhana in the comments, the above is only a diff a-->b and not reversible (meaning extra properties in b would be ignored). Use instead a-->b-->a:

(function(_) {
  function deepDiff(a, b, r) {
    _.each(a, function(v, k) {
      // already checked this or equal...
      if (r.hasOwnProperty(k) || b[k] === v) return;
      // but what if it returns an empty object? still attach?
      r[k] = _.isObject(v) ? _.diff(v, b[k]) : v;
    });
  }

  /* the function */
  _.mixin({
    diff: function(a, b) {
      var r = {};
      deepDiff(a, b, r);
      deepDiff(b, a, r);
      return r;
    }
  });
})(_.noConflict());

See http://jsfiddle.net/drzaus/9g5qoxwj/ for full example+tests+mixins

How to know installed Oracle Client is 32 bit or 64 bit?

The following, taken from here, was not mentioned here:

If the Oracle Client is 32 bit, it will contain a "lib" folder; but if it is a 64 bit Oracle Client it will have both "lib" and "lib32" folders.

Also, starting in Oracle 11.2.0.1, the client version for 64-bit and the Oracle client for 32-bit are shipped separately, and there is an $ORACLE_HOME/lib64 directory.

$ORACLE_HOME/lib/ ==> 32 bit $ORACLE_HOME/lib64 ==> 64 bit

Or

$ORACLE_HOME/lib/ ==> 64 bit $ORACLE_HOME/lib32 ==> 32 bit

Get a list of URLs from a site

do wget -r -l0 www.oldsite.com

Then just find www.oldsite.com would reveal all urls, I believe.

Alternatively, just serve that custom not-found page on every 404 request! I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.

Stylesheet not loaded because of MIME-type

In my case it was the execution order of tasks ran by Grunt.

It was executing the task connect that sets up the local server and automatically opens the app in a new tab before executing less and postcss that transpile styles.

Basically, I changed this:

grunt.registerTask('default', 'Start server. Process styles.', ['connect', 'less', 'postcss']);

To this:

grunt.registerTask('default', 'Process styles. Start server.', ['less', 'postcss', 'connect']);

And it worked! Hope it helps other people too.

one line if statement in php

You can use Ternary operator logic Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

Python script header


I'd suggest 3 things in the beginning of your script:

First, as already being said use environment:

#!/usr/bin/env python

Second, set your encoding:

# -*- coding: utf-8 -*-

Third, set some doc string:

"""This is a awesome
    python script!"""

And for sure I would use " " (4 spaces) for ident.
Final header will look like:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""This is a awesome
        python script!"""


Best wishes and happy coding.

Can't find file executable in your configured search path for gnc gcc compiler

I had also found this error but I have solved this problem by easy steps. If you want to solve this problem follow these steps:

Step 1: First start code block

Step 2: Go to menu bar and click on the Setting menu

Step 3: After that click on the Compiler option

Step 4: Now, a pop up window will be opened. In this window, select "GNU GCC COMPILER"

Step 5: Now go to the toolchain executables tab and select the compiler installation directory like (C:\Program Files (x86)\CodeBlocks\MinGW\bin)

Step 6: Click on the Ok.

enter image description here

Now you can remove this error by follow these steps. Sometimes you don't need to select bin folder. You need to select only (C:\Program Files (x86)\CodeBlocks\MinGW) this path but some system doesn't work this path. That's why you have to select path from C:/ to bin folder.

Thank you.

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

"Javac" doesn't work correctly on Windows 10

If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on. In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.

I restarted and checked it again in cmd ,it worked.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

How to enable or disable an anchor using jQuery?

The app I'm currently working on does it with a CSS style in combination with javascript.

a.disabled { color:gray; }

Then whenever I want to disable a link I call

$('thelink').addClass('disabled');

Then, in the click handler for 'thelink' a tag I always run a check first thing

if ($('thelink').hasClass('disabled')) return;

Enumerations on PHP

It might be as simple as

enum DaysOfWeek {
    Sunday,
    Monday,
    // ...
}

in the future.

PHP RFC: Enumerated Types

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

<context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.

How to use UTF-8 in resource properties with ResourceBundle

http://sourceforge.net/projects/eclipse-rbe/

as already stated property files should be encoded in ISO 8859-1

You can use the above plugin for eclipse IDE to make the Unicode conversion for you.

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

How to use custom packages

For a project hosted on GitHub, here's what people usually do:

github.com/
  laike9m/
    myproject/
      mylib/
        mylib.go
        ...
      main.go

mylib.go

package mylib

...

main.go

import "github.com/laike9m/myproject/mylib"

...

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

if (boolean == false) vs. if (!boolean)

Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE) instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false).

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

Ant: How to execute a command for each file in directory?

Use the <apply> task.

It executes a command once for each file. Specify the files by means of filesets or any other resource. <apply> is built-in; no additional dependency needed; no custom task implementation needed.

It's also possible to run the command only once, appending all files as arguments in one go. Use the parallel attribute to switch the behaviour.

Sorry for being late a year.

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

How to count the number of columns in a table using SQL?

Maybe something like this:

SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'

this will count number of columns in a the table FOO

You can also just

select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';

where the owner is schema and note that Table Names are upper case

Adjust UILabel height depending on the text

You can get height using below code

You have to pass

  1. text 2. font 3. label width

    func heightForLabel(text: String, font: UIFont, width: CGFloat) -> CGFloat {
    
       let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
       label.numberOfLines = 0
       label.lineBreakMode = NSLineBreakMode.byWordWrapping
       label.font = font
       label.text = text
       label.sizeToFit()
    
       return label.frame.height
    }
    

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

git branch --set-upstream-to=origin/master 

Or, if master isn't the currently checked-out branch:

git branch --set-upstream-to=origin/master master

Class has no objects member

I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".

Linter Path Edit

How to avoid annoying error "declared and not used"

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 
    Check(err)
}

Android: textview hyperlink

You could have two separate TextViews and you could align them accordingly in your layout if needed:

    Text1.setText(
        Html.fromHtml(
            "<a href=\"http://www.google.com\">google</a> "));
    Text1.setMovementMethod(LinkMovementMethod.getInstance());

    Text2.setText(
            Html.fromHtml(
                "<a href=\"http://www.stackoverflow.com\">stackoverflow</a> "));
    Text2.setMovementMethod(LinkMovementMethod.getInstance());

Then if you want to strip the "link underline". Create a class:

public class URLSpanNoUnderline extends URLSpan {
    public URLSpanNoUnderline(String url) {
        super(url);
    }
    @Override public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);
        }
}

Then add this method in your main Activity class where you have the TextViews

private void stripUnderlines(TextView textView) {
    Spannable s = new SpannableString(textView.getText());
    URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
    for (URLSpan span: spans) {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        s.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL());
        s.setSpan(span, start, end, 0);
    }
    textView.setText(s);
}

And then just call this after you initialised the TextViews (in your onCreate):

stripUnderlines(Text1);
stripUnderlines(Text2);

"unrecognized selector sent to instance" error in Objective-C

I had the same error and I discovered the following:

When you use the code

[self.refreshControl addTarget:self action:@selector(yourRefreshMethod:) forControlEvents:UIControlEventValueChanged];

You may think it's looking for the selector:

- (void)yourRefreshMethod{
    (your code here)
}

But it's actually looking for the selector:

- (void)yourRefreshMethod:(id)sender{
    (your code here)
}

That selector doesn't exist, so you get the crash.

You can change the selector to receive (id)sender in order to solve the error.

But what if you have other functions that call the refresh function without providing a sender? You need one function that works for both. Easy solution is to add another function:

- (void)yourRefreshMethodWithSender:(id)sender{
    [self yourRefreshMethod];
}

And then modify the refresh pulldown code to call that selector instead:

[self.refreshControl addTarget:self action:@selector(yourRefreshMethodWithSender:) forControlEvents:UIControlEventValueChanged];

I'm also doing the Stanford iOS course on an older Mac that can't be upgraded to the newest version of Mac OSX. So I'm still building for iOS 6.1, and this solved the problem for me.

What is the difference between JAX-RS and JAX-WS?

Can JAX-RS do Asynchronous Request like JAX-WS?

1) I don't know if the JAX-RS API includes a specific mechanism for asynchronous requests, but this answer could still change based on the client implementation you use.

Can JAX-RS access a web service that is not running on the Java platform, and vice versa?

2) I can't think of any reason it wouldn't be able to.

What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?

3) REST based architectures typically will use a lightweight data format, like JSON, to send data back and forth. This is in contrast to JAX-WS which uses XML. I don't see XML by itself so significantly heavier than JSON (which some people may argue), but with JAX-WS it's how much XML is used that ends up making REST with JSON the lighter option.

What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?

4) As stated in 3, REST architectures often use JSON to send and receive data. JAX-WS uses XML. It's not that JSON is so significantly smaller than XML by itself. It's mostly that JAX-WS specification includes lots overhead in how it communicates.

On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don't need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent.

Nginx: stat() failed (13: permission denied)

I faced this problem, I solved it to give permissions to nginx user and group something like this:

chown -R nginx:nginx /username/test/static

Display unescaped HTML in Vue.js

Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.

So for your specific example you would need:

<div id="logapp">    
    <table>
        <tbody>
            <tr v-repeat="logs">
                <td v-html="fail"></td>
                <td v-html="type"></td>
                <td v-html="description"></td>
                <td v-html="stamp"></td>
                <td v-html="id"></td>
            </tr>
        </tbody>
    </table>
</div>

Disable Drag and Drop on HTML elements?

Try preventing default on mousedown event:

<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>

or

<div onmousedown="return false">asd</div>

ActiveX component can't create object

I also meet the same error in vbscript.

Set objFSO = CreateObject("Scripting.FileSystemObject")

Solution:
Open command line, run :

regsvr32 /i "c:\windows\system32\scrrun.dll"

and it works

How do I change the font size of a UILabel in Swift?

SWIFT 3.1

Label.font = Label.font.withSize(NewValue)

How to change Maven local repository in eclipse

In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting

For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml

Depending on the Settings.xml the Local Repository gets automatically configured to the specified location. Click here for screenshot

How to programmatically set cell value in DataGridView?

If the DataGridView has been populated by DataSource = x (i.e. is databound) then you need to change the bound data, not the DataGridView cells themselves.

One way of getting to that data from a known row or column is thus:

(YourRow.DataBoundItem as DataRowView).Row['YourColumn'] = NewValue;

How to resolve the "ADB server didn't ACK" error?

i have solve this problem several times using the same steps :

1- Close Eclipse.

2- Restart your phone.

3- End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.

4- Issue kill and start command in \platform-tools\

C:\sdk\platform-tools>adb kill-server

C:\sdk\platform-tools>adb start-server

5- If it says something like 'started successfully', you are good.

but now it's doesn't work cause i have an anti-virus called "Baidu", this program have run "Baidu ADB server", finally i turn this process off and retry above steps it's work properly.

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

How do I disable a href link in JavaScript?

Try this when you dont want user to redirect on click

<a href="javascript: void(0)">I am a useless link</a>

Angular: How to download a file from HttpClient?

Using Blob as a source for an img:

template:

<img [src]="url">

component:

 public url : SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('/api/image.jpg').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

Further reference about trusting save values

How to select the Date Picker In Selenium WebDriver

From Java 8 you can use this simple method for picking a random date from the date picker

List<WebElement> datePickerDays = driver.findElements(By.tagName("td"));
datePickerDays.stream().filter(e->e.getText().equals(whichDateYouWantToClick)).findFirst().get().click();

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

How to use <md-icon> in Angular Material?

In their latest release there's a directive called md-icon

<md-icon icon="img/icons/ic_refresh_24px.svg"></md-icon>

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

JavaScript: Parsing a string Boolean value?

Why not keep it simple?

var parseBool = function(str) {
    if (typeof str === 'string' && str.toLowerCase() == 'true')
            return true;

    return (parseInt(str) > 0);
}

Android Google Maps API V2 Zoom to Current Location

    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);

        }
    });

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

How to use table variable in a dynamic sql statement?

Using Temp table solves the problem but I ran into issues using Exec so I went with the following solution of using sp_executesql:

Create TABLE #tempJoin ( Old_ID int, New_ID int);

declare @table_name varchar(128);

declare @strSQL nvarchar(3072);

set @table_name = 'Object';

--build sql sting to execute
set @strSQL='INSERT INTO '+@table_name+' SELECT '+@columns+' FROM #tempJoin CJ
                        Inner Join '+@table_name+' sourceTbl On CJ.Old_ID = sourceTbl.Object_ID'

**exec sp_executesql @strSQL;**

Render a string in HTML and preserve spaces and linebreaks

As you mentioned on @Developer 's answer, I would probably HTML-encode on user input. If you are worried about XSS, you probably never need the user's input in it's original form, so you might as well escape it (and replace spaces and newlines while you are at it).

Note that escaping on input means you should either use @Html.Raw or create an MvcHtmlString to render that particular input.

You can also try

System.Security.SecurityElement.Escape(userInput)

but I think it won't escape spaces either. So in that case, I suggest just do a .NET

System.Security.SecurityElement.Escape(userInput).Replace(" ", "&nbsp;").Replace("\n", "<br>")

on user input. And if you want to dig deeper into usability, perhaps you can do an XML parse of the user's input (or play with regular expressions) to only allow a predefined set of tags. For instance, allow

<p>, <span>, <strong>

... but don't allow

<script> or <iframe>

Searching for Text within Oracle Stored Procedures

 SELECT * FROM ALL_source WHERE UPPER(text) LIKE '%BLAH%'

EDIT Adding additional info:

 SELECT * FROM DBA_source WHERE UPPER(text) LIKE '%BLAH%'

The difference is dba_source will have the text of all stored objects. All_source will have the text of all stored objects accessible by the user performing the query. Oracle Database Reference 11g Release 2 (11.2)

Another difference is that you may not have access to dba_source.

Nth word in a string variable

Using awk

echo $STRING | awk -v N=$N '{print $N}'

Test

% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three

Failed to resolve version for org.apache.maven.archetypes

Try , It worked for = I just removed "archetypes" folder from below location

C:\Users\Lenovo.m2\repository\org\apache\maven

But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....

enter image description here

enter image description here

enter image description here

Change Proxy

 <proxy>
          <id>optional</id>
          <active>true</active>
          <protocol>http</protocol>
          <username></username>
          <password></password>
          <host>10.23.73.253</host>
          <port>8080</port>
          <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
        </proxy>

How to sort strings in JavaScript

<!doctype html>
<html>
<body>
<p id = "myString">zyxtspqnmdba</p>
<p id = "orderedString"></p>
<script>
var myString = document.getElementById("myString").innerHTML;
orderString(myString);
function orderString(str) {
    var i = 0;
    var myArray = str.split("");
    while (i < str.length){
        var j = i + 1;
        while (j < str.length) {
            if (myArray[j] < myArray[i]){
                var temp = myArray[i];
                myArray[i] = myArray[j];
                myArray[j] = temp;
            }
            j++;
        }
        i++;
    }
    var newString = myArray.join("");
    document.getElementById("orderedString").innerHTML = newString;
}
</script>
</body>
</html>

How to replace ${} placeholders in a text file?

Here's a robust Bash function that - despite using eval - should be safe to use.

All ${varName} variable references in the input text are expanded based on the calling shell's variables.

Nothing else is expanded: neither variable references whose names are not enclosed in {...} (such as $varName), nor command substitutions ($(...) and legacy syntax `...`), nor arithmetic substitutions ($((...)) and legacy syntax $[...]).

To treat a $ as a literal, \-escape it; e.g.:\${HOME}

Note that input is only accepted via stdin.

Example:

$ expandVarsStrict <<<'$HOME is "${HOME}"; `date` and \$(ls)' # only ${HOME} is expanded
$HOME is "/Users/jdoe"; `date` and $(ls)

Function source code:

expandVarsStrict(){
  local line lineEscaped
  while IFS= read -r line || [[ -n $line ]]; do  # the `||` clause ensures that the last line is read even if it doesn't end with \n
    # Escape ALL chars. that could trigger an expansion..
    IFS= read -r -d '' lineEscaped < <(printf %s "$line" | tr '`([$' '\1\2\3\4')
    # ... then selectively reenable ${ references
    lineEscaped=${lineEscaped//$'\4'{/\${}
    # Finally, escape embedded double quotes to preserve them.
    lineEscaped=${lineEscaped//\"/\\\"}
    eval "printf '%s\n' \"$lineEscaped\"" | tr '\1\2\3\4' '`([$'
  done
}

The function assumes that no 0x1, 0x2, 0x3, and 0x4 control characters are present in the input, because those chars. are used internally - since the function processes text, that should be a safe assumption.

Replace a newline in TSQL

REPLACE(@string, CHAR(13) + CHAR(10), '')

Eclipse reported "Failed to load JNI shared library"

Installing a 64-bit version of Java will solve the issue. Go to page Java Downloads for All Operating Systems

This is a problem due to the incompatibility of the Java version and the Eclipse version both should be 64 bit if you are using a 64-bit system.

Check an integer value is Null in c#

There is already a correct answer from Adam, but you have another option to refactor your code:

if (Age.GetValueOrDefault() == 0)
{
    // it's null or 0
}

How to compare files from two different branches?

Use commit hashes as this:

git diff <hash1> <hash2> <filename>

where hash1 can be any commit from any branch, the same for hash2.

What does @@variable mean in Ruby?

A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. Check out the following example; its output is in the comments at the end of the puts lines:

class Test
  @@shared = 1

  def value
    @@shared
  end

  def value=(value)
    @@shared = value
  end
end

class AnotherTest < Test; end

t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2

x = Test.new
puts "x.value is #{x.value}" # 2

a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3

You can see that @@shared is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared, with one @, would not be.

[Update]

As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class class, but only the instance of the Class class you're working with. An example:

class Polygon
  class << self
    attr_accessor :sides
  end
end

class Triangle < Polygon
  @sides = 3
end

class Rectangle < Polygon
  @sides = 4
end

class Square < Rectangle
end

class Hexagon < Polygon
  @sides = 6
end

puts "Triangle.sides:  #{Triangle.sides.inspect}"  # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides:    #{Square.sides.inspect}"    # nil
puts "Hexagon.sides:   #{Hexagon.sides.inspect}"   # 6

I included the Square example (which outputs nil) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.

Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.

Fixed size div?

You can also hard code in the dimensions in your html code as opposed to putting the desired dimensions in a style sheet

<div id="mainDiv">
    <div id="mydiv" style="height:150px; width:150px;">
    </div>
</div>

An App ID with Identifier '' is not available. Please enter a different string

In my case it wasn't letting me because I set bundle id in xcode project BEFORE creating online, so I changed temporarily in xcode, created online then changed back to normal in xcode.

How to amend a commit without changing commit message (reusing the previous one)?

just to add some clarity, you need to stage changes with git add, then amend last commit:

git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

Get user profile picture by Id

http://graph.facebook.com/" + facebookId + "/picture?type=square For instance: http://graph.facebook.com/67563683055/picture?type=square

There are also more sizes besides "square". See the docs.

Update September 2020
As Facebook have updated their docs this method is not working anymore without a token. You need to append some kind of access_token. You can find further information and how to do it correctly in the fb docs to the graph api of user picture

Requirements Change This endpoint supports App-Scoped User IDs (ASID), User IDs (UID), and Page-Scoped User IDs (PSID). Currently you can query ASIDs and UIDs with no requirements. However, beginning October 24, 2020, an access token will be required for all UID-based queries. If you query a UID and thus must include a token:

use a User access token for Facebook Login authenticated requests
use a Page access token for page-scoped requests
use an App access token for server-side requests
use a Client access token for mobile or web client-side requests

Quote of fb docs

Python append() vs. + operator on lists, why do these give different results?

The method you're looking for is extend(). From the Python documentation:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

How to make an HTML back link?

try this

<a href="javascript:history.go(-1)"> Go Back </a>

Laravel Mail::send() sending to multiple to or bcc addresses

Try this:

$toemail = explode(',', str_replace(' ', '', $request->toemail));

How to get HttpClient returning status code and response body?

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.

Why does Math.Round(2.5) return 2 instead of 3?

You should check MSDN for Math.Round:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.

You can specify the behavior of Math.Round using an overload:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3

Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2

How to get the background color code of an element in hex?

You have the color you just need to convert it into the format you want.

Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

Try This.

$stmt->bindValue(':v1', null, PDO::PARAM_NULL); // --> insert null

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

What's the difference between Cache-Control: max-age=0 and no-cache?

In my recent tests with IE8 and Firefox 3.5, it seems that both are RFC-compliant. However, they differ in their "friendliness" to the origin server. IE8 treats no-cache responses with the same semantics as max-age=0,must-revalidate. Firefox 3.5, however, seems to treat no-cache as equivalent to no-store, which sucks for performance and bandwidth usage.

Squid Cache, by default, seems to never store anything with a no-cache header, just like Firefox.

My advice would be to set public,max-age=0 for non-sensitive resources you want to have checked for freshness on every request, but still allow the performance and bandwidth benefits of caching. For per-user items with the same consideration, use private,max-age=0.

I would avoid the use of no-cache entirely, as it seems it has been bastardized by some browsers and popular caches to the functional equivalent of no-store.

Additionally, do not emulate Akamai and Limelight. While they essentially run massive caching arrays as their primary business, and should be experts, they actually have a vested interest in causing more data to be downloaded from their networks. Google might not be a good choice for emulation, either. They seem to use max-age=0 or no-cache randomly depending on the resource.

Create an instance of a class from a string

I've used this method successfully:

System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)

You'll need to cast the returned object to your desired object type.

calling Jquery function from javascript

You can't.

function(){

    function my_fun(){
           /.. some operations ../
    }
}

That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.

$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.

Of course, if you want to run this function when the DOM has fully loaded, you should do the following:

function my_fun(){
    /* some operations */
}

$(function(){
    my_fun(); //run my_fun() ondomready
});

// just js
function js_fun(){
   my_fun(); //== call my_fun() again
}

How do I send an HTML email?

If you are using Google app engine/Java, then use the following...

MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SENDER_EMAIL_ADDRESS, "Admin"));
msg.addRecipient(Message.RecipientType.TO,
                 new InternetAddress(toAddress, "user");

msg.setSubject(subject,"UTF-8");

Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(message, "text/html");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);

How to check if Location Services are enabled?

If you are using AndroidX, use below code to check Location Service is enabled or not:

fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))

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>
    )
  }
});

Parse usable Street Address, City, State, Zip from a string

There are data services that given a zip code will give you list of street names in that zip code.

Use a regex to extract Zip or City State - find the correct one or if a error get both. pull the list of streets from a data source Correct the city and state, and then street address. Once you get a valid Address line 1, city, state, and zip you can then make assumptions on address line 2..3

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

list all files in the folder and also sub folders

You can return a List instead of an array and things gets much simpler.

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 

How to install SQL Server Management Studio 2012 (SSMS) Express?

Good evening,

The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.

Cheers.

making a paragraph in html contain a text from a file

I would use javascript for this.

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState === 4 && txtFile.status == 200) {
     allText = txtFile.responseText;
  }
document.getElementById('your div id').innerHTML = allText;

This is just a code sample, would need tweaking for all browsers, etc.

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

What is the correct way to check for string equality in JavaScript?

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

Sum all the elements java arraylist

Not very hard, just use m.get(i) to get the value from the list.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum += m.get(i);
    }
    return sum;
}

No grammar constraints (DTD or XML schema) detected for the document

Try understanding the suggestion given in warning messages, it's helps sometime.

I also had the same issues, after doing some research i found the solution and fixed by adding the below line at the beginning

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>

which lead to some other issue in my case. Which i solved by reading the suggestions, which again turned into the another problem, which has been solved understanding the original cause, that the first link was broken (not found). Below are the step by step images which explains what has been done to resolve the issue completely.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

How to use Bootstrap modal using the anchor tag for Register?

You will have to modify the below line:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

modalRegister is the ID and hence requires a preceding # for ID reference in html.

So, the modified html code snippet would be as follows:

<li><a href="#" data-toggle="modal" data-target="#modalRegister">Register</a></li>

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

How to split large text file in windows?

If you have installed Git for Windows, you should have Git Bash installed, since that comes with Git.

Use the split command in Git Bash to split a file:

  • into files of size 500MB each: split myLargeFile.txt -b 500m

  • into files with 10000 lines each: split myLargeFile.txt -l 10000

Tips:

  • If you don't have Git/Git Bash, download at https://git-scm.com/download

  • If you lost the shortcut to Git Bash, you can run it using C:\Program Files\Git\git-bash.exe

That's it!


I always like examples though...

Example:

enter image description here

You can see in this image that the files generated by split are named xaa, xab, xac, etc.

These names are made up of a prefix and a suffix, which you can specify. Since I didn't specify what I want the prefix or suffix to look like, the prefix defaulted to x, and the suffix defaulted to a two-character alphabetical enumeration.

Another Example:

This example demonstrates

  • using a filename prefix of MySlice (instead of the default x),
  • the -d flag for using numerical suffixes (instead of aa, ab, ac, etc...),
  • and the option -a 5 to tell it I want the suffixes to be 5 digits long:

enter image description here

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

How to view method information in Android Studio?

If you need only Parameter info then:

On Mac, it's assigned to Command+P

On Windows, it's assigned to Ctrl+P

If you need document info then:

On Mac, it's assigned to Command+Q

On Windows, it's assigned to Ctrl+Q

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

range() for floats

A solution without numpy etc dependencies was provided by kichik but due to the floating point arithmetics, it often behaves unexpectedly. As noted by me and blubberdiblub, additional elements easily sneak into the result. For example naive_frange(0.0, 1.0, 0.1) would yield 0.999... as its last value and thus yield 11 values in total.

A robust version is provided here:

def frange(x, y, jump=1.0):
    '''Range for floats.'''
    i = 0.0
    x = float(x)  # Prevent yielding integers.
    x0 = x
    epsilon = jump / 2.0
    yield x  # yield always first value
    while x + epsilon < y:
        i += 1.0
        x = x0 + i * jump
        yield x

Because the multiplication, the rounding errors do not accumulate. The use of epsilon takes care of possible rounding error of the multiplication, even though issues of course might rise in the very small and very large ends. Now, as expected:

> a = list(frange(0.0, 1.0, 0.1))
> a[-1]
0.9
> len(a)
10

And with somewhat larger numbers:

> b = list(frange(0.0, 1000000.0, 0.1))
> b[-1]
999999.9
> len(b)
10000000

The code is also available as a GitHub Gist.

How to use a WSDL file to create a WCF service (not make a call)

Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.

svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)

This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.

Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.

Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

javascript regex for special characters

This regex works well for me to validate password:

/[ !"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/

This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

In this version, month, day, and year determines which days to block on the calendar.

$(document).ready(function (){
  var d         = new Date();
  var natDays   = [[1,1,2009],[1,1,2010],[12,31,2010],[1,19,2009]];

  function nationalDays(date) {
    var m = date.getMonth();
    var d = date.getDate();
    var y = date.getFullYear();

    for (i = 0; i < natDays.length; i++) {
      if ((m == natDays[i][0] - 1) && (d == natDays[i][1]) && (y == natDays[i][2]))
      {
        return [false];
      }
    }
    return [true];
  }
  function noWeekendsOrHolidays(date) {
    var noWeekend = $.datepicker.noWeekends(date);
      if (noWeekend[0]) {
        return nationalDays(date);
      } else {
        return noWeekend;
    }
  }
  $(function() { 
    $(".datepicker").datepicker({

      minDate: new Date(d.getFullYear(), 1 - 1, 1),
      maxDate: new Date(d.getFullYear()+1, 11, 31),

      hideIfNoPrevNext: true,
      beforeShowDay: noWeekendsOrHolidays,
     });
  });
});

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

Giving a border to an HTML table row, <tr>

Absolutely! Just use

<tr style="outline: thin solid">

on which ever row you like. Here's a fiddle.

Of course, as people have mentioned, you can do this via an id, or class, or some other means if you wish.

Using new line(\n) in string and rendering the same in HTML

I had the following problem where I was fetching data from a database and wanted to display a string containing \n. None of the solutions above worked for me and I finally came up with a solution: https://stackoverflow.com/a/61484190/7251208

Can scripts be inserted with innerHTML?

For me the best way is to insert the new HTML content through innerHtml and then use

setTimeout(() => {
        var script_el = document.createElement("script")
        script_el.src = 'script-to-add.js'
        document.body.appendChild(script_el)
    }, 500)

The setTimeout is not required but it works better. This worked for me.

Best way to remove duplicate entries from a data table

Heres a easy and fast way using AsEnumerable().Distinct()

private DataTable RemoveDuplicatesRecords(DataTable dt)
{
    //Returns just 5 unique rows
    var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
    DataTable dt2 = UniqueRows.CopyToDataTable();
    return dt2;
}

My Blog Article: Remove duplicate rows from datatable

Cannot find module cv2 when using OpenCV

Try this out:

sudo ldconfig

sudo nano /etc/ld.so.conf.d/opencv.conf

and add this following line in the opencv.conf not in the command window

/usr/local/lib

Then:

sudo ldconfig

sudo nano /etc/bash.bashrc

and add this two lines in the bash.bashrc not in the command window

PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig       
export PKG_CONFIG_PATH

at last reboot your Pi sudo reboot now

and try import cv2

JavaFX Panel inside Panel auto resizing

After hours of searching and testing finally got it just after posting the question!

You can use the "AnchorPane.topAnchor, AnchorPane.bottomAnchor, AnchorPane.leftAnchor, AnchorPane.rightAnchor" fxml commands with the value "0.0" to fit/stretch/align the child elements inside a AnchorPane. So, these commands tell to child element to follow its parent while resizing.

My updated code Main.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <!--<StackPane fx:id="stackPane" ></StackPane>--> <!-- replace with the following -->
    <StackPane fx:id="stackPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>

Here is the result:

enter image description here

For api documentation: http://docs.oracle.com/javafx/2/api/javafx/scene/layout/AnchorPane.html

Convert ArrayList to String array in Android

Well in general:

List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");

String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
    namesArr[i] = names.get(i);  
}

Or better yet, using built in:

List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);

AttributeError: 'module' object has no attribute

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone

Regex to match alphanumeric and spaces

I got it:

string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);

Didn't know you could put \s in the brackets

Change package name for Android in React Native

If you are using Android Studio-

changing com.myapp to com.mycompany.myapp

  1. create a new package hierarchy com.mycompany.myapp under android/app/src/main/java

  2. Copy all classes from com.myapp to com.mycompany.myapp using Android studio GUI

  3. Android studio will take care of putting suitable package name for all copied classes. This is useful if you have some custom modules and don't want to manually replace in all the .java files.

  4. Update android/app/src/main/AndroidManifest.xml and android/app/build.gradle (replace com.myapp to com.mycompany.myapp

  5. Sync the project (gradle build)

Unix - copy contents of one directory to another

To make an exact copy, permissions, ownership, and all use "-a" with "cp". "-r" will copy the contents of the files but not necessarily keep other things the same.

cp -av Source/* Dest/

(make sure Dest/ exists first)

If you want to repeatedly update from one to the other or make sure you also copy all dotfiles, rsync is a great help:

rsync -av --delete Source/ Dest/

This is also "recoverable" in that you can restart it if you abort it while copying. I like "-v" because it lets you watch what is going on but you can omit it.

What is the difference between varchar and varchar2 in Oracle?

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.

  2. If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values. e.g.,

    name varchar(10)

will reserve 6 bytes of memory even if the name is 'Ravi__', whereas

name varchar2(10) 

will reserve space according to the length of the input string. e.g., 4 bytes of memory for 'Ravi__'.

Here, _ represents NULL.

NOTE: varchar will reserve space for null values and varchar2 will not reserve any space for null values.

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

Is there a CSS selector for elements containing certain text?

Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:

_x000D_
_x000D_
      cells = document.querySelectorAll('td');_x000D_
     console.log(cells);_x000D_
      [].forEach.call(cells, function (el) {_x000D_
     if(el.innerText.indexOf("male") !== -1){_x000D_
     //el.click(); click or any other option_x000D_
     console.log(el)_x000D_
     }_x000D_
    });
_x000D_
 <table>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>male</td>_x000D_
        <td>34</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Susanne</td>_x000D_
        <td>female</td>_x000D_
        <td>14</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

<table>
  <tr>
    <td data-content="Peter">Peter</td>
    <td data-content="male">male</td>
    <td data-content="34">34</td>
  </tr>
  <tr>
    <td data-conten="Susanne">Susanne</td>
    <td data-content="female">female</td>
    <td data-content="14">14</td>
  </tr>
</table>

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

How to run function in AngularJS controller on document ready?

Here's my attempt inside of an outer controller using coffeescript. It works rather well. Please note that settings.screen.xs|sm|md|lg are static values defined in a non-uglified file I include with the app. The values are per the Bootstrap 3 official breakpoints for the eponymous media query sizes:

xs = settings.screen.xs // 480
sm = settings.screen.sm // 768
md = settings.screen.md // 992
lg = settings.screen.lg // 1200

doMediaQuery = () ->

    w = angular.element($window).width()

    $scope.xs = w < sm
    $scope.sm = w >= sm and w < md
    $scope.md = w >= md and w < lg
    $scope.lg = w >= lg
    $scope.media =  if $scope.xs 
                        "xs" 
                    else if $scope.sm
                        "sm"
                    else if $scope.md 
                        "md"
                    else 
                        "lg"

$document.ready () -> doMediaQuery()
angular.element($window).bind 'resize', () -> doMediaQuery()

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

How to skip to next iteration in jQuery.each() util?

Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:

$(".row").each( function() {
    if ( ! leaveTheLoop ) {
        ... do stuff here ...
    }
});

Rather than actually returning like this:

$(".row").each( function() {
    if ( leaveTheLoop ) 
        return; //go to next iteration in .each()
    ... do stuff here ...
});

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Chrome desktop notification example

Check the design and API specification (it's still a draft) or check the source from (page no longer available) for a simple example: It's mainly a call to window.webkitNotifications.createNotification.

If you want a more robust example (you're trying to create your own Google Chrome's extension, and would like to know how to deal with permissions, local storage and such), check out Gmail Notifier Extension: download the crx file instead of installing it, unzip it and read its source code.

Fixing the order of facets in ggplot

There are a couple of good solutions here.

Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:

# Change this code:
facet_grid(.~size) + 
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))

This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.

How to return a list of keys from a Hash Map?

Using map.keySet(), you can get a set of keys. Then convert this set into List by:

List<String> l = new ArrayList<String>(map.keySet());

And then use l.get(int) method to access keys.

PS:- source- Most concise way to convert a Set<String> to a List<String>

Simple mediaplayer play mp3 from file path?

I use this class for Audio play. If your audio location is raw folder.

Call method for play:

new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
                        .getDetail().get(0).getAudio(),"raw", getPackageName()));

AudioPlayer.java class:

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    // mothod for raw folder (R.raw.fileName)
    public void play(Context context, int rid){
        stop();

        mMediaPlayer = MediaPlayer.create(context, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

    // mothod for other folder 
    public void play(Context context, String name) {
        stop();

        //mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}

How to delete selected text in the vi editor

I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?

Forget the mouse. To remove 5 lines, either:

  • Go to the first line and type d5d (dd deletes one line, d5d deletes 5 lines) ~or~
  • Type Shift-v to enter linewise selection mode, then move the cursor down using j (yes, use h, j, k and l to move left, down, up, right respectively, that's much more efficient than using the arrows) and type d to delete the selection.

Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?

As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.

I suggest spending some time with the Vim Tutor (run vimtutor) to get more familiar with Vim in a very didactic way.

See also

Spring not autowiring in unit tests with JUnit

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

How to identify server IP address in PHP

If you are using PHP version 5.3 or higher you can do the following:

$host= gethostname();
$ip = gethostbyname($host);

This works well when you are running a stand-alone script, not running through the web server.

best way to get the key of a key/value javascript object

I was having the same problem and this is what worked

//example of an Object
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

//How to access a single key or value
var key = Object.keys(person)[0];
var value = person.firstName;

How to validate white spaces/empty spaces? [Angular 2]

If you are using Angular Reactive Forms you can create a file with a function - a validator. This will not allow only spaces to be entered.

import { AbstractControl } from '@angular/forms';
export function removeSpaces(control: AbstractControl) {
  if (control && control.value && !control.value.replace(/\s/g, '').length) {
    control.setValue('');
  }
  return null;
}

and then in your component typescript file use the validator like this for example.

this.formGroup = this.fb.group({
  name: [null, [Validators.required, removeSpaces]]
});

How to check for registry value using VbScript

Try this. This script gets current logged in user's name & home directory:

On Error Resume Next

Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp) 

strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp) 

How to download a file over HTTP?

In 2012, use the python requests library

>>> import requests
>>> 
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760

You can run pip install requests to get it.

Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.


2015-12-30

People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including tqdm:

from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

This is essentially the implementation @kvance described 30 months ago.

Finding absolute value of a number without using Math.abs()

Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

(x + (x >> 31)) ^ (x >> 31);

This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

How can I let a user download multiple files when a button is clicked?

This was the method which worked best for me and didn't open up new tabs, but just downloaded the files/images I required:

var filesForDownload = [];
filesForDownload( { path: "/path/file1.txt", name: "file1.txt" } );
filesForDownload( { path: "/path/file2.jpg", name: "file2.jpg" } );
filesForDownload( { path: "/path/file3.png", name: "file3.png" } );
filesForDownload( { path: "/path/file4.txt", name: "file4.txt" } );

$jq('input.downloadAll').click( function( e )
{
    e.preventDefault();

    var temporaryDownloadLink = document.createElement("a");
    temporaryDownloadLink.style.display = 'none';

    document.body.appendChild( temporaryDownloadLink );

    for( var n = 0; n < filesForDownload.length; n++ )
    {
        var download = filesForDownload[n];
        temporaryDownloadLink.setAttribute( 'href', download.path );
        temporaryDownloadLink.setAttribute( 'download', download.name );

        temporaryDownloadLink.click();
    }

    document.body.removeChild( temporaryDownloadLink );
} );

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

START_STICKY and START_NOT_STICKY

  • START_STICKY: It will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand() method is NULL. This is suitable for the service which are not executing commands but running independently and waiting for the job.
  • START_NOT_STICKY: It will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService() calls. It’s the best option to avoid running a service in case if it is not necessary.
  • START_REDELIVER_INTENT: It’s same as STAR_STICKY and it recreates the service, call onStartCommand() with last intent that was delivered to the service.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Adding elements to object

If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:

var element = { quantity: quantity };
cart[id] = element;

This allows you to add multiple items to the cart like so:

cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};

// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }

first-child and last-child with IE8

Since :last-child is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child is supported, as it's defined in the CSS2.1 specification.

One possible solution is to simply give the last child a class name and style that class.

Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.

no suitable HttpMessageConverter found for response type

If you are using Spring Boot, you might want to make sure you have the Jackson dependency in your classpath. You can do this manually via:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Or you can use the web starter:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

Service vs IntentService in the Android platform

Service

  • Invoke by startService()
  • Triggered from any Thread
  • Runs on Main Thread
  • May block main (UI) thread. Always use thread within service for long task
  • Once task has done, it is our responsibility to stop service by calling stopSelf() or stopService()

IntentService

  • It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
  • Invoke via Intent
  • Triggered from Main Thread
  • Runs on the separate thread
  • Can't run the task in parallel and multiple intents are Queued on the same worker thread.

How to toggle (hide / show) sidebar div using jQuery

$('button').toggle(
function() {
    $('#B').css('left', '0')
}, function() {
    $('#B').css('left', '200px')
})

Check working example at http://jsfiddle.net/hThGb/1/

You can also see any animated version at http://jsfiddle.net/hThGb/2/

Firestore Getting documents id from collection

To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });

Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

Field 'id' doesn't have a default value?

I was getting error while ExecuteNonQuery() resolved with adding AutoIncrement to Primary Key of my table. In your case if you don't want to add primary key then we must need to assign value to primary key.

ALTER TABLE `t1` 
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;

Connecting to a network folder with username/password in Powershell

PowerShell 3 supports this out of the box now.

If you're stuck on PowerShell 2, you basically have to use the legacy net use command (as suggested earlier).

How I can get web page's content and save it into the string variable

I recommend not using WebClient.DownloadString. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM () incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!

Instead, this slight variation will work correctly with BOMs:

string ReadTextFromUrl(string url) {
    // WebClient is still convenient
    // Assume UTF8, but detect BOM - could also honor response charset I suppose
    using (var client = new WebClient())
    using (var stream = client.OpenRead(url))
    using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
        return textReader.ReadToEnd();
    }
}

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How can I see the size of a GitHub repository before cloning it?

From JavaScript, since the Github API is CORS enabled:

_x000D_
_x000D_
fetch('https://api.github.com/repos/webdev23/source_control_sentry')
  .then(v => v.json()).then((function(v){
   console.log(v['size'] + "KB")
  })
)
_x000D_
_x000D_
_x000D_

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

Python conditional assignment operator

I think what you are looking for, if you are looking for something in a dictionary, is the setdefault method:

(Pdb) we=dict()
(Pdb) we.setdefault('e',14)
14
(Pdb) we['e']
14
(Pdb) we['r']="p"
(Pdb) we.setdefault('r','jeff')
'p'
(Pdb) we['r']
'p'
(Pdb) we[e]
*** NameError: name 'e' is not defined
(Pdb) we['e']
14
(Pdb) we['q2']

*** KeyError: 'q2' (Pdb)

The important thing to note in my example is that the setdefault method changes the dictionary if and only if the key that the setdefault method refers to is not present.

How to add an extra row to a pandas dataframe

A different approach that I found ugly compared to the classic dict+append, but that works:

df = df.T

df[0] = ['1/1/2013', 'Smith','test',123]

df = df.T

df
Out[6]: 
       Date   Name Action   ID
0  1/1/2013  Smith   test  123