Programs & Examples On #Facebook php sdk

The Facebook PHP-SDK provides Facebook Platform support to your PHP - based web apps.

Getting list of Facebook friends with latest API

in the recent version of facebook sdk , facebook has disabled the feature that let you access some one friends list due to security reasons ... check the documentation to learn more ...

Composer install error - requires ext_curl when it's actually enabled

This worked for me: http://ubuntuforums.org/showthread.php?t=1519176

After installing composer using the command curl -sS https://getcomposer.org/installer | php just run a sudo apt-get update then reinstall curl with sudo apt-get install php5-curl. Then composer's installation process should work so you can finally run php composer.phar install to get the dependencies listed in your composer.json file.

Addressing localhost from a VirtualBox virtual machine

I found that 10.0.2.2:<port> works, but only if Promiscuous Mode is set correctly. After installing my VM, I went to Settings > Network > Adapter 1.

NAT is set by default, and the Promiscuous Mode dropdown is disabled. I switched from NAT to Bridged Adapter, which enabled the Promiscuous Mode dropdown, and then changed the value from "Deny" to "Allow VMs". I then switched back to NAT, which disabled Promiscuous Mode again, but retained the new value.

After only this change, I was able to launch my VM and see my host machines localhost:<port> on my VM at 10.0.2.2:<port>.

Best GUI designer for eclipse?

Old question, but have you checked out JFormDesigner?

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

PHP Create and Save a txt file to root directory

It's creating the file in the same directory as your script. Try this instead.

$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

Extracting just Month and Year separately from Pandas Datetime column

Best way found!!

the df['date_column'] has to be in date time format.

df['month_year'] = df['date_column'].dt.to_period('M')

You could also use D for Day, 2M for 2 Months etc. for different sampling intervals, and in case one has time series data with time stamp, we can go for granular sampling intervals such as 45Min for 45 min, 15Min for 15 min sampling etc.

Get the year from specified date php

Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:

$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

To all who have faced this issue/ will face it in the future:

Click on Build menu -> Select Build Variant -> restore to 'debug'

Outcomment on debuggable in module:app /* debug { debuggable true }*/

Go to Build menu -> generate signed apk -> .... -> build it

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Why are primes important in cryptography?

Most basic and general explanation: cryptography is all about number theory, and all integer numbers (except 0 and 1) are made up of primes, so you deal with primes a lot in number theory.

More specifically, some important cryptographic algorithms such as RSA critically depend on the fact that prime factorization of large numbers takes a long time. Basically you have a "public key" consisting of a product of two large primes used to encrypt a message, and a "secret key" consisting of those two primes used to decrypt the message. You can make the public key public, and everyone can use it to encrypt messages to you, but only you know the prime factors and can decrypt the messages. Everyone else would have to factor the number, which takes too long to be practical, given the current state of the art of number theory.

How to schedule a periodic task in Java?

Use Google Guava AbstractScheduledService as given below:

public class ScheduledExecutor extends AbstractScheduledService {

   @Override
   protected void runOneIteration() throws Exception {
      System.out.println("Executing....");
   }

   @Override
   protected Scheduler scheduler() {
        return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
   }

   @Override
   protected void startUp() {
       System.out.println("StartUp Activity....");
   }


   @Override
   protected void shutDown() {
       System.out.println("Shutdown Activity...");
   }

   public static void main(String[] args) throws InterruptedException {
       ScheduledExecutor se = new ScheduledExecutor();
       se.startAsync();
       Thread.sleep(15000);
       se.stopAsync();
   }
}

If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.

Python Hexadecimal

Use the format() function with a '02x' format.

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'

How can I brew link a specific version?

if @simon's answer is not working in some of the mac's please follow the below process.

If you have already installed swiftgen using the following commands:

$ brew update $ brew install swiftgen

then follow the steps below in order to run swiftgen with older version.

Step 1: brew uninstall swiftgen Step 2: Navigate to: https://github.com/SwiftGen/SwiftGen/releases and download the swiftgen with version: swiftgen-4.2.0.zip.

Unzip the package in any of the directories.

Step 3: Execute the following in a terminal:

$ mkdir -p ~/dependencies/swiftgen
$ cp -R ~/<your_directory_name>/swiftgen-4.2.0/ ~/dependencies/swiftgen
$ cd /usr/local/bin
$ ln -s ~/dependencies/swiftgen/bin/swiftgen swiftgen
$ mkdir ~/Library/Application\ Support/SwiftGen
$ ln -s ~/dependencies/swiftgen/templates/ ~/Library/Application\ Support/SwiftGen/

$ swiftgen --version

You should get: SwiftGen v0.0 (Stencil v0.8.0, StencilSwiftKit v1.0.0, SwiftGenKit v1.0.1)

enter image description here

set initial viewcontroller in appdelegate - swift

Disable Main.storyboard

General -> Deployment Info -> Main Interface -> remove `Main` 
Info.plist -> remove Key/Value for `UISceneStoryboardFile` and  `UIMainStoryboardFile`

Add Storyboard ID

Main.storyboard -> Select View Controller -> Inspectors -> Identity inspector -> Storyboard ID -> e.g. customVCStoryboardId

Swift 5 and Xcode 11

Extend UIWindow

class CustomWindow : UIWindow {
    //...
}

Edit generated by Xcode SceneDelegate.swift

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: CustomWindow!

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "customVCStoryboardId")

        window = CustomWindow(windowScene: windowScene)
        window.rootViewController = initialViewController
        window.makeKeyAndVisible()
    }

    //...
}

Python vs. Java performance (runtime speed)

Different languages do different things with different levels of efficiency.

The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.

jwt check if token expired

This is the answer if someone want to know

if (Date.now() >= exp * 1000) {
  return false;
}

Convert number of minutes into hours & minutes using PHP

function hour_min($minutes){// Total
   if($minutes <= 0) return '00 Hours 00 Minutes';
else    
   return sprintf("%02d",floor($minutes / 60)).' Hours '.sprintf("%02d",str_pad(($minutes % 60), 2, "0", STR_PAD_LEFT)). " Minutes";
}
echo hour_min(250); //Function Call will return value : 04 Hours 10 Minutes

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Add a system variable named "node", with value of your node path. It solves my problem, hope it helps.

Can you use @Autowired with static fields?

@Autowired can be used with setters so you could have a setter modifying an static field.

Just one final suggestion... DON'T

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

You might looking for the placeholder attribute which will display a grey text in the input field while empty.

From Mozilla Developer Network:

A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.

However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )

And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/

How can I use the HTML5 canvas element in IE?

Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.

I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.

I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year

Eric @ www.webkrunk.com

Deleting an SVN branch

For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)

context menu

Find the branch folder you want to delete, right-click it, and select "Delete."

deleting the folder

Enter your commit message, and you're done.

committing

Split an integer into digits to compute an ISBN checksum

Recursion version:

def int_digits(n):
    return [n] if n<10 else int_digits(n/10)+[n%10]

How to append one file to another in Linux from the shell?

Another solution:

cat file1 | tee -a file2

tee has the benefit that you can append to as many files as you like, for example:

cat file1 | tee -a file2 file3 file3

will append the contents of file1 to file2, file3 and file4.

From the man page:

-a, --append
       append to the given FILEs, do not overwrite

Using two CSS classes on one element

If you have 2 classes i.e. .indent and .font, class="indent font" works.

You dont have to have a .indent.font{} in css.

You can have the classes separate in css and still call both just using the class="class1 class2" in the html. You just need a space between one or more class names.

How to pretty print nested dictionaries?

By this way you can print it in pretty way for example your dictionary name is yasin

import json

print (json.dumps(yasin, indent=2))

or, safer:

print (json.dumps(yasin, indent=2, default=str))

No generated R.java file in my project

This is actually a bug in the tutorials code. I was having the same issue and I finally realized the issue was in the "note_edit.xml" file.

Some of the layout_heigh/width attributes were set to "match_parent" which is not a valid value, they're supposed to be set to "fill_parent".

This was throwing a bug, that was causing the generation of the R.java file to fail. So, if you're having this issue, or a similar one, check all of your xml files and make sure that none of them have any errors.

Static Initialization Blocks

So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:

1- Just initialize it when you declare the variable:

static int x = 3;

2- Have a static initializing block:

static int x;

static {
 x=3;
}

3- Have a class method (static method) that accesses the class variable and initializes it: this is the alternative to the above static block; you can write a private static method:

public static int x=initializeX();

private static int initializeX(){
 return 3;
}

Now why would you use static initializing block instead of static methods?

It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.

let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.

Note: the static blocks are called in the order they appear in the code.

Example 1:

class A{
 public static int a =f();

// this is a static method
 private static int f(){
  return 3;
 }

// this is a static block
 static {
  a=5;
 }

 public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
  System.out.print(A.a); // this will print 5
 }

}

Example 2:

class A{
 static {
  a=5;
 }
 public static int a =f();

 private static int f(){
  return 3;
 }

 public static void main(String args[]) {
  System.out.print(A.a); // this will print 3
 }

}

C# - Print dictionary

Just to close this

foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
    //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

Changes to this

foreach (KeyValuePair<DateTime, string> kvp in dictionary)
{
    //textBox3.Text += ("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
    textBox3.Text += string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

dyld: Library not loaded: @rpath/libswiftCore.dylib

The most easy and easy to ignored way : clean and rebuild.

This solved the issue after tried the answers above and did not worked.

Firebase (FCM) how to get token

Instead of this:

    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
//        Get updated InstanceID token.
//        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "Refreshed token: " + refreshedToken);
//
//        TODO: Implement this method to send any registration to your app's servers.
//        sendRegistrationToServer(refreshedToken);
//
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // [END refresh_token]

Do this:

    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // Implement this method to send token to your app's server
       sendRegistrationToServer(refreshedToken);

    }
    // [END refresh_token]

And one more thing:

You need to call sendRegistrationToServer() method which will update token on server, if you are sending push notifications from server.

UPDATE:

New Firebase token is generated (onTokenRefresh() is called) when:

  • The app deletes Instance ID
  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

How to add a .dll reference to a project in Visual Studio

Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference dialog.
Be sure that the new reference has the Copy Local = True.
The Add Reference dialog could be opened right-clicking on the References item in your project in Solution Explorer

UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)

Read about NuGet here

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Have you tried to cast it to a date, with <mydatetime>::date ?

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

Set space between divs

For folks searching for solution to set spacing between N divs, here is another approach using pseudo selectors:

div:not(:last-child) {
  margin-right: 40px;
}

You can also combine child pseudo selectors:

div:not(:first-child):not(:last-child) {
  margin-left: 20px;
  margin-right: 20px;
}

What is function overloading and overriding in php?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

Check if url contains string with JQuery

if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

How do I enable/disable log levels in Android?

Stripping out the logging with proguard (see answer from @Christopher ) was easy and fast, but it caused stack traces from production to mismatch the source if there was any debug logging in the file.

Instead, here's a technique that uses different logging levels in development vs. production, assuming that proguard is used only in production. It recognizes production by seeing if proguard has renamed a given class name (in the example, I use "com.foo.Bar"--you would replace this with a fully-qualified class name that you know will be renamed by proguard).

This technique makes use of commons logging.

private void initLogging() {
    Level level = Level.WARNING;
    try {
        // in production, the shrinker/obfuscator proguard will change the
        // name of this class (and many others) so in development, this
        // class WILL exist as named, and we will have debug level
        Class.forName("com.foo.Bar");
        level = Level.FINE;
    } catch (Throwable t) {
        // no problem, we are in production mode
    }
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (Handler handler : handlers) {
        Log.d("log init", "handler: " + handler.getClass().getName());
        handler.setLevel(level);
    }
}

How to display databases in Oracle 11g using SQL*Plus

Maybe you could use this view, but i'm not sure.

select * from v$database;

But I think It will only show you info about the current db.

Other option, if the db is running in linux... whould be something like this:

SQL>!grep SID $TNS_ADMIN/tnsnames.ora | grep -v PLSExtProc

How to implode array with key and value without foreach in PHP

I spent measurements (100000 iterations), what fastest way to glue an associative array?

Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"

We have array (for example):

$array = [
    'test0' => 344,
    'test1' => 235,
    'test2' => 876,
    ...
];

Test number one:

Use http_build_query and str_replace:

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

Test number two:

Use array_map and implode:

implode(',', array_map(
        function ($v, $k) {
            return $k.':'.$v;
        },
        $array,
        array_keys($array)
    ));

Average time to implode 1000 elements: 0.0004890081976675

Test number three:

Use array_walk and implode:

array_walk($array,
        function (&$v, $k) {
            $v = $k.':'.$v;
        }
    );
implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

Test number four:

Use foreach:

    $str = '';
    foreach($array as $key=>$item) {
        $str .= $key.':'.$item.',';
    }
    rtrim($str, ',');

Average time to implode 1000 elements: 0.00026632803902445

I can conclude that the best way to glue the array - use http_build_query and str_replace

Write single CSV file using spark-csv

If you are running Spark with HDFS, I've been solving the problem by writing csv files normally and leveraging HDFS to do the merging. I'm doing that in Spark (1.6) directly:

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs._

def merge(srcPath: String, dstPath: String): Unit =  {
   val hadoopConfig = new Configuration()
   val hdfs = FileSystem.get(hadoopConfig)
   FileUtil.copyMerge(hdfs, new Path(srcPath), hdfs, new Path(dstPath), true, hadoopConfig, null) 
   // the "true" setting deletes the source files once they are merged into the new output
}


val newData = << create your dataframe >>


val outputfile = "/user/feeds/project/outputs/subject"  
var filename = "myinsights"
var outputFileName = outputfile + "/temp_" + filename 
var mergedFileName = outputfile + "/merged_" + filename
var mergeFindGlob  = outputFileName

    newData.write
        .format("com.databricks.spark.csv")
        .option("header", "false")
        .mode("overwrite")
        .save(outputFileName)
    merge(mergeFindGlob, mergedFileName )
    newData.unpersist()

Can't remember where I learned this trick, but it might work for you.

Postgresql SELECT if string contains

In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%' there are position (reversed order of args) and strpos.

SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0

Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain % and especially _ (single char wildcard), to give no false positives.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I had the same "After Private Key filter, 0 certs were left" message and spent too much of my life trying to figure out what the message meant.

The problem was that I had installed the certificate incorrectly in the Windows Certificate store so there was no private key associated with the code signing certificate.

What I should have done was this:

  1. Using either Firefox or Internet Explorer, submit the request to the issuer. This generates a PRIVATE KEY which is stored silently by the browser (a dialog appears for a fraction of a second in Firefox). Note that other browsers may not work: your life is too short to find out if they do.

  2. Submit the request, jump through the issuer's validation hoops and loops, sacrifice a goat, pray to the gods, submit a signed statement from your great grandparents, etc.

  3. Download the certificate (.crt) and import it into the same browser. The browser now has both the private key and the certificate.

  4. Export the certificate from the browser as a Personal Information Exchange (.p12) file. You will be asked to supply a password to protect this file.

  5. Keep a backup copy of the .p12 file.

  6. Run the Certificate Manager (certmgr.msc), right click on the Personal certificate store, select All Tasks/Import... and import the .p12 file into Windows. You will be asked for the password you used to protect the file. At this point, depending upon your security requirements, you can mark the key as exportable so you can restore a copy from the Windows store. You can also mark that a password is required before use if you want to break batch scripts.

  7. Run signtool successfully, breathe a sigh of relief, and ponder how much of your life you have wasted due to bad error messages and poor or missing documentation.

How should I make my VBA code compatible with 64-bit Windows?

To write for all versions of Office use a combination of the newer VBA7 and Win64 conditional Compiler Constants.

VBA7 determines if code is running in version 7 of the VB editor (VBA version shipped in Office 2010+).

Win64 determines which version (32-bit or 64-bit) of Office is running.

#If VBA7 Then
'Code is running VBA7 (2010 or later).

     #If Win64 Then
     'Code is running in 64-bit version of Microsoft Office.
     #Else
     'Code is running in 32-bit version of Microsoft Office.
     #End If

#Else
'Code is running VBA6 (2007 or earlier).

#End If

See Microsoft Support Article for more details.

Get hours difference between two dates in Moment Js

All you need to do is pass in hours as the second parameter to moments diff function.

var a = moment([21,30,00], "HH:mm:ss")
var b = moment([09,30,00], "HH:mm:ss")
a.diff(b, 'hours') // 12

Docs: https://momentjs.com/docs/#/displaying/difference/

Example:

_x000D_
_x000D_
const dateFormat = "YYYY-MM-DD HH:mm:ss";_x000D_
// Get your start and end date/times_x000D_
const rightNow = moment().format(dateFormat);_x000D_
const thisTimeYesterday = moment().subtract(1, 'days').format(dateFormat);_x000D_
// pass in hours as the second parameter to the diff function_x000D_
const differenceInHours = moment(rightNow).diff(thisTimeYesterday, 'hours');_x000D_
_x000D_
console.log(`${differenceInHours} hours have passed since this time yesterday`);
_x000D_
<script _x000D_
  src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_

Creating a class object in c++

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.

This is wrong. A constructor must exist in order to create an object. The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated. In fact, the lifetime of an object is defined to begin when the constructor routine returns.

From Paragraph 3.8/1 of the C++11 Standard:

[...] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

Therefore, a constructor must be present.

1) What is the difference between both the way of creating class objects.

When you instantiate object with automatic storage duration, like this (where X is some class):

X x;

You are creating an object which will be automatically destroyed when it goes out of scope. On the other hand, when you do:

X* x = new X();

You are creating an object dynamically and you are binding its address to a pointer. This way, the object you created will not be destroyed when your x pointer goes out of scope.

In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics, raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).

In fact, when creating an object with new, you always have to remember destroying it with delete:

delete x;

If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:

std::shared_ptr<X> x = std::make_shared<X>();

Smart pointers take care of memory management issues, which is what gives you headache with raw pointers. Smart pointers are, in fact, almost the same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.

2) If i am creating object like Example example; how to use that in an singleton class.

You could do something like this (simplified code):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

Upgrade python without breaking yum

vim `which yum`
modify #/usr/bin/python to #/usr/bin/python2.4

Javascript call() & apply() vs bind()?

TL;DR:

In simple words, bind creates the function, call and apply executes the function whereas apply expects the parameters in array

Full Explanation

Assume we have multiplication function

function multiplication(a,b){
console.log(a*b);
}

Lets create some standard functions using bind

var multiby2 = multiplication.bind(this,2);

Now multiby2(b) is equal to multiplication(2,b);

multiby2(3); //6
multiby2(4); //8

What if I pass both the parameters in bind

var getSixAlways = multiplication.bind(this,3,2);

Now getSixAlways() is equal to multiplication(3,2);

getSixAlways();//6

even passing parameter returns 6; getSixAlways(12); //6

var magicMultiplication = multiplication.bind(this);

This create a new multiplication function and assigns it to magicMultiplication.

Oh no, we are hiding the multiplication functionality into magicMultiplication.

calling magicMultiplication returns a blank function b()

on execution it works fine magicMultiplication(6,5); //30

How about call and apply?

magicMultiplication.call(this,3,2); //6

magicMultiplication.apply(this,[5,2]); //10

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

how to count the total number of lines in a text file using python

You can use sum() with a generator expression:

with open('data.txt') as f:
    print sum(1 for _ in f)

Note that you cannot use len(f), since f is an iterator. _ is a special variable name for throwaway variables, see What is the purpose of the single underscore "_" variable in Python?.

You can use len(f.readlines()), but this will create an additional list in memory, which won't even work on huge files that don't fit in memory.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

WebSphere Application Server V7 does support Java Platform, Standard Edition (Java SE) 6 (see Specifications and API documentation in the Network Deployment (All operating systems), Version 7.0 Information Center) and it's since the release V8.5 when Java 7 has been supported.

I couldn't find the Java 6 SDK documentation, and could only consult IBM JVM Messages in Java 7 Windows documentation. Alas, I couldn't find the error message in the documentation either.

Since java.lang.UnsupportedClassVersionError is "Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.", you ran into an issue of building the application with more recent version of Java than the one supported by the runtime environment, i.e. WebSphere Application Server 7.0.

I may be mistaken, but I think that offset=6 in the message is to let you know what position caused the incompatibility issue to occur. It's irrelevant for you, for me, and for many other people, but some might find it useful, esp. when they generate bytecode themselves.

Run the versionInfo command to find out about the Installed Features of WebSphere Application Server V7, e.g.

C:\IBM\WebSphere\AppServer>.\bin\versionInfo.bat
WVER0010I: Copyright (c) IBM Corporation 2002, 2005, 2008; All rights reserved.
WVER0012I: VersionInfo reporter version 1.15.1.47, dated 10/18/11

--------------------------------------------------------------------------------
IBM WebSphere Product Installation Status Report
--------------------------------------------------------------------------------

Report at date and time February 19, 2013 8:07:20 AM EST

Installation
--------------------------------------------------------------------------------
Product Directory        C:\IBM\WebSphere\AppServer
Version Directory        C:\IBM\WebSphere\AppServer\properties\version
DTD Directory            C:\IBM\WebSphere\AppServer\properties\version\dtd
Log Directory            C:\ProgramData\IBM\Installation Manager\logs

Product List
--------------------------------------------------------------------------------
BPMPC                    installed
ND                       installed
WBM                      installed

Installed Product
--------------------------------------------------------------------------------
Name                  IBM Business Process Manager Advanced V8.0
Version               8.0.1.0
ID                    BPMPC
Build Level           20121102-1733
Build Date            11/2/12
Package               com.ibm.bpm.ADV.V80_8.0.1000.20121102_2136
Architecture          x86-64 (64 bit)
Installed Features    Non-production
                      Business Process Manager Advanced - Client (always installed)
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

Installed Product
--------------------------------------------------------------------------------
Name                  IBM WebSphere Application Server Network Deployment
Version               8.0.0.5
ID                    ND
Build Level           cf051243.01
Build Date            10/22/12
Package               com.ibm.websphere.ND.v80_8.0.5.20121022_1902
Architecture          x86-64 (64 bit)
Installed Features    IBM 64-bit SDK for Java, Version 6
                      EJBDeploy tool for pre-EJB 3.0 modules
                      Embeddable EJB container
                      Sample applications
                      Stand-alone thin clients and resource adapters
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

Installed Product
--------------------------------------------------------------------------------
Name                  IBM Business Monitor
Version               8.0.1.0
ID                    WBM
Build Level           20121102-1733
Build Date            11/2/12
Package               com.ibm.websphere.MON.V80_8.0.1000.20121102_2222
Architecture          x86-64 (64 bit)
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

--------------------------------------------------------------------------------
End Installation Status Report
--------------------------------------------------------------------------------

Using "super" in C++

Bjarne Stroustrup mentions in Design and Evolution of C++ that super as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.

Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.

After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.

Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.

So, no, this will probably never get standardized.

If you don't have a copy, Design and Evolution is well worth the cover price. Used copies can be had for about $10.

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

The big thing about SP_EXECUTESQL is that it allows you to create parameterized queries which is very good if you care about SQL injection.

Virtualbox shared folder permissions

In my case the following was necessary:

sudo chgrp vboxsf /media/sf_sharedFolder

Why do we need boxing and unboxing in C#?

In general, you typically will want to avoid boxing your value types.

However, there are rare occurances where this is useful. If you need to target the 1.1 framework, for example, you will not have access to the generic collections. Any use of the collections in .NET 1.1 would require treating your value type as a System.Object, which causes boxing/unboxing.

There are still cases for this to be useful in .NET 2.0+. Any time you want to take advantage of the fact that all types, including value types, can be treated as an object directly, you may need to use boxing/unboxing. This can be handy at times, since it allows you to save any type in a collection (by using object instead of T in a generic collection), but in general, it is better to avoid this, as you're losing type safety. The one case where boxing frequently occurs, though, is when you're using Reflection - many of the calls in reflection will require boxing/unboxing when working with value types, since the type is not known in advance.

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

How to set value in @Html.TextBoxFor in Razor syntax?

The problem is that you are using a lower case v.

You need to set it to Value and it should fix your issue:

@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })

How can I close a login form and show the main form without my application closing?

I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.

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

This should work:

[ int(x) for x in "40 1".split(" ") ]

List all kafka topics

You have a stale version of the package with commands that no longer accept zookeeper but rather bootstrap-server as the connection. Confluent will then connect with Zookeeper internally.

https://www.confluent.io/download/ (5.3 or greater)

How do I exit the results of 'git diff' in Git Bash on windows?

Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.

Run batch file from Java code

Your code is fine, but the problem is inside the batch file.

You have to show the content of the bat file, your problem is in the paths inside the bat file.

Matplotlib-Animation "No MovieWriters Available"

Had the same problem....managed to get it to work after a little while.

Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables

http://www.wikihow.com/Install-FFmpeg-on-Windows

Download from ffmpeg.org

Hope this helps someone - even after a while after the question - good luck

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

Testing for empty or nil-value string

If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

For 1. topic (Target Unreachable, identifier 'bean' resolved to null);

I checked valuable answers the @BalusC and the other sharers but I exceed the this problem like this on my scenario. After the creating a new xhtml with different name and creating bean class with different name then I wrote (not copy-paste) the codes step by step to the new bean class and new xhtml file.

Error importing SQL dump into MySQL: Unknown database / Can't create database

I create the database myself using the command line. Then try to import again, it works.

Find all special characters in a column in SQL Server 2008

select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Selenium WebDriver.get(url) does not open the URL

I had the same problem but with Chrome.

Solved it using the following steps

  1. Install Firefox/Chrome webdriver from Google
  2. Put the webdriver in Chrome's directory.

Here's the code and it worked fine

from selenium import webdriver

class InstaBot(object):
    def __init__(self):
        self.driver=webdriver.Chrome("C:\Program 
        Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure 
                                                      #it is chrome driver 
        self.driver.get("https://www.wikipedia.com")
        
        
InstaBot()

How can I specify my .keystore file with Spring Boot and Tomcat?

If you don't want to implement your connector customizer, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer. According to the README, you only have to create your keystore, configure connector.https.*, import the library and add @ComponentScan("org.ycavatars.sboot.kit"). Then you'll have HTTPS connection.

Byte[] to InputStream or OutputStream

I'm assuming you mean that 'use' means read, but what i'll explain for the read case can be basically reversed for the write case.

so you end up with a byte[]. this could represent any kind of data which may need special types of conversions (character, encrypted, etc). let's pretend you want to write this data as is to a file.

firstly you could create a ByteArrayInputStream which is basically a mechanism to supply the bytes to something in sequence.

then you could create a FileOutputStream for the file you want to create. there are many types of InputStreams and OutputStreams for different data sources and destinations.

lastly you would write the InputStream to the OutputStream. in this case, the array of bytes would be sent in sequence to the FileOutputStream for writing. For this i recommend using IOUtils

byte[] bytes = ...;//
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
FileOutputStream out = new FileOutputStream(new File(...));
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);

and in reverse

FileInputStream in = new FileInputStream(new File(...));
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
byte[] bytes = out.toByteArray();

if you use the above code snippets you'll need to handle exceptions and i recommend you do the 'closes' in a finally block.

Is there 'byte' data type in C++?

There's also byte_lite, compatible with C++98, C++11 and later.

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

How to access the correct `this` inside a callback?

First, you need to have a clear understanding of scope and behaviour of this keyword in the context of scope.

this & scope :


there are two types of scope in javascript. They are :

   1) Global Scope

   2) Function Scope

in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this keyword in global scope refers to the window object.this inside function also refers to the window object.So this will always refer to the window until we find a way to manipulate this to indicate a context of our own choosing.

--------------------------------------------------------------------------------
-                                                                              -
-   Global Scope                                                               -
-   ( globally "this" refers to window object)                                 -     
-                                                                              -
-         function outer_function(callback){                                   -
-                                                                              -
-               // outer function scope                                        -
-               // inside outer function"this" keyword refers to window object -                                                                              -
-              callback() // "this" inside callback also refers window object  -

-         }                                                                    -
-                                                                              -
-         function callback_function(){                                        -
-                                                                              -
-                //  function to be passed as callback                         -
-                                                                              -
-                // here "THIS" refers to window object also                   -
-                                                                              -
-         }                                                                    -
-                                                                              -
-         outer_function(callback_function)                                    -
-         // invoke with callback                                              -
--------------------------------------------------------------------------------

Different ways to manipulate this inside callback functions:

Here I have a constructor function called Person. It has a property called name and four method called sayNameVersion1,sayNameVersion2,sayNameVersion3,sayNameVersion4. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.

function Person(name){

    this.name = name

    this.sayNameVersion1 = function(callback){
        callback.bind(this)()
    }
    this.sayNameVersion2 = function(callback){
        callback()
    }

    this.sayNameVersion3 = function(callback){
        callback.call(this)
    }

    this.sayNameVersion4 = function(callback){
        callback.apply(this)
    }

}

function niceCallback(){

    // function to be used as callback

    var parentObject = this

    console.log(parentObject)

}

Now let's create an instance from person constructor and invoke different versions of sayNameVersionX ( X refers to 1,2,3,4 ) method with niceCallback to see how many ways we can manipulate the this inside callback to refer to the person instance.

var p1 = new Person('zami') // create an instance of Person constructor

bind :

What bind do is to create a new function with the this keyword set to the provided value.

sayNameVersion1 and sayNameVersion2 use bind to manipulate this of the callback function.

this.sayNameVersion1 = function(callback){
    callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
    callback()
}

first one bind this with callback inside the method itself.And for the second one callback is passed with the object bound to it.

p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method

p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback

call :

The first argument of the call method is used as this inside the function that is invoked with call attached to it.

sayNameVersion3 uses call to manipulate the this to refer to the person object that we created, instead of the window object.

this.sayNameVersion3 = function(callback){
    callback.call(this)
}

and it is called like the following :

p1.sayNameVersion3(niceCallback)

apply :

Similar to call, first argument of apply refers to the object that will be indicated by this keyword.

sayNameVersion4 uses apply to manipulate this to refer to person object

this.sayNameVersion4 = function(callback){
    callback.apply(this)
}

and it is called like the following.Simply the callback is passed,

p1.sayNameVersion4(niceCallback)

Add a border outside of a UIView (instead of inside)

With the above accepted best answer i made experiences with such not nice results and unsightly edges:

border without bezier path

So i will share my UIView Swift extension with you, that uses a UIBezierPath instead as border outline – without unsightly edges (inspired by @Fattie):

border with bezier path

//  UIView+BezierPathBorder.swift

import UIKit

extension UIView {

    fileprivate var bezierPathIdentifier:String { return "bezierPathBorderLayer" }

    fileprivate var bezierPathBorder:CAShapeLayer? {
        return (self.layer.sublayers?.filter({ (layer) -> Bool in
            return layer.name == self.bezierPathIdentifier && (layer as? CAShapeLayer) != nil
        }) as? [CAShapeLayer])?.first
    }

    func bezierPathBorder(_ color:UIColor = .white, width:CGFloat = 1) {

        var border = self.bezierPathBorder
        let path = UIBezierPath(roundedRect: self.bounds, cornerRadius:self.layer.cornerRadius)
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask

        if (border == nil) {
            border = CAShapeLayer()
            border!.name = self.bezierPathIdentifier
            self.layer.addSublayer(border!)
        }

        border!.frame = self.bounds
        let pathUsingCorrectInsetIfAny =
            UIBezierPath(roundedRect: border!.bounds, cornerRadius:self.layer.cornerRadius)

        border!.path = pathUsingCorrectInsetIfAny.cgPath
        border!.fillColor = UIColor.clear.cgColor
        border!.strokeColor = color.cgColor
        border!.lineWidth = width * 2
    }

    func removeBezierPathBorder() {
        self.layer.mask = nil
        self.bezierPathBorder?.removeFromSuperlayer()
    }

}

Example:

let view = UIView(frame: CGRect(x: 20, y: 20, width: 100, height: 100))
view.layer.cornerRadius = view.frame.width / 2
view.backgroundColor = .red

//add white 2 pixel border outline
view.bezierPathBorder(.white, width: 2)

//remove border outline (optional)
view.removeBezierPathBorder()

How to find day of week in php in a specific timezone

Another quick way:

date_default_timezone_set($userTimezone);
echo date("l");

Max size of an iOS application

50 Meg is the max for Cell data download.

But you might be able to keep it under that in the app store and then have the app download other content after the user install and runs the app, so the app can be bigger. But not sure what the apple rules are for this.

I know that all in-app purchases need to be approved, but not sure if this kind of content needs to be approved.

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

Android studio doesn't list my phone under "Choose Device"

I face Same problem. In my case i solved this by following some steps.

  1. click attached debugger to android process (It located In android tools inside run button)

  2. if see adb not responding error dialog. then click restart of dialogue button.

  3. Now you can see which device is connected. now close this window.

  4. again press run button. Now you find your targeted device or emulator which is connected.

Hopefully it helps you.

Node.js getaddrinfo ENOTFOUND

I got this issue resolved by removing non-desirable characters from the password for the connection. For example, I had these characters: <##% and it caused the problem (most probably hash tag was the root cause of the problem).

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

How can I find the number of days between two Date objects in Ruby?

Subtract the beginning date from the end date:

endDate - beginDate 

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Flurry Support for iPhone 5 (ARMv7s) As I mentioned in yesterday’s post, Flurry started working on a version of the iOS SDK to support the ARMv7s processor in the new iPhone 5 immediately after the announcement on Wednesday.

I am happy to tell you that the work is done and the SDK is now available on the site.

Get full path of a file with FileUpload Control

FileUpload will never give you the full path for security reasons.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.

$products = DB::table('products AS pr')
        ->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
        ->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
        ->orderBy('pr.id', 'desc')
        ->get();

Hope this helps.

Insert an item into sorted list in Python

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']

Sorting a list using Lambda/Linq to objects

Sort uses the IComparable interface, if the type implements it. And you can avoid the ifs by implementing a custom IComparer:

class EmpComp : IComparer<Employee>
{
    string fieldName;
    public EmpComp(string fieldName)
    {
        this.fieldName = fieldName;
    }

    public int Compare(Employee x, Employee y)
    {
        // compare x.fieldName and y.fieldName
    }
}

and then

list.Sort(new EmpComp(sortBy));

-bash: export: `=': not a valid identifier

I had the same problem and figured it out from your comments, but thought I would add the reason I caused the error to occur (for other beginners).

I had opened and edited .bash_profile using the open command in Terminal, which opened it in Text Editor. I typed in an addition to .bash_profile and it used improper quote characters. I opened .bash_profile in Atom and fixed up the error. I also associated the file with Atom for future editing.

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

Strings and character with printf

If you try this:

#include<stdio.h>

void main()
{
 char name[]="siva";
 printf("name = %p\n", name);
 printf("&name[0] = %p\n", &name[0]);
 printf("name printed as %%s is %s\n",name);
 printf("*name = %c\n",*name);
 printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data
=========   ======

0xbff5391b    0x73  's'  ---> name[0]
0xbff5391c    0x69  'i'  ---> name[1]
0xbff5391d    0x76  'v'  ---> name[2]
0xbff5391e    0x61  'a'  ---> name[3]
0xbff5391f    0x00  '\0' ---> This is the NULL termination of the string

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

ASP.NET MVC DropDownListFor with model of type List<string>

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })

Which gives a drop down list like so:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

Make the current Git branch a master branch

Rename the branch to master by:

git branch -M branch_name master

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Launch a shell command with in a python script, wait for the termination and return to the script

You can use subprocess.Popen. There's a few ways to do it:

import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()

Converting an int into a 4 byte char array (C)

int a = 1;
char * c = (char*)(&a); //In C++ should be intermediate cst to void*

How to extract the decimal part from a floating point number in C?

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

How to replace a string in a SQL Server Table Column

It's this easy:

update my_table
set path = replace(path, 'oldstring', 'newstring')

Create a new object from type parameter in generic class

i use this: let instance = <T>{}; it generally works EDIT 1:

export class EntityCollection<T extends { id: number }>{
  mutable: EditableEntity<T>[] = [];
  immutable: T[] = [];
  edit(index: number) {
    this.mutable[index].entity = Object.assign(<T>{}, this.immutable[index]);
  }
}

Windows batch: sleep

For a pure cmd.exe script, you can use this piece of code that returns the current time in hundreths of seconds.

:gettime
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

You may then use it in a wait loop like this.

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

And putting all pieces together:

@echo off
setlocal enableextensions enabledelayedexpansion

call :gettime t1
echo %t1%
call :wait %1
call :gettime t2
echo %t2%
set /A tt = (t2-t1)/100
echo %tt%
goto :eof

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

:gettime 
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

For a more detailed description of the commands used here, check HELP SET and HELP CALL information.

How can I get device ID for Admob

Add this class to your project

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;

import com.google.android.gms.ads.AdRequest;
import java.io.UnsupportedEncodingException;

public class AdsHelper {
public static AdRequest createRequest(Context context) {
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
    if (BuildConfig.DEBUG) {
        String deviceId = MD5(getDeviceId(context));
        if (!TextUtils.isEmpty(deviceId)) {
            adRequest.addTestDevice(deviceId.toUpperCase());
        }
    }

    return adRequest.build();
}



    private static String MD5(String md5) {
        if (TextUtils.isEmpty(md5)) return null;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte anArray : array) {
                sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException ignored) {
        } catch(UnsupportedEncodingException ignored){
        }
        return null;
    }

    private static String getDeviceId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }

    }
}

Usage:

AdRequest adRequest = AdsHelper.createRequest(this);

Get the week start date and week end date from week number

you can also use this:

  SELECT DATEADD(day, DATEDIFF(day, 0, WeddingDate) /7*7, 0) AS weekstart,
         DATEADD(day, DATEDIFF(day, 6, WeddingDate-1) /7*7 + 7, 6) AS WeekEnd

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

Binary numbers in Python

Not sure if helpful, but I leave my solution here:

class Solution:
    # @param A : string
    # @param B : string
    # @return a strings
    def addBinary(self, A, B):
        num1 = bin(int(A, 2))
        num2 = bin(int(B, 2))
        bin_str = bin(int(num1, 2)+int(num2, 2))
        b_index = bin_str.index('b')
        return bin_str[b_index+1:]

s = Solution()
print(s.addBinary("11", "100"))

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        })),
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        })),
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            })),
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
            }))
        ]
        )]),
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            })),
            animate('800ms ease-in-out', style({
                'opacity': '1'
            }))
        ]
        )])
    ]),
]

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

import { SlideInOutAnimation } from './animations';

@Component({
  ...
  animations: [SlideInOutAnimation]
})
export class AppComponent  {
  animationState = 'in';

  ...

  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      console.log(this.animationState);
      this.animationState = this.animationState === 'out' ? 'in' : 'out';
      console.log(this.animationState);
    }
  }
}

And here is how your app.component.html would look like :

<div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  THIS DIV IS ANIMATED</div>
  <div class="content">THIS IS CONTENT DIV</div>
</div>

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [ ..., BrowserAnimationsModule ],
  ...
})

How to configure nginx to enable kinda 'file browser' mode?

I've tried many times.

And at last I just put autoindex on; in http but outside of server, and it's OK.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

First of all, please vote and comment on the API request on the .NET repo.

Here's my optimized version of the ObservableRangeCollection (optimized version of James Montemagno's one).

It performs very fast and is meant to reuse existing elements when possible and avoid unnecessary events, or batching them into one, when possible. The ReplaceRange method replaces/removes/adds the required elements by the appropriate indices and batches the possible events.

Tested on Xamarin.Forms UI with great results for very frequent updates to the large collection (5-7 updates per second).

Note: Since WPF is not accustomed to work with range operations, it will throw a NotSupportedException, when using the ObservableRangeCollection from below in WPF UI-related work, such as binding it to a ListBox etc. (you can still use the ObservableRangeCollection<T> if not bound to UI).
However you can use the WpfObservableRangeCollection<T> workaround.
The real solution would be creating a CollectionView that knows how to deal with range operations, but I still didn't have the time to implement this.

RAW Code - open as Raw, then do Ctrl+A to select all, then Ctrl+C to copy.

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;

namespace System.Collections.ObjectModel
{
  /// <summary>
  /// Implementation of a dynamic data collection based on generic Collection&lt;T&gt;,
  /// implementing INotifyCollectionChanged to notify listeners
  /// when items get added, removed or the whole list is refreshed.
  /// </summary>
  public class ObservableRangeCollection<T> : ObservableCollection<T>
  {
    //------------------------------------------------------
    //
    //  Private Fields
    //
    //------------------------------------------------------

    #region Private Fields    
    [NonSerialized]
    private DeferredEventsCollection _deferredEvents;
    #endregion Private Fields


    //------------------------------------------------------
    //
    //  Constructors
    //
    //------------------------------------------------------

    #region Constructors
    /// <summary>
    /// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
    /// </summary>
    public ObservableRangeCollection() { }

    /// <summary>
    /// Initializes a new instance of the ObservableCollection class that contains
    /// elements copied from the specified collection and has sufficient capacity
    /// to accommodate the number of elements copied.
    /// </summary>
    /// <param name="collection">The collection whose elements are copied to the new list.</param>
    /// <remarks>
    /// The elements are copied onto the ObservableCollection in the
    /// same order they are read by the enumerator of the collection.
    /// </remarks>
    /// <exception cref="ArgumentNullException"> collection is a null reference </exception>
    public ObservableRangeCollection(IEnumerable<T> collection) : base(collection) { }

    /// <summary>
    /// Initializes a new instance of the ObservableCollection class
    /// that contains elements copied from the specified list
    /// </summary>
    /// <param name="list">The list whose elements are copied to the new list.</param>
    /// <remarks>
    /// The elements are copied onto the ObservableCollection in the
    /// same order they are read by the enumerator of the list.
    /// </remarks>
    /// <exception cref="ArgumentNullException"> list is a null reference </exception>
    public ObservableRangeCollection(List<T> list) : base(list) { }

    #endregion Constructors

    //------------------------------------------------------
    //
    //  Public Methods
    //
    //------------------------------------------------------

    #region Public Methods

    /// <summary>
    /// Adds the elements of the specified collection to the end of the <see cref="ObservableCollection{T}"/>.
    /// </summary>
    /// <param name="collection">
    /// The collection whose elements should be added to the end of the <see cref="ObservableCollection{T}"/>.
    /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.
    /// </param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void AddRange(IEnumerable<T> collection)
    {
      InsertRange(Count, collection);
    }

    /// <summary>
    /// Inserts the elements of a collection into the <see cref="ObservableCollection{T}"/> at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index at which the new elements should be inserted.</param>
    /// <param name="collection">The collection whose elements should be inserted into the List<T>.
    /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>                
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is not in the collection range.</exception>
    public void InsertRange(int index, IEnumerable<T> collection)
    {
      if (collection == null)
        throw new ArgumentNullException(nameof(collection));
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (index > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
        {
          return;
        }
      }
      else if (!ContainsAny(collection))
      {
        return;
      }

      CheckReentrancy();

      //expand the following couple of lines when adding more constructors.
      var target = (List<T>)Items;
      target.InsertRange(index, collection);

      OnEssentialPropertiesChanged();

      if (!(collection is IList list))
        list = new List<T>(collection);

      OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, list, index));
    }


    /// <summary> 
    /// Removes the first occurence of each item in the specified collection from the <see cref="ObservableCollection{T}"/>.
    /// </summary>
    /// <param name="collection">The items to remove.</param>        
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void RemoveRange(IEnumerable<T> collection)
    {
      if (collection == null)
        throw new ArgumentNullException(nameof(collection));

      if (Count == 0)
      {
        return;
      }
      else if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
          return;
        else if (countable.Count == 1)
          using (IEnumerator<T> enumerator = countable.GetEnumerator())
          {
            enumerator.MoveNext();
            Remove(enumerator.Current);
            return;
          }
      }
      else if (!(ContainsAny(collection)))
      {
        return;
      }

      CheckReentrancy();

      var clusters = new Dictionary<int, List<T>>();
      var lastIndex = -1;
      List<T> lastCluster = null;
      foreach (T item in collection)
      {
        var index = IndexOf(item);
        if (index < 0)
        {
          continue;
        }

        Items.RemoveAt(index);

        if (lastIndex == index && lastCluster != null)
        {
          lastCluster.Add(item);
        }
        else
        {
          clusters[lastIndex = index] = lastCluster = new List<T> { item };
        }
      }

      OnEssentialPropertiesChanged();

      if (Count == 0)
        OnCollectionReset();
      else
        foreach (KeyValuePair<int, List<T>> cluster in clusters)
          OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster.Value, cluster.Key));

    }

    /// <summary>
    /// Iterates over the collection and removes all items that satisfy the specified match.
    /// </summary>
    /// <remarks>The complexity is O(n).</remarks>
    /// <param name="match"></param>
    /// <returns>Returns the number of elements that where </returns>
    /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
    public int RemoveAll(Predicate<T> match)
    {
      return RemoveAll(0, Count, match);
    }

    /// <summary>
    /// Iterates over the specified range within the collection and removes all items that satisfy the specified match.
    /// </summary>
    /// <remarks>The complexity is O(n).</remarks>
    /// <param name="index">The index of where to start performing the search.</param>
    /// <param name="count">The number of items to iterate on.</param>
    /// <param name="match"></param>
    /// <returns>Returns the number of elements that where </returns>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
    public int RemoveAll(int index, int count, Predicate<T> match)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (match == null)
        throw new ArgumentNullException(nameof(match));

      if (Count == 0)
        return 0;

      List<T> cluster = null;
      var clusterIndex = -1;
      var removedCount = 0;

      using (BlockReentrancy())
      using (DeferEvents())
      {
        for (var i = 0; i < count; i++, index++)
        {
          T item = Items[index];
          if (match(item))
          {
            Items.RemoveAt(index);
            removedCount++;

            if (clusterIndex == index)
            {
              Debug.Assert(cluster != null);
              cluster.Add(item);
            }
            else
            {
              cluster = new List<T> { item };
              clusterIndex = index;
            }

            index--;
          }
          else if (clusterIndex > -1)
          {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
            clusterIndex = -1;
            cluster = null;
          }
        }

        if (clusterIndex > -1)
          OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
      }

      if (removedCount > 0)
        OnEssentialPropertiesChanged();

      return removedCount;
    }

    /// <summary>
    /// Removes a range of elements from the <see cref="ObservableCollection{T}"/>>.
    /// </summary>
    /// <param name="index">The zero-based starting index of the range of elements to remove.</param>
    /// <param name="count">The number of elements to remove.</param>
    /// <exception cref="ArgumentOutOfRangeException">The specified range is exceeding the collection.</exception>
    public void RemoveRange(int index, int count)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (count == 0)
        return;

      if (count == 1)
      {
        RemoveItem(index);
        return;
      }

      //Items will always be List<T>, see constructors
      var items = (List<T>)Items;
      List<T> removedItems = items.GetRange(index, count);

      CheckReentrancy();

      items.RemoveRange(index, count);

      OnEssentialPropertiesChanged();

      if (Count == 0)
        OnCollectionReset();
      else
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index));
    }

    /// <summary> 
    /// Clears the current collection and replaces it with the specified collection,
    /// using the default <see cref="EqualityComparer{T}"/>.
    /// </summary>             
    /// <param name="collection">The items to fill the collection with, after clearing it.</param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void ReplaceRange(IEnumerable<T> collection)
    {
      ReplaceRange(0, Count, collection, EqualityComparer<T>.Default);
    }

    /// <summary>
    /// Clears the current collection and replaces it with the specified collection,
    /// using the specified comparer to skip equal items.
    /// </summary>
    /// <param name="collection">The items to fill the collection with, after clearing it.</param>
    /// <param name="comparer">An <see cref="IEqualityComparer{T}"/> to be used
    /// to check whether an item in the same location already existed before,
    /// which in case it would not be added to the collection, and no event will be raised for it.</param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
    public void ReplaceRange(IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
      ReplaceRange(0, Count, collection, comparer);
    }

    /// <summary>
    /// Removes the specified range and inserts the specified collection,
    /// ignoring equal items (using <see cref="EqualityComparer{T}.Default"/>).
    /// </summary>
    /// <param name="index">The index of where to start the replacement.</param>
    /// <param name="count">The number of items to be replaced.</param>
    /// <param name="collection">The collection to insert in that location.</param>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void ReplaceRange(int index, int count, IEnumerable<T> collection)
    {
      ReplaceRange(index, count, collection, EqualityComparer<T>.Default);
    }

    /// <summary>
    /// Removes the specified range and inserts the specified collection in its position, leaving equal items in equal positions intact.
    /// </summary>
    /// <param name="index">The index of where to start the replacement.</param>
    /// <param name="count">The number of items to be replaced.</param>
    /// <param name="collection">The collection to insert in that location.</param>
    /// <param name="comparer">The comparer to use when checking for equal items.</param>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
    public void ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (collection == null)
        throw new ArgumentNullException(nameof(collection));
      if (comparer == null)
        throw new ArgumentNullException(nameof(comparer));

      if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
        {
          RemoveRange(index, count);
          return;
        }
      }
      else if (!ContainsAny(collection))
      {
        RemoveRange(index, count);
        return;
      }

      if (index + count == 0)
      {
        InsertRange(0, collection);
        return;
      }

      if (!(collection is IList<T> list))
        list = new List<T>(collection);

      using (BlockReentrancy())
      using (DeferEvents())
      {
        var rangeCount = index + count;
        var addedCount = list.Count;

        var changesMade = false;
        List<T>
            newCluster = null,
            oldCluster = null;


        int i = index;
        for (; i < rangeCount && i - index < addedCount; i++)
        {
          //parallel position
          T old = this[i], @new = list[i - index];
          if (comparer.Equals(old, @new))
          {
            OnRangeReplaced(i, newCluster, oldCluster);
            continue;
          }
          else
          {
            Items[i] = @new;

            if (newCluster == null)
            {
              Debug.Assert(oldCluster == null);
              newCluster = new List<T> { @new };
              oldCluster = new List<T> { old };
            }
            else
            {
              newCluster.Add(@new);
              oldCluster.Add(old);
            }

            changesMade = true;
          }
        }

        OnRangeReplaced(i, newCluster, oldCluster);

        //exceeding position
        if (count != addedCount)
        {
          var items = (List<T>)Items;
          if (count > addedCount)
          {
            var removedCount = rangeCount - addedCount;
            T[] removed = new T[removedCount];
            items.CopyTo(i, removed, 0, removed.Length);
            items.RemoveRange(i, removedCount);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, i));
          }
          else
          {
            var k = i - index;
            T[] added = new T[addedCount - k];
            for (int j = k; j < addedCount; j++)
            {
              T @new = list[j];
              added[j - k] = @new;
            }
            items.InsertRange(i, added);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, i));
          }

          OnEssentialPropertiesChanged();
        }
        else if (changesMade)
        {
          OnIndexerPropertyChanged();
        }
      }
    }

    #endregion Public Methods


    //------------------------------------------------------
    //
    //  Protected Methods
    //
    //------------------------------------------------------

    #region Protected Methods

    /// <summary>
    /// Called by base class Collection&lt;T&gt; when the list is being cleared;
    /// raises a CollectionChanged event to any listeners.
    /// </summary>
    protected override void ClearItems()
    {
      if (Count == 0)
        return;

      CheckReentrancy();
      base.ClearItems();
      OnEssentialPropertiesChanged();
      OnCollectionReset();
    }

    /// <summary>
    /// Called by base class Collection&lt;T&gt; when an item is set in list;
    /// raises a CollectionChanged event to any listeners.
    /// </summary>
    protected override void SetItem(int index, T item)
    {
      if (Equals(this[index], item))
        return;

      CheckReentrancy();
      T originalItem = this[index];
      base.SetItem(index, item);

      OnIndexerPropertyChanged();
      OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
    }

    /// <summary>
    /// Raise CollectionChanged event to any listeners.
    /// Properties/methods modifying this ObservableCollection will raise
    /// a collection changed event through this virtual method.
    /// </summary>
    /// <remarks>
    /// When overriding this method, either call its base implementation
    /// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
    /// </remarks>
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      if (_deferredEvents != null)
      {
        _deferredEvents.Add(e);
        return;
      }
      base.OnCollectionChanged(e);
    }

    protected virtual IDisposable DeferEvents() => new DeferredEventsCollection(this);

    #endregion Protected Methods


    //------------------------------------------------------
    //
    //  Private Methods
    //
    //------------------------------------------------------

    #region Private Methods

    /// <summary>
    /// Helper function to determine if a collection contains any elements.
    /// </summary>
    /// <param name="collection">The collection to evaluate.</param>
    /// <returns></returns>
    private static bool ContainsAny(IEnumerable<T> collection)
    {
      using (IEnumerator<T> enumerator = collection.GetEnumerator())
        return enumerator.MoveNext();
    }

    /// <summary>
    /// Helper to raise Count property and the Indexer property.
    /// </summary>
    private void OnEssentialPropertiesChanged()
    {
      OnPropertyChanged(EventArgsCache.CountPropertyChanged);
      OnIndexerPropertyChanged();
    }

    /// <summary>
    /// /// Helper to raise a PropertyChanged event for the Indexer property
    /// /// </summary>
    private void OnIndexerPropertyChanged() =>
      OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);

    /// <summary>
    /// Helper to raise CollectionChanged event to any listeners
    /// </summary>
    private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) =>
      OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));

    /// <summary>
    /// Helper to raise CollectionChanged event with action == Reset to any listeners
    /// </summary>
    private void OnCollectionReset() =>
      OnCollectionChanged(EventArgsCache.ResetCollectionChanged);

    /// <summary>
    /// Helper to raise event for clustered action and clear cluster.
    /// </summary>
    /// <param name="followingItemIndex">The index of the item following the replacement block.</param>
    /// <param name="newCluster"></param>
    /// <param name="oldCluster"></param>
    //TODO should have really been a local method inside ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer),
    //move when supported language version updated.
    private void OnRangeReplaced(int followingItemIndex, ICollection<T> newCluster, ICollection<T> oldCluster)
    {
      if (oldCluster == null || oldCluster.Count == 0)
      {
        Debug.Assert(newCluster == null || newCluster.Count == 0);
        return;
      }

      OnCollectionChanged(
          new NotifyCollectionChangedEventArgs(
              NotifyCollectionChangedAction.Replace,
              new List<T>(newCluster),
              new List<T>(oldCluster),
              followingItemIndex - oldCluster.Count));

      oldCluster.Clear();
      newCluster.Clear();
    }

    #endregion Private Methods

    //------------------------------------------------------
    //
    //  Private Types
    //
    //------------------------------------------------------

    #region Private Types
    private sealed class DeferredEventsCollection : List<NotifyCollectionChangedEventArgs>, IDisposable
    {
      private readonly ObservableRangeCollection<T> _collection;
      public DeferredEventsCollection(ObservableRangeCollection<T> collection)
      {
        Debug.Assert(collection != null);
        Debug.Assert(collection._deferredEvents == null);
        _collection = collection;
        _collection._deferredEvents = this;
      }

      public void Dispose()
      {
        _collection._deferredEvents = null;
        foreach (var args in this)
          _collection.OnCollectionChanged(args);
      }
    }

    #endregion Private Types

  }

  /// <remarks>
  /// To be kept outside <see cref="ObservableCollection{T}"/>, since otherwise, a new instance will be created for each generic type used.
  /// </remarks>
  internal static class EventArgsCache
  {
    internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
    internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]");
    internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
  }
}

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

Group by multiple field names in java 8

I needed to make report for a catering firm which serves lunches for various clients. In other words, catering may have on or more firms which take orders from catering, and it must know how many lunches it must produce every single day for all it's clients !

Just to notice, I didn't use sorting, in order not to over complicate this example.

This is my code :

@Test
public void test_2() throws Exception {
    Firm catering = DS.firm().get(1);
    LocalDateTime ldtFrom = LocalDateTime.of(2017, Month.JANUARY, 1, 0, 0);
    LocalDateTime ldtTo = LocalDateTime.of(2017, Month.MAY, 2, 0, 0);
    Date dFrom = Date.from(ldtFrom.atZone(ZoneId.systemDefault()).toInstant());
    Date dTo = Date.from(ldtTo.atZone(ZoneId.systemDefault()).toInstant());

    List<PersonOrders> LON = DS.firm().getAllOrders(catering, dFrom, dTo, false);
    Map<Object, Long> M = LON.stream().collect(
            Collectors.groupingBy(p
                    -> Arrays.asList(p.getDatum(), p.getPerson().getIdfirm(), p.getIdProduct()),
                    Collectors.counting()));

    for (Map.Entry<Object, Long> e : M.entrySet()) {
        Object key = e.getKey();
        Long value = e.getValue();
        System.err.println(String.format("Client firm :%s, total: %d", key, value));
    }
}

Limiting number of displayed results when using ngRepeat

Slightly more "Angular way" would be to use the straightforward limitTo filter, as natively provided by Angular:

<ul class="phones">
  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp | limitTo:quantity">
    {{phone.name}}
    <p>{{phone.snippet}}</p>
  </li>
</ul>
app.controller('PhoneListCtrl', function($scope, $http) {
    $http.get('phones.json').then(
      function(phones){
        $scope.phones = phones.data;
      }
    );
    $scope.orderProp = 'age';
    $scope.quantity = 5;
  }
);

PLUNKER

Order data frame rows according to vector with specific order

Here's a similar system for the situation where you have a variable you want to sort by, initially, but then you want to sort by a secondary variable according to the order that this secondary variable first appears in the initial sort.

In the function below, the initial sort variable is called order_by and the secondary variable is called order_along - as in "order by this variable along its initial order".

library(dplyr, warn.conflicts = FALSE)
df <- structure(
  list(
    msoa11hclnm = c(
      "Bewbush", "Tilgate", "Felpham",
      "Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
      "Upperton", "Arundel", "Kemptown"
    ),
    lad20nm = c(
      "Crawley", "Crawley",
      "Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
      "Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
    ),
    shape_area = c(
      1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
      7036428, 5656430, 2653589, 72832514, 826151
    )
  ),
  row.names = c(NA, -12L), class = "data.frame"
)

this does not give me what I need:

df %>% 
  dplyr::arrange(shape_area, lad20nm)
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3      Bewbush           Crawley    1328821
#> 4     Upperton        Eastbourne    2653589
#> 5      Tilgate           Crawley    3089180
#> 6      Felpham              Arun    3540014
#> 7          Ore          Hastings    5517102
#> 8     Mile Oak Brighton and Hove    5656430
#> 9     Polegate           Wealden    7036428
#> 10      Selsey        Chichester    9738033
#> 11      Ratton        Eastbourne   10152663
#> 12     Arundel              Arun   72832514

Here’s a function:

order_along <- function(df, order_along, order_by) {
  cols <- colnames(df)
  
  df <- df %>%
    dplyr::arrange({{ order_by }})
  
  df %>% 
    dplyr::select({{ order_along }}) %>% 
    dplyr::distinct() %>% 
    dplyr::full_join(df) %>% 
    dplyr::select(dplyr::all_of(cols))
  
}

order_along(df, lad20nm, shape_area)
#> Joining, by = "lad20nm"
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3     Mile Oak Brighton and Hove    5656430
#> 4      Bewbush           Crawley    1328821
#> 5      Tilgate           Crawley    3089180
#> 6     Upperton        Eastbourne    2653589
#> 7       Ratton        Eastbourne   10152663
#> 8      Felpham              Arun    3540014
#> 9      Arundel              Arun   72832514
#> 10         Ore          Hastings    5517102
#> 11    Polegate           Wealden    7036428
#> 12      Selsey        Chichester    9738033

Created on 2021-01-12 by the reprex package (v0.3.0)

How do I make a relative reference to another workbook in Excel?

The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:

http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651

Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1 with no folder names to traverse.

getting error while updating Composer

If you're using php 7.3 for laravel 5.7. this work for me

sudo apt-get install php-gd php-xml php7.3-mbstring

How can I make a menubar fixed on the top while scrolling

to set a div at position fixed you can use

position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */

C# Numeric Only TextBox Control

I used the TryParse that @fjdumont mentioned but in the validating event instead.

private void Number_Validating(object sender, CancelEventArgs e) {
    int val;
    TextBox tb = sender as TextBox;
    if (!int.TryParse(tb.Text, out val)) {
        MessageBox.Show(tb.Tag +  " must be numeric.");
        tb.Undo();
        e.Cancel = true;
    }
}

I attached this to two different text boxes with in my form initializing code.

    public Form1() {
        InitializeComponent();
        textBox1.Validating+=new CancelEventHandler(Number_Validating);
        textBox2.Validating+=new CancelEventHandler(Number_Validating);
    }

I also added the tb.Undo() to back out invalid changes.

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

How to change package name in flutter?

If you don’t like changing files in such a way then alternative way would be to use this package.

https://pub.dev/packages/rename

rename --bundleId com.newpackage.appname
pub global run rename --appname "Your New App Name"

Using this, you simply run these 2 commands in your terminal and your app name and identifiers will be changed.pub global run

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Here is simple sample from android developer.

Basically, you can write a file in the internal storage like this :

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

Create new user in MySQL and give it full access to one database

To me this worked.

CREATE USER 'spowner'@'localhost' IDENTIFIED BY '1234'; 
GRANT ALL PRIVILEGES ON test.* To 'spowner'@'localhost'; 
FLUSH PRIVILEGES;

where

  • spowner : user name
  • 1234 : password of spowner
  • test : database 'spowner' has access right to

MVC Razor Radio Button

<label>@Html.RadioButton("ABC", "YES")Yes</label>
<label>@Html.RadioButton("ABC", "NO")No</label>

Re-enabling window.alert in Chrome

I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

Pass correct "this" context to setTimeout callback?

EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object:

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){ that.tip.destroy() }, 1000);
} 

In the ES5 spec, just released a year before that time, it introduced the bind method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:

if (this.options.destroyOnHide) {
     setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}

The bind function creates a new function with the this value pre-filled.

Now in modern JS, this is exactly the problem arrow functions solve in ES6:

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);
}

Arrow functions do not have a this value of its own, when you access it, you are accessing the this value of the enclosing lexical scope.

HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:

if (this.options.destroyOnHide) {
     setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}

See also:

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.

Count number of 1's in binary representation

Please note the fact that: n&(n-1) always eliminates the least significant 1.

Hence we can write the code for calculating the number of 1's as follows:

count=0;
while(n!=0){
  n = n&(n-1);
  count++;
}
cout<<"Number of 1's in n is: "<<count;

The complexity of the program would be: number of 1's in n (which is constantly < 32).

How to write ternary operator condition in jQuery?

Here is a working example in side a function:

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

In your case. Change the selector and the return values

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

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

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

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

Multiple commands in an alias for bash

On windows, in Git\etc\bash.bashrc I use (at the end of the file)

a(){
    git add $1  
    git status
}

and then in git bash simply write

$ a Config/

Inline CSS styles in React: how to implement a:hover?

With a using of the hooks:

const useFade = () => {
  const [ fade, setFade ] = useState(false);

  const onMouseEnter = () => {
    setFade(true);
  };

  const onMouseLeave = () => {
    setFade(false);
  };

  const fadeStyle = !fade ? {
    opacity: 1, transition: 'all .2s ease-in-out',
  } : {
    opacity: .5, transition: 'all .2s ease-in-out',
  };

  return { fadeStyle, onMouseEnter, onMouseLeave };
};

const ListItem = ({ style }) => {
  const { fadeStyle, ...fadeProps } = useFade();

  return (
    <Paper
      style={{...fadeStyle, ...style}}
      {...fadeProps}
    >
      {...}
    </Paper>
  );
};

How do I create a comma-separated list using a SQL query?

MySQL

  SELECT r.name,
         GROUP_CONCAT(a.name SEPARATOR ',')
    FROM RESOURCES r
    JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
    JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name

**


MS SQL Server

SELECT r.name,
       STUFF((SELECT ','+ a.name
               FROM APPLICATIONS a
               JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
              WHERE ar.resource_id = r.id
           GROUP BY a.name
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
 FROM RESOURCES r
 GROUP BY deptno;

Oracle

  SELECT r.name,
         LISTAGG(a.name SEPARATOR ',') WITHIN GROUP (ORDER BY a.name)
  FROM RESOURCES r
        JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
        JOIN APPLICATIONS a ON a.id = ar.app_id
  GROUP BY r.name;

How do I install PHP cURL on Linux Debian?

Type in console as root:

apt-get update && apt-get install php5-curl

or with sudo:

sudo apt-get update && sudo apt-get install php5-curl

Sorry I missread.

1st, check your DNS config and if you can ping any host at all,

ping google.com
ping zm.archive.ubuntu.com

If it does not work, check /etc/resolv.conf or /etc/network/resolv.conf, if not, change your apt-source to a different one.

/etc/apt/sources.list

Mirrors: http://www.debian.org/mirror/list

You should not use Ubuntu sources on Debian and vice versa.

how to fetch data from database in Hibernate

I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql

So the thing is you just have to write a query

Query query = session.createQuery("from Employee");

it will give you all the data list but to fetch data from this you have to write this line.

List<Employee> fetchedData = query.list();

As simple as it looks.

How to set time delay in javascript

There are two (mostly used) types of timer function in javascript setTimeout and setInterval (other)

Both these methods have same signature. They take a call back function and delay time as parameter.

setTimeout executes only once after the delay whereas setInterval keeps on calling the callback function after every delay milisecs.

both these methods returns an integer identifier that can be used to clear them before the timer expires.

clearTimeout and clearInterval both these methods take an integer identifier returned from above functions setTimeout and setInterval

Example:

setTimeout

alert("before setTimeout");

setTimeout(function(){
        alert("I am setTimeout");
   },1000); //delay is in milliseconds 

  alert("after setTimeout");

If you run the the above code you will see that it alerts before setTimeout and then after setTimeout finally it alerts I am setTimeout after 1sec (1000ms)

What you can notice from the example is that the setTimeout(...) is asynchronous which means it doesn't wait for the timer to get elapsed before going to next statement i.e alert("after setTimeout");

Example:

setInterval

alert("before setInterval"); //called first

 var tid = setInterval(function(){
        //called 5 times each time after one second  
      //before getting cleared by below timeout. 
        alert("I am setInterval");
   },1000); //delay is in milliseconds 

  alert("after setInterval"); //called second

setTimeout(function(){
     clearInterval(tid); //clear above interval after 5 seconds
},5000);

If you run the the above code you will see that it alerts before setInterval and then after setInterval finally it alerts I am setInterval 5 times after 1sec (1000ms) because the setTimeout clear the timer after 5 seconds or else every 1 second you will get alert I am setInterval Infinitely.

How browser internally does that?

I will explain in brief.

To understand that you have to know about event queue in javascript. There is a event queue implemented in browser. Whenever an event get triggered in js, all of these events (like click etc.. ) are added to this queue. When your browser has nothing to execute it takes an event from queue and executes them one by one.

Now, when you call setTimeout or setInterval your callback get registered to an timer in browser and it gets added to the event queue after the given time expires and eventually javascript takes the event from the queue and executes it.

This happens so, because javascript engine are single threaded and they can execute only one thing at a time. So, they cannot execute other javascript and keep track of your timer. That is why these timers are registered with browser (browser are not single threaded) and it can keep track of timer and add an event in the queue after the timer expires.

same happens for setInterval only in this case the event is added to the queue again and again after the specified interval until it gets cleared or browser page refreshed.

Note

The delay parameter you pass to these functions is the minimum delay time to execute the callback. This is because after the timer expires the browser adds the event to the queue to be executed by the javascript engine but the execution of the callback depends upon your events position in the queue and as the engine is single threaded it will execute all the events in the queue one by one.

Hence, your callback may sometime take more than the specified delay time to be called specially when your other code blocks the thread and not giving it time to process what's there in the queue.

And as I mentioned javascript is single thread. So, if you block the thread for long.

Like this code

while(true) { //infinite loop 
}

Your user may get a message saying page not responding.

jQuery UI Alert Dialog as a replacement for alert()

As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.

This can also be cleaned up simply by adding:

$(this).dialog('destroy').remove();

to the close method of the dialog. Example adding this line to eidylon's answer:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: function() { onCloseCallback();
                           /* Cleanup node(s) from DOM */
                           $(this).dialog('destroy').remove();
                          }
    });
}

EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?

Initial size for the ArrayList

I guess an exact answer to your question would be:

Setting an intial size on an ArrayList reduces the nr. of times internal memory re-allocation has to occur. The list is backed by an array. If you specify i.e. initial capacity 0, already at the first insertion of an element the internal array would have to be resized. If you have an approximate idea of how many elements your list would hold, setting the initial capacity would reduce the nr. of memory re-allocations happening while you use the list.

How to pre-populate the sms body text via an html link

For iOS 8, try this:

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

Switching the ";" with a "&" worked for me.

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

How to get All input of POST in Laravel

Try this :

use Illuminate\Support\Facades\Request;
public function add_question(Request $request)
{
    return $request->all();
}

EditText, clear focus on touch outside

In Kotlin

hidekeyboard() is a Kotlin Extension

fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
}

In activity add dispatchTouchEvent

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
    if (event.action == MotionEvent.ACTION_DOWN) {
        val v: View? = currentFocus
        if (v is EditText) {
            val outRect = Rect()
            v.getGlobalVisibleRect(outRect)
            if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                v.clearFocus()
                hideKeyboard()
            }
        }
    }
    return super.dispatchTouchEvent(event)
}

Add these properties in the top most parent

android:focusableInTouchMode="true"
android:focusable="true"

How to create a localhost server to run an AngularJS project

  • Run
ng serve

This command run in your terminal after your in project folder location like ~/my-app$

  • Then run the command - it will show the URl NG Live Development Server is listening on localhost:4200

  • Open your browser on http://localhost:4200

SQL Server equivalent to MySQL enum data type?

It doesn't. There's a vague equivalent:

mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))

disable horizontal scroll on mobile web

For me, the viewport meta tag actually caused a horizontal scroll issue on the Blackberry.

I removed content="initial-scale=1.0; maximum-scale=1.0; from the viewport tag and it fixed the issue. Below is my current viewport tag:

<meta name="viewport" content="user-scalable=0;"/>

Using Switch Statement to Handle Button Clicks

One way of achieving this is to make your class implement OnClickListener and then add it to your buttons like this:

Example:

//make your class implement OnClickListener
public class MyClass implements OnClickListener{

        ...

        //Create your buttons and set their onClickListener to "this"
        Button b1 = (Button) findViewById(R.id.buttonplay);   
        b1.setOnClickListener(this);

        Button b2 = (Button) findViewById(R.id.buttonstop);   
        b2.setOnClickListener(this);

        ...

        //implement the onClick method here
        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
            case R.id.buttonplay:
              //Play voicefile
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
              break;
            case R.id.buttonstop:
              //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
              break;
          }
       }
}

For more information see Android Developers > Handling UI Events.

How can I check if an element exists in the visible DOM?

  • If an element is in the DOM, its parents should also be in
  • And the last grandparent should be the document

So to check that we just loop unto the element's parentNode tree until we reach the last grandparent

Use this:

/**
 * @param {HTMLElement} element - The element to check
 * @param {boolean}     inBody  - Checks if the element is in the body
 * @return {boolean}
 */
var isInDOM = function(element, inBody) {
    var _ = element, last;

    while (_) {
        last = _;
        if (inBody && last === document.body) { break;}
        _ = _.parentNode;
    }

    return inBody ? last === document.body : last === document;
};

How can I programmatically determine if my app is running in the iphone simulator?

/// Returns true if its simulator and not a device

public static var isSimulator: Bool {
    #if (arch(i386) || arch(x86_64)) && os(iOS)
        return true
    #else
        return false
    #endif
}

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

how to get current month and year

You can use this:

<p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>

Temporary table in SQL server causing ' There is already an object named' error

You must modify the query like this

CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN(FRST_NAME,LAST_NAME)
SELECT LAST_NAME,FRST_NAME  FROM TBL_PEOPLE

-- Make a last session for clearing the all temporary tables. always drop at end. In your case, sometimes, there might be an error happen if the table is not exists, while you trying to delete.

DROP TABLE #TMPGUARDIAN

Avoid using insert into Because If you are using insert into then in future if you want to modify the temp table by adding a new column which can be filled after some process (not along with insert). At that time, you need to rework and design it in the same manner.

Use Table Variable http://odetocode.com/articles/365.aspx

declare @userData TABLE(
 LAST_NAME NVARCHAR(30),
    FRST_NAME NVARCHAR(30)
)

Advantages No need for Drop statements, since this will be similar to variables. Scope ends immediately after the execution.

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

Make the first character Uppercase in CSS

Note that the ::first-letter selector does not work with inline elements, so it must be either block or inline-block, as follows:

.m_title {display:inline-block}
.m_title:first-letter {text-transform: uppercase}

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

Change a Rails application to production

In Rails 3

Adding Rails.env = ActiveSupport::StringInquirer.new('production') into the application.rb and rails s will work same as rails server -e production

module BlacklistAdmin
  class Application < Rails::Application

    config.encoding = "utf-8"
    Rails.env = ActiveSupport::StringInquirer.new('production')

    config.filter_parameters += [:password]
  end
end

DataGridView - Focus a specific cell

public void M(){ 
  dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
  dataGridView1.CurrentCell.Selected = true; 
  dataGridView1.BeginEdit(true);
}

Bad Gateway 502 error with Apache mod_proxy and Tomcat

Most likely you should increase Timeout parameter in apache conf (default value 120 sec)

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

Sorting HashMap by values

found a solution but not sure the performance if the map has large size, useful for normal case.

   /**
     * sort HashMap<String, CustomData> by value
     * CustomData needs to provide compareTo() for comparing CustomData
     * @param map
     */

    public void sortHashMapByValue(final HashMap<String, CustomData> map) {
        ArrayList<String> keys = new ArrayList<String>();
        keys.addAll(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                CustomData val1 = map.get(lhs);
                CustomData val2 = map.get(rhs);
                if (val1 == null) {
                    return (val2 != null) ? 1 : 0;
                } else if (val1 != null) && (val2 != null)) {
                    return = val1.compareTo(val2);
                }
                else {
                    return 0;
                }
            }
        });

        for (String key : keys) {
            CustomData c = map.get(key);
            if (c != null) {
                Log.e("key:"+key+", CustomData:"+c.toString());
            } 
        }
    }

What does Java option -Xmx stand for?

The -Xmx option changes the maximum Heap Space for the VM. java -Xmx1024m means that the VM can allocate a maximum of 1024 MB. In layman terms this means that the application can use a maximum of 1024MB of memory.

Ruby 'require' error: cannot load such file

The problem is that require does not load from the current directory. This is what I thought, too but then I found this thread. For example I tried the following code:

irb> f = File.new('blabla.rb')
=> #<File:blabla.rb>
irb> f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
LoadError: cannot load such file -- blabla.rb
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from D:/dev/Ruby193/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `req
uire'
        from (irb):24
        from D:/dev/Ruby193/bin/irb:12:in `<main>'

As it can be seen it read the file ok, but I could not require it (the path was not recognized). and here goes code that works:

irb f = File.new('D://blabla.rb')
=> #<File:D://blabla.rb>
irb f.read
=> "class Tokenizer\n    def self.tokenize(string)\n        return string.split(
\" \")\n    end\nend\n"
irb> require f
=> true

As you can see if you specify the full path the file loads correctly.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

How do I know the script file name in a Bash script?

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

Batch script to install MSI

This is how to install a normal MSI file silently:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging at indicated path
 /QN = run completely silently
 /i = run install sequence 

The msiexec.exe command line is extensive with support for a variety of options. Here is another overview of the same command line interface. Here is an annotated versions (was broken, resurrected via way back machine).

It is also possible to make a batch file a lot shorter with constructs such as for loops as illustrated here for Windows Updates.

If there are check boxes that must be checked during the setup, you must find the appropriate PUBLIC PROPERTIES attached to the check box and set it at the command line like this:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log" STARTAPP=1 SHOWHELP=Yes

These properties are different in each MSI. You can find them via the verbose log file or by opening the MSI in Orca, or another appropriate tool. You must look either in the dialog control section or in the Property table for what the property name is. Try running the setup and create a verbose log file first and then search the log for messages ala "Setting property..." and then see what the property name is there. Then add this property with the value from the log file to the command line.

Also have a look at how to use transforms to customize the MSI beyond setting command line parameters: How to make better use of MSI files

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you want to present a new view in the same storyboard,

In CurrentViewController.m,

#import "YourViewController.h"

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
YourViewController *viewController = (YourViewController *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self presentViewController:viewController animated:YES completion:nil];

To set identifier to a view controller, Open MainStoryBoard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Django, creating a custom 500/404 error page

settings.py:

DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost']  #provide your host name

and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

Java: how do I check if a Date is within a certain range?

For covering my case -> I've got a range start & end date, and dates list that can be as partly in provided range, as fully (overlapping).

Solution covered with tests:

/**
 * Check has any of quote work days in provided range.
 *
 * @param startDate inclusively
 * @param endDate   inclusively
 *
 * @return true if any in provided range inclusively
 */
public boolean hasAnyWorkdaysInRange(LocalDate startDate, LocalDate endDate) {
    if (CollectionUtils.isEmpty(workdays)) {
        return false;
    }

    LocalDate firstWorkDay = getFirstWorkDay().getDate();
    LocalDate lastWorkDay = getLastWorkDay().getDate();

    return (firstWorkDay.isBefore(endDate) || firstWorkDay.equals(endDate))
            && (lastWorkDay.isAfter(startDate) || lastWorkDay.equals(startDate));
}

How to parse an RSS feed using JavaScript?

You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:

// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "https://stackoverflow.com/feeds/question/10943544",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.

Change a web.config programmatically with C# (.NET)

Here it is some code:

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

See more examples in this article, you may need to take a look to impersonation.

R dates "origin" must be supplied

by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".

(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)

How to call python script on excel vba?

To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program

Sub runpython()

Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
   MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub

In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I really have the same problem, finally, i solved it.

its likey not the Swift Mail's problem. It's Yaml parser's problem. if your password only the digits, the password senmd to swift finally not the same one.

swiftmailer:
    transport:  smtp
    encryption: ssl
    auth_mode:  login
    host:       smtp.gmail.com
    username:   your_username
    password:   61548921

you need fix it with double quotes password: "61548921"

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

It helped my case to install the right curl version

sudo apt-get install php5-curl

How to compare files from two different branches?

More modern syntax:

git diff ..master path/to/file

The double-dot prefix means "from the current working directory to". You can also say:

  • master.., i.e. the reverse of above. This is the same as master.
  • mybranch..master, explicitly referencing a state other than the current working tree.
  • v2.0.1..master, i.e. referencing a tag.
  • [refspec]..[refspec], basically anything identifiable as a code state to git.

How to get the previous URL in JavaScript?

If you want to go to the previous page without knowing the url, you could use the new History api.

history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.

But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API

For more information see the doc

How to split CSV files as per number of rows specified?

Use the Linux split command:

split -l 20 file.txt new    

Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.

Type man split at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail command, for example) and then add it back on to each of the split files.

Adding a module (Specifically pymorph) to Spyder (Python IDE)

One can also follow the below steps : Spyder -> Tools -> Open Command Prompt -> write the command "pip install html5lib"

trying to animate a constraint in swift

Watch this.

The video says that you need to just add self.view.layoutIfNeeded() like the following:

UIView.animate(withDuration: 1.0, animations: {
       self.centerX.constant -= 75
       self.view.layoutIfNeeded()
}, completion: nil)

Find a private field with Reflection?

You can do it just like with a property:

FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)
    ...

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

How to break out of jQuery each Loop

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

Is it possible to use if...else... statement in React render function?

If you need more than one condition, so you can try this out

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

passing 2 $index values within nested ng-repeat

Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!

Right way

  <table>
    <tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
        <td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">

          <b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
          <small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>

        </td>
    </tr>
  </table>

Check: plnkr.co/52oIhLfeXXI9ZAynTuAJ

Why isn't my Pandas 'apply' function referencing multiple columns working?

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.

How do I calculate someone's age in Java?

import java.io.*;

class AgeCalculator
{
    public static void main(String args[])
    {
        InputStreamReader ins=new InputStreamReader(System.in);
        BufferedReader hey=new BufferedReader(ins);

        try
        {
            System.out.println("Please enter your name: ");
            String name=hey.readLine();

            System.out.println("Please enter your birth date: ");
            String date=hey.readLine();

            System.out.println("please enter your birth month:");
            String month=hey.readLine();

            System.out.println("please enter your birth year:");
            String year=hey.readLine();

            System.out.println("please enter current year:");
            String cYear=hey.readLine();

            int bDate = Integer.parseInt(date);
            int bMonth = Integer.parseInt(month);
            int bYear = Integer.parseInt(year);
            int ccYear=Integer.parseInt(cYear);

            int age;

            age = ccYear-bYear;
            int totalMonth=12;
            int yourMonth=totalMonth-bMonth;

            System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
        }
        catch(IOException err)
        {
            System.out.println("");
        }
    }
}

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

Pass a local file in to URL in Java

new File(path).toURI().toURL();

Eclipse CDT project built but "Launch Failed. Binary Not Found"

For what it's worth, I had this problem - and the cause was invalid DWARF 3 info in the binary in the selected project (which didn't have any runnable binaries).

The way it work was something like this: I had two projects Main and Library. Main depended on the Library project and the former had an executable, while the latter just produced a static library (that Main linked against).

My run option was set to "Run/Debug -> Launch" setting was set to "launch current, otherwise last" as follows (see bottom right):

Run/Debug settings

If I had the Main project selected, everything would work fine: it would launch the main project. If I had the Library project selected1 it would fail with the error message given by the OP. The reason seemed to be this: since I had the Library project selected, the PE scanner would scan the binary files in the project to see if any were launchable, and because scanning was failing due to this bug the error message popped up before it ever got to "Launch the previously launched application".

I could work around it by:

  1. Making sure the project I wanted to launch was selected, or ...
  2. Changing compilers to one that made DWARF info that Eclipse could parse without failure, or ...
  3. Selecting "Always launch the previously launched application" in the Run/Debug settings - although it might not be your preferred mode of operation.

1 I wouldn't usually select the project directly, of course, it would be indirectly selected because I was working in one of the source files it contained.

What is the difference between <section> and <div>?

<section> means that the content inside is grouped (i.e. relates to a single theme), and should appear as an entry in an outline of the page.

<div>, on the other hand, does not convey any meaning, aside from any found in its class, lang and title attributes.

So no: using a <div> does not define a section in HTML.

From the spec:

<section>

The <section> element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Each section should be identified, typically by including a heading (h1-h6 element) as a child of the <section> element.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site’s home page could be split into sections for an introduction, news items, and contact information.

...

The <section> element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the <div> element instead. A general rule is that the <section> element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.

(https://www.w3.org/TR/html/sections.html#the-section-element)

<div>

The <div> element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements.

Note: Authors are strongly encouraged to view the <div> element as an element of last resort, for when no other element is suitable. Use of more appropriate elements instead of the <div> element leads to better accessibility for readers and easier maintainability for authors.

(https://www.w3.org/TR/html/grouping-content.html#the-div-element)

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

var $select = $(document.getElementById("selectTagName"));
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0]);

How do you know if Tomcat Server is installed on your PC

Open your windows search bar, and search for the keyword Tomcat. If a shortcut file is found instead, you can open the source file location of the shortcut by right-clicking the shortcut file and selecting the Properties.

jQuery UI Dialog individual CSS styling

The standard way to do this is with jQuery UI's CSS Scopes:

<div class="myCssScope">
   <!-- dialog goes here -->
</div>

Unfortunately, the jQuery UI dialog moves the dialog DOM elements to the end of the document, to fix potential z-index issues. This means the scoping won't work (it will no longer have a ".myCssScope" ancestor).

Christoph Herold designed a workaround which I've implemented as a jQuery plugin, maybe that will help.

How do I set default terminal to terminator?

open dconf Editor and go to org > gnome > desktop > application > terminal and change gnome-terminal to terminator