Programs & Examples On #Api key

An application programming interface key (API key) is a code passed in by computer programs calling an API (application programming interface) to identify the calling program, its developer, or its user to the Web site.

Googlemaps API Key for Localhost

If you are working on localhost, create a separate APIkey for your development and then remove restrictions on that key so that your localhost can use it. Remember to not use this key on production, so you don't expose your key to hunters online.

I had the same issue and all attempts to get the restrictions working on my localhost environment was not successful until I created a separate apikey specifically for development and then removed its restrictions. However I don't use that key on production environment, and once am done with developments, I will delete the API key immediately.

I Know this post is late, but for people that will likely face this issue in the future, this is the best route to go.

Adding an .env file to React Project

Today there is a simpler way to do that.

Just create the .env.local file in your root directory and set the variables there. In your case:

REACT_APP_API_KEY = 'my-secret-api-key'

Then you call it en your js file in that way:

process.env.REACT_APP_API_KEY

React supports environment variables since [email protected] .You don't need external package to do that.

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env

*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.

Files priority:

npm start: .env.development.local, .env.development, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm test: .env.test.local, .env.test, .env (note .env.local is missing)

More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Place API key in Headers or URL

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://[email protected]/myresource/myid

This way it can also be passed as headers with basic-auth.

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

Best practice for storing and protecting private API keys in applications

Whatever you do to secure your secret keys is not going to be a real solution. If developer can decompile the application there is no way to secure the key, hiding the key is just security by obscurity and so is code obfuscation. Problem with securing a secret key is that in order to secure it you have to use another key and that key needs to also be secured. Think of a key hidden in a box that is locked with a key. You place a box inside a room and lock the room. You are left with another key to secure. And that key is still going to be hardcoded inside your application.

So unless the user enters a PIN or a phrase there is no way to hide the key. But to do that you would have to have a scheme for managing PINs happening out of band, which means through a different channel. Certainly not practical for securing keys for services like Google APIs.

How to execute logic on Optional if not present?

ifPresentOrElse can handle cases of nullpointers as well. Easy approach.

   Optional.ofNullable(null)
            .ifPresentOrElse(name -> System.out.println("my name is "+ name),
                    ()->System.out.println("no name or was a null pointer"));

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

How to make responsive table

For make responsive table you can make 100% of each ‘td’ and insert related heading in the ‘td’ on the mobile(less the ’768px’ width).

See More:
http://wonderdesigners.com/?p=227

iOS 8 UITableView separator inset 0 not working

In iOS8:

Adding this to my UITableViewCell Subclass:

- (UIEdgeInsets)layoutMargins {
    return UIEdgeInsetsZero;
}

and this to "tableView:cellForRowAtIndexPath" or "tableView:willDisplayCell":

[editCell setSeparatorInset:UIEdgeInsetsZero];

WORKED for me.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

$(window).resize(function() {
  //update stuff
});

Edit and replay XHR chrome/firefox etc?

Updating/completing zszep answer:

After copying the request as cUrl (bash), simply import it in the Postman App:

enter image description here

pandas three-way joining multiple dataframes on columns

One does not need a multiindex to perform join operations. One just need to set correctly the index column on which to perform the join operations (which command df.set_index('Name') for example)

The join operation is by default performed on index. In your case, you just have to specify that the Name column corresponds to your index. Below is an example

A tutorial may be useful.

# Simple example where dataframes index are the name on which to perform
# the join operations
import pandas as pd
import numpy as np
name = ['Sophia' ,'Emma' ,'Isabella' ,'Olivia' ,'Ava' ,'Emily' ,'Abigail' ,'Mia']
df1 = pd.DataFrame(np.random.randn(8, 3), columns=['A','B','C'], index=name)
df2 = pd.DataFrame(np.random.randn(8, 1), columns=['D'],         index=name)
df3 = pd.DataFrame(np.random.randn(8, 2), columns=['E','F'],     index=name)
df = df1.join(df2)
df = df.join(df3)

# If you have a 'Name' column that is not the index of your dataframe,
# one can set this column to be the index
# 1) Create a column 'Name' based on the previous index
df1['Name'] = df1.index
# 1) Select the index from column 'Name'
df1 = df1.set_index('Name')

# If indexes are different, one may have to play with parameter how
gf1 = pd.DataFrame(np.random.randn(8, 3), columns=['A','B','C'], index=range(8))
gf2 = pd.DataFrame(np.random.randn(8, 1), columns=['D'], index=range(2,10))
gf3 = pd.DataFrame(np.random.randn(8, 2), columns=['E','F'], index=range(4,12))

gf = gf1.join(gf2, how='outer')
gf = gf.join(gf3, how='outer')

ExecuteNonQuery doesn't return results

What kind of query do you perform? Using ExecuteNonQuery is intended for UPDATE, INSERT and DELETE queries. As per the documentation:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

react-router (v4) how to go back?

Hope this will help someone:

import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';

interface Props {
  history: History;
}

@withRouter
export default class YourComponent extends React.PureComponent<Props> {

  private onBackClick = (event: React.MouseEvent): void => {
    const { history } = this.props;
    history.goBack();
  };

...

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

Can I load a UIImage from a URL?

The Best and easy way to load Image via Url is by this Code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];

    dispatch_async(dispatch_get_main_queue(), ^{
        imgView.image= [UIImage imageWithData:data];
    });
});

Replace imgUrl by your ImageURL
Replace imgView by your UIImageView.

It will load the Image in another Thread, so It will not slow down your App load.

Set selected item of spinner programmatically

This is stated in comments elsewhere on this page but thought it useful to pull it out into an answer:

When using an adapter, I've found that the spinnerObject.setSelection(INDEX_OF_CATEGORY2) needs to occur after the setAdapter call; otherwise, the first item is always the initial selection.

// spinner setup...
spinnerObject.setAdapter(myAdapter);
spinnerObject.setSelection(INDEX_OF_CATEGORY2);

This is confirmed by reviewing the AbsSpinner code for setAdapter.

React js change child component's state from parent component

You can send a prop from the parent and use it in child component so you will base child's state changes on the sent prop changes and you can handle this by using getDerivedStateFromProps in the child component.

Java 8 Stream and operation on arrays

There are new methods added to java.util.Arrays to convert an array into a Java 8 stream which can then be used for summing etc.

int sum =  Arrays.stream(myIntArray)
                 .sum();

Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.

//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...

int[] result = new int[a.length];

IntStream.range(0, a.length)
         .forEach(i -> result[i] = a[i] * b[i]);

EDIT

Commenter @Holger points out you can use the map method instead of forEach like this:

int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();

ITSAppUsesNonExemptEncryption export compliance while internal testing?

There are basically 2 things to bear in mind. You are only allowed to set it to NO if you either don't use encryption at all, or you are part of the exempt regulations. This applies to the following kind of applications:

Source: Chamber of Commerce: https://www.bis.doc.gov/index.php/policy-guidance/encryption/encryption-faqs#15

Consumer applications

  • piracy and theft prevention for software or music;
  • music, movies, tunes/music, digital photos – players, recorders and organizers
  • games/gaming – devices, runtime software, HDMI and other component interfaces, development tools
  • LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing);
  • printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies
  • household utilities and appliances

Business / systems applications: systems operations, integration and control. Some examples

  • business process automation (BPA) – process planning and scheduling, supply chain management, inventory and delivery

  • transportation – safety and maintenance, systems monitoring and on-board controllers (including aviation, railway, and commercial automotive systems), ‘smart highway’ technologies, public transit operations and fare collection, etc.

  • industrial, manufacturing or mechanical systems - including robotics, plant safety, utilities, factory and other heavy equipment, facilities systems controllers such as fire alarms and HVAC

  • medical / clinical – including diagnostic applications, patient scheduling, and medical data records confidentiality

  • applied geosciences – mining / drilling, atmospheric sampling / weather monitoring, mapping / surveying, dams / hydrology

Research /scientific /analytical. Some examples:

  • business process management (BPM) – business process abstraction and modeling

  • scientific visualization / simulation / co-simulation (excluding such tools for computing, networking, cryptanalysis, etc.)

  • data synthesis tools for social, economic, and political sciences (e.g., economic, population, global climate change, public opinion polling, etc. forecasting and modeling)

Secure intellectual property delivery and installation. Some examples

  • software download auto-installers and updaters

  • license key product protection and similar purchase validation

  • software and hardware design IP protection

  • computer aided design (CAD) software and other drafting tools

Note: These regulations are also true for testing your app using TestFlight

What is the difference between == and equals() in Java?

== is an operator and equals() is a method.

Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.

How can I delete using INNER JOIN with SQL Server?

You don't specify the tables for Company and Date, and you might want to fix that.

Standard SQL using MERGE:

MERGE WorkRecord2 T
   USING Employee S
      ON T.EmployeeRun = S.EmployeeNo
         AND Company = '1'
         AND Date = '2013-05-06'
WHEN MATCHED THEN DELETE;

The answer from Devart is also standard SQL, though incomplete. It should look more like this:

DELETE
  FROM WorkRecord2
  WHERE EXISTS ( SELECT *
                   FROM Employee S
                  WHERE S.EmployeeNo = WorkRecord2.EmployeeRun
                        AND Company = '1'
                        AND Date = '2013-05-06' );

The important thing to note about the above is it is clear the delete is targeting a single table, as enforced in the second example by requiring a scalar subquery.

For me, the various proprietary syntax answers are harder to read and understand. I guess the mindset for is best described in the answer by frans eilering, i.e. the person writing the code doesn't necessarily care about the person who will read and maintain the code.

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Differences in In python 2 and 3 version:

If you already have a default method in a class with same name and you re-declare as a same name it will appear as unbound-method call of that class instance when you wanted to instantiated it.

If you wanted class methods, but you declared them as instance methods instead.

An instance method is a method that is used when to create an instance of the class.

An example would be

   def user_group(self):   #This is an instance method
        return "instance method returning group"

Class label method:

   @classmethod
   def user_group(groups):   #This is an class-label method
        return "class method returning group"

In python 2 and 3 version differ the class @classmethod to write in python 3 it automatically get that as a class-label method and don't need to write @classmethod I think this might help you.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

jQuery is not JavaScript which is more easy to use in some cases.

Look at this example:

<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>

Source: CSS Tricks, MDN

Executing Shell Scripts from the OS X Dock?

I know this is old but in case it is helpful to others:

If you need to run a script and want the terminal to pop up so you can see the results you can do like Abyss Knight said and change the extension to .command. If you double click on it it will open a terminal window and run.

I however needed this to run from automator or appleScript. So to get this to open a new terminal the command I ran from "run shell script" was "open myShellScript.command" and it opened in a new terminal.

Correct way to pass multiple values for same parameter name in GET request

Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

http://localhost/?key[]=1&key[]=2

Returns:

Array
(
[key] => Array
    (
        [0] => 1
        [1] => 2
    )

Redirect to new Page in AngularJS using $location

$location won't help you with external URLs, use the $window service instead:

$window.location.href = 'http://www.google.com';

Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.

SQL not a single-group group function

If you want downloads number for each customer, use:

select ssn
     , sum(time)
  from downloads
 group by ssn

If you want just one record -- for a customer with highest number of downloads -- use:

select *
  from (
        select ssn
             , sum(time)
          from downloads
         group by ssn
         order by sum(time) desc
       )
 where rownum = 1

However if you want to see all customers with the same number of downloads, which share the highest position, use:

select *
  from (
        select ssn
             , sum(time)
             , dense_rank() over (order by sum(time) desc) r
          from downloads
         group by ssn
       )
 where r = 1

How to read a text file from server using JavaScript?

Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax() function.

<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){

  $.ajax({
    url:'text.txt',
    success: function (data){
      //parse your data here
      //you can split into lines using data.split('\n') 
      //an use regex functions to effectively parse it
    }
  });
}
</script>
</head><body>
  <button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>

nginx - read custom header from upstream server

I was facing the same issue. I tried both $http_my_custom_header and $sent_http_my_custom_header but it did not work for me.

Although solved this issue by using $upstream_http_my_custom_header.

Can't find bundle for base name /Bundle, locale en_US

I had the same problemo, and balus solution fixed it.

For the record:

WEB-INF\faces-config is

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <message-bundle>
            Message
        </message-bundle>
    </application>
</faces-config>

And had Message.properties under WebContent\Resources (after mkyong's tutorial)

the pesky exception appeared even when i renamed the bundle to "Message_en_us" and "Message_en". Moving it to src\ worked.

Should someone post the missing piece to make bundles work under resources,it would be a beautiful thing.

jQuery Validation plugin: disable validation for specified submit buttons

I have two button for form submission, button named save and exit bypasses the validation :

$('.save_exist').on('click', function (event) {
            $('#MyformID').removeData('validator');
            $('.form-control').removeClass('error');
            $('.form-control').removeClass('required');                
            $("#loanApplication").validate().cancelSubmit = true;
            $('#loanApplication').submit();
            event.preventDefault();
});

Removing html5 required attribute with jQuery

Even though the ID selector is the simplest, you can also use the name selector as below:

$('[name='submitted[first_name]']').removeAttr('required');

For more see: https://api.jquery.com/attribute-equals-selector/

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

Cannot run Eclipse; JVM terminated. Exit code=13

Go to the folder where you saved Eclipse. Look in the configuration folder at the startup log. It will give you a much better diagnostic than "exit code 13".

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

Random "Element is no longer attached to the DOM" StaleElementReferenceException

Yes, if you're having problems with StaleElementReferenceExceptions it's because there is a race condition. Consider the following scenario:

WebElement element = driver.findElement(By.id("foo"));
// DOM changes - page is refreshed, or element is removed and re-added
element.click();

Now at the point where you're clicking the element, the element reference is no longer valid. It's close to impossible for WebDriver to make a good guess about all the cases where this might happen - so it throws up its hands and gives control to you, who as the test/app author should know exactly what may or may not happen. What you want to do is explicitly wait until the DOM is in a state where you know things won't change. For example, using a WebDriverWait to wait for a specific element to exist:

// times out after 5 seconds
WebDriverWait wait = new WebDriverWait(driver, 5);
    
// while the following loop runs, the DOM changes - 
// page is refreshed, or element is removed and re-added
wait.until(presenceOfElementLocated(By.id("container-element")));        

// now we're good - let's click the element
driver.findElement(By.id("foo")).click();

The presenceOfElementLocated() method would look something like this:

private static Function<WebDriver,WebElement> presenceOfElementLocated(final By locator) {
    return new Function<WebDriver, WebElement>() {
        @Override
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    };
}

You're quite right about the current Chrome driver being quite unstable, and you'll be happy to hear that the Selenium trunk has a rewritten Chrome driver, where most of the implementation was done by the Chromium developers as part of their tree.

PS. Alternatively, instead of waiting explicitly like in the example above, you can enable implicit waits - this way WebDriver will always loop up until the specified timeout waiting for the element to become present:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)

In my experience though, explicitly waiting is always more reliable.

How do I create an .exe for a Java program?

Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).

As for wrappers, the best ones i've used (as previously suggested) are:

JSmooth

and

Launch4j

best of luck!

How to switch to the new browser window, which opens after click on the button?

Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();

Draw horizontal rule in React Native

Just create a View component which has small height.

<View style={{backgroundColor:'black', height:10}}/>

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

add created_at and updated_at fields to mongoose schemas

I actually do this in the back

If all goes well with the updating:

 // All ifs passed successfully. Moving on the Model.save
    Model.lastUpdated = Date.now(); // <------ Now!
    Model.save(function (err, result) {
      if (err) {
        return res.status(500).json({
          title: 'An error occured',
          error: err
        });
      }
      res.status(200).json({
        message: 'Model Updated',
        obj: result
      });
    });

HttpClient does not exist in .net 4.0: what can I do?

read this...

Portable HttpClient for .NET Framework and Windows Phone

see paragraph Using HttpClient on .NET Framework 4.0 or Windows Phone 7.5 http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

PHP date() with timezone?

Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.

$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');

See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php

How to iterate over the keys and values with ng-repeat in AngularJS?

we can follow below procedure to avoid display of key-values in alphabetical order.

Javascript

$scope.data = {
   "id": 2,
   "project": "wewe2012",
   "date": "2013-02-26",
   "description": "ewew",
   "eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
    var test = {};
    test[key]=$scope.data[key];
    array.push(test);
}
$scope.data = array;

HTML

<p ng-repeat="obj in data">
   <font ng-repeat="(key, value) in obj">
      {{key}} : {{value}}
   </font>
</p>

React.js create loop through Array

You can simply do conditional check before doing map like

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   })
}

Now a days .map can be done in two different ways but still the conditional check is required like

.map with return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
   return <li key={player.championId}>{player.summonerName}</li>
 })
}

.map without return

{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
   return <li key={player.championId}>{player.summonerName}</li>
 ))
}

both the above functionalities does the same

How to change TextField's height and width?

You can try the margin property in the Container. Wrap the TextField inside a Container and adjust the margin property.

new Container(
  margin: const EdgeInsets.only(right: 10, left: 10),
  child: new TextField( 
    decoration: new InputDecoration(
      hintText: 'username',
      icon: new Icon(Icons.person)),
  )
),

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

Running code in main thread from another thread

One method I can think of is this:

1) Let the UI bind to the service.
2) Expose a method like the one below by the Binder that registers your Handler:

public void registerHandler(Handler handler) {
    mHandler = handler;
}

3) In the UI thread, call the above method after binding to the service:

mBinder.registerHandler(new Handler());

4) Use the handler in the Service's thread to post your task:

mHandler.post(runnable);

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

Prevent form submission on Enter key press

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

HashSet vs LinkedHashSet

All Methods and constructors are same but only one difference is LinkedHashset will maintain insertion order but it will not allow duplicates.

Hashset will not maintain any insertion order. It is combination of List and Set simple :)

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

How to find which views are using a certain table in SQL Server (2008)?

If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

enter image description here

enter image description here

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

How to get an object's property's value by property name?

$com1 = new-object PSobject                                                         #Task1
$com2 = new-object PSobject                                                         #Task1
$com3 = new-object PSobject                                                         #Task1



$com1 | add-member noteproperty -name user -value jindpal                           #Task2
$com1 | add-member noteproperty -name code -value IT01                              #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com2 | add-member noteproperty -name user -value singh                             #Task2
$com2 | add-member noteproperty -name code -value IT02                              #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com3 | add-member noteproperty -name user -value dhanoa                             #Task2
$com3 | add-member noteproperty -name code -value IT03                               #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}        #Task3


$arr += $com1, $com2, $com3                                                          #Task4


write-host "windows version of computer1 is: "$com1.ver()                            #Task3
write-host "user name of computer1 is: "$com1.user                                   #Task6
write-host "code of computer1 is: "$com1,code                                        #Task5
write-host "windows version of computer2 is: "$com2.ver()                            #Task3
write-host "user name of computer2 is: "$com2.user                                   #Task6
write-host "windows version of computer3 is: "$com3.ver()                            #Task3
write-host "user name of computer3 is: "$com1.user                                   #Task6
write-host "code of computer3 is: "$com3,code                                        #Task5

read-host

Strip HTML from Text JavaScript

Another, admittedly less elegant solution than nickf's or Shog9's, would be to recursively walk the DOM starting at the <body> tag and append each text node.

var bodyContent = document.getElementsByTagName('body')[0];
var result = appendTextNodes(bodyContent);

function appendTextNodes(element) {
    var text = '';

    // Loop through the childNodes of the passed in element
    for (var i = 0, len = element.childNodes.length; i < len; i++) {
        // Get a reference to the current child
        var node = element.childNodes[i];
        // Append the node's value if it's a text node
        if (node.nodeType == 3) {
            text += node.nodeValue;
        }
        // Recurse through the node's children, if there are any
        if (node.childNodes.length > 0) {
            appendTextNodes(node);
        }
    }
    // Return the final result
    return text;
}

How to display multiple notifications in android

Replace your line with this.

notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);

How to draw border around a UILabel?

UILabel properties borderColor,borderWidth,cornerRadius in Swift 4

@IBOutlet weak var anyLabel: UILabel!
   override func viewDidLoad() {
        super.viewDidLoad()
        anyLabel.layer.borderColor = UIColor.black.cgColor
        anyLabel.layer.borderWidth = 2
        anyLabel.layer.cornerRadius = 5
        anyLabel.layer.masksToBounds = true
}

onKeyDown event not working on divs in React

You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div 
      className="player"
      style={{ position: "absolute" }}
      onKeyDown={this.onKeyPressed}
    >
      <div className="light-circle">
        <div className="image-wrapper">
          <img src={IMG_URL+player.img} />
        </div>
      </div>
    </div>
  )
}

c++ integer->std::string conversion. Simple function?

Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);

it also provides some safety:

try{
  std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
 ...
}

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

Remove all line breaks from a long string of text

The canonic answer, in Python, would be :

s = ''.join(s.splitlines())

It splits the string into lines (letting Python doing it according to its own best practices). Then you merge it. Two possibilities here:

  • replace the newline by a whitespace (' '.join())
  • or without a whitespace (''.join())

How to know a Pod's own IP address from inside a container in the Pod?

In some cases, instead of relying on downward API, programmatically reading the local IP address (from network interfaces) from inside of the container also works.

For example, in golang: https://stackoverflow.com/a/31551220/6247478

SQL server ignore case in a where expression

What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.

Filter array to have unique values

You can use Map and Spread Operator:

_x000D_
_x000D_
var rawData = ["X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11", "X_row7", "X_row4", "X_row6", "X_row10", "X_row8", "X_row9", "X_row11"];_x000D_
_x000D_
var unique = new Map();_x000D_
rawData.forEach(d => unique.set(d, d));_x000D_
var uniqueItems = [...unique.keys()];_x000D_
_x000D_
console.log(uniqueItems);
_x000D_
_x000D_
_x000D_

Error in file(file, "rt") : cannot open the connection

This error also occurs when you try to use the result of getwd() directly in the path. The problem is the missingness of the "/" at the end. Try the following code:

projectFolder <- paste(getwd(), "/", sep = '')

The paste() is to concatenate the forward slash at the end.

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

How to download file in swift?

iOS 13 Swift 5, 5.1

@IBAction func btnDownload(_ sender: Any) {
    
    // file location to save download file
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent(statementPDF)
        return (documentsURL, [.removePreviousFile])
    }
    
    // Alamofire to download file
    Alamofire.download("http://pdf_url", to: destination).responseData { response in
        hideLoader()
        switch response.result {
        case .success:
            // write something here
            if response.destinationURL != nil {
                showAlertMessage(titleStr: APPNAME, messageStr: "File Saved in Documents!")
                
            }
        case .failure:
            showAlertMessage(titleStr: APPNAME, messageStr: response.result.error.debugDescription)
        }
    }
}

Please add these permissions to info.plist, so you will able to check the download file in Document Directory

<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>

Check if the file exists using VBA

based on other answers here I'd like to share my one-liners that should work for dirs and files:

  • Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
    
    • (just Len(Dir(path)) did not work for directories (Excel 2010 / Win7))
  • CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
    

as PathExists(path) function:

Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function

Spring MVC: How to return image in @ResponseBody?

By using Spring 3.1.x and 3.2.x, this is how you should do it:

The controller method:

@RequestMapping("/photo2")
public @ResponseBody byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}

And the mvc annotation in servlet-context.xml file:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>image/jpeg</value>
                    <value>image/png</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.

If you just want to compute some derived data, either:

  1. Do it right inside render
  2. Or, if re-calculating it is expensive, use a memoization helper like memoize-one.

Here's the simplest "after" example:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

Check out this section of the blog post to learn more.

How to get `DOM Element` in Angular 2?

Update (using renderer):

Note that the original Renderer service has now been deprecated in favor of Renderer2

as on Renderer2 official doc.

Furthermore, as pointed out by @GünterZöchbauer:

Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.


You can achieve this by using elementRef as well as by ViewChild. however it's not recommendable to use elementRef due to:

  • security issue
  • tight coupling

as pointed out by official ng2 documentation.

1. Using elementRef (Direct Access):

export class MyComponent {    
constructor (private _elementRef : ElementRef) {
 this._elementRef.nativeElement.querySelector('textarea').focus();
 }
}

2. Using ViewChild (better approach):

<textarea  #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}" 
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var


export class MyComponent implements AfterViewInit {
  @ViewChild('tasknote') input: ElementRef;

   ngAfterViewInit() {
    this.input.nativeElement.focus();

  }
}

3. Using renderer:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of depreaced invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

What do you want to do with this unique ID? Maybe you can do what you want without this ID.

The MAC address maybe is one option but this is not an trusted unique ID because the user can change the MAC address of a computer.

To get the motherboard or processor ID check on this link.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

To create an image for the UIToolbar, make a png in photoshop and WHERE EVER there is ANY colour it puts it white, and where it's alpha = 0 then it leaves it alone.

The SDK actually put's the border around the icon you have made and turns it white without you having to do anything.

See, this is what I made in Photoshop for my forward button (obviously swap it around for back button):

http://twitpic.com/1oanv

and this is what it appeared like in Interface Builder

http://twitpic.com/1oaoa

What do >> and << mean in Python?

The other case involving print >>obj, "Hello World" is the "print chevron" syntax for the print statement in Python 2 (removed in Python 3, replaced by the file argument of the print() function). Instead of writing to standard output, the output is passed to the obj.write() method. A typical example would be file objects having a write() method. See the answer to a more recent question: Double greater-than sign in Python.

Get names of all files from a folder with Ruby

The following snippets exactly shows the name of the files inside a directory, skipping subdirectories and ".", ".." dotted folders:

Dir.entries("your/folder").select { |f| File.file? File.join("your/folder", f) }

Sending an Intent to browser to open specific URL

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

raw_input function in Python

The raw_input() function reads a line from input (i.e. the user) and returns a string

Python v3.x as raw_input() was renamed to input()

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

Ref: Docs Python 3

image processing to improve tesseract OCR accuracy

you can do noise reduction and then apply thresholding, but that you can you can play around with the configuration of the OCR by changing the --psm and --oem values

try: --psm 5 --oem 2

you can also look at the following link for further details here

Rendering React Components from Array of Objects

This is quite likely the simplest way to achieve what you are looking for.

In order to use this map function in this instance, we will have to pass a currentValue (always-required) parameter, as well an index (optional) parameter. In the below example, station is our currentValue, and x is our index.

station represents the current value of the object within the array as it is iterated over. x automatically increments; increasing by one each time a new object is mapped.

render () {
    return (
        <div>
            {stations.map((station, x) => (
                <div key={x}> {station} </div>
            ))}
        </div>
    );
}

What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.

Java properties UTF-8 encoding in Eclipse

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));

this works well in java 1.6. How can i do this in 1.5, Since Properties class does not have a method to pars InputStreamReader.

How To: Execute command line in C#, get STD OUT results

There is a ProcessHelper Class in PublicDomain open source code which might interest you.

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

You should restart your Xampp or whatever server you're runnung, make sure sq

Nullable DateTime conversion

You can try this

var lastPostDate = reader[3] == DBNull.Value ?
                                default(DateTime?): 
                                Convert.ToDateTime(reader[3]);

Could not resolve all dependencies for configuration ':classpath'

In my case, my Android Studio version was 3.6.1 and i have modified the classpath like below;

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

and that error was gone.

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

How to handle query parameters in angular 2

To complement the two previous answers, Angular2 supports both query parameters and path variables within routing. In @RouteConfig definition, if you define parameters within a path, Angular2 handles them as path variables and as query parameters if not.

Let's take a sample:

@RouteConfig([
  { path: '/:id', component: DetailsComponent, name: 'Details'}
])

If you call the navigate method of the router like this:

this.router.navigate( [
  'Details', { id: 'companyId', param1: 'value1'
}]);

You will have the following address: /companyId?param1=value1. The way to get parameters is the same for both, query parameters and path variables. The difference between them is that path variables can be seen as mandatory parameters and query parameters as optional ones.

Hope it helps you, Thierry

UPDATE: After changes in router alpha.31 http query params no longer work (Matrix params #2774). Instead angular router uses so called Matrix URL notation.

Reference https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:

The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.

Finding the Eclipse Version Number

1 - Open Eclipse IDE. 2 - Press: Alt + H 3 - Use keyboard arrows to go dwn the list 4 - Select About Eclipse IDE tab.

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

How to compile and run C files from within Notepad++ using NppExec plugin?

I've made a single powerfull script that will:

-Compile and run multi language code like C, C++, Java, Python and C#.
-Delete the old executable before compiling code.
-Only run the code if it's compiled successfully.

I've also made a very noob friendly tutorial Transform Notepad++ to Powerful Multi Languages IDE which contains some additional scripts like to only run or Compile the code, run code inside CMD etc.

npp_console 1               //open console
NPP_CONSOLE -               //disable output of commands
npe_console m-              //disable unnecessary output
con_colour bg= 191919 fg= F5F5F5    //set console colors
npp_save                //save the file
cd $(CURRENT_DIRECTORY)         //follow current directory
NPP_CONSOLE +               //enable output
IF $(EXT_PART)==.c GOTO C       //if .c file goto C label
IF $(EXT_PART)==.cpp GOTO CPP       //if .cpp file goto CPP label
IF $(EXT_PART)==.java GOTO JAVA     //if .java file goto JAVA label
IF $(EXT_PART)==.cs GOTO C#     //if .cs file goto C# label
IF $(EXT_PART)==.py GOTO PYTHON     //if .py file goto PYTHON label
echo FILE SAVED
GOTO EXITSCRIPT             // else treat it as a text file and goto EXITSCRIPT
//C label
:C                                                                  
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"//delete existing executable file if exists
gcc "$(FILE_NAME)" -o $(NAME_PART)              //compile file
IF $(EXITCODE) != 0 GOTO EXITSCRIPT             //if any compilation error then abort
echo C CODE COMPILED SUCCESSFULLY:              //print message on console
$(NAME_PART)                                            //run file in cmd, set color to green and pause cmd after output
GOTO EXITSCRIPT                         //finally exits

:CPP
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
g++ "$(FILE_NAME)" -o $(NAME_PART)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C++ CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:JAVA
cmd /C if exist "$(NAME_PART).class" cmd /c del "$(NAME_PART).class"
javac $(FILE_NAME) -Xlint
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo JAVA CODE COMPILED SUCCESSFULLY:
java $(NAME_PART)
GOTO EXITSCRIPT

:C#
cmd /C if exist "$(NAME_PART).exe" cmd /c del "$(NAME_PART).exe"
csc $(FILE_NAME)
IF $(EXITCODE) != 0 GOTO EXITSCRIPT
echo C# CODE COMPILED SUCCESSFULLY:
$(NAME_PART)
GOTO EXITSCRIPT

:PYTHON
echo RUNNING PYTHON SCRIPT IN CMD:              //python is a script so no need to compile
python $(NAME_PART).py
GOTO EXITSCRIPT

:EXITSCRIPT
// that's all, folks!

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
{
    public static string CompressToBase64(this string data)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
    }

    public static string DecompressFromBase64(this string data)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    }
    
    public static byte[] Compress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.CompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }

    public static byte[] Decompress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.DecompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }
    
    public static void CompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
        {
            stream.CopyTo(gZipStream);
            gZipStream.Flush();
        }
    }

    public static void DecompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
        {
            gZipStream.CopyTo(outputStream);
        }
    }
}

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

Select all 'tr' except the first one

I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:

tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */

They both function in exactly the same way (in the context of HTML tables anyway) as:

tr:not(:first-child)

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

How to preserve request url with nginx proxy_pass

I think the proxy_set_header directive could help:

location / {
    proxy_pass http://my_app_upstream;
    proxy_set_header Host $host;
    # ...
}

SVG: text inside rect

Programmatically using D3:

body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').transition().duration(500).attr('width', 150)
                .attr('height', 100)
                .attr('x', 40)
                .attr('y', 100)
                .style('fill', 'white')
                .attr('stroke', 'black')
text = svg.append('text').text('This is some information about whatever')
                .attr('x', 50)
                .attr('y', 150)
                .attr('fill', 'black')

jQuery delete all table rows except first

Another way to accomplish this is using the empty() function of jQuery with the thead and tbody elements in your table.

Example of a table:

<table id="tableId">
<thead>
    <tr><th>Col1</th><th>Col2</th></tr>
</thead>
<tbody>
    <tr><td>some</td><td>content</td></tr>
    <tr><td>to be</td><td>removed</td></tr>
</tbody>
</table>

And the jQuery command:

$("#tableId > tbody").empty();

This will remove every rows contained in the tbody element of your table and keep the thead element where your header should be. It can be useful when you want to refresh only the content of a table.

READ_EXTERNAL_STORAGE permission for Android

I also had a similar error log and here's what I did-

  1. In onCreate method we request a Dialog Box for checking permissions

    ActivityCompat.requestPermissions(MainActivity.this,
    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
    
  2. Method to check for the result

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission granted and now can proceed
             mymethod(); //a sample method called
    
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // add other cases for more permissions
        }
    }
    

The official documentation to Requesting Runtime Permissions

@viewChild not working - cannot read property nativeElement of undefined

You'll also get this error if your target element is inside a hidden element. If this is your HTML:

<div *ngIf="false">
    <span #sp>Hello World</span>
</div>

Your @ViewChild('sp') sp will be undefined.

Solution

In such a case, then don't use *ngIf.

Instead use a class to show/hide your element being hidden.

<div [class.show]="shouldShow">...</div>

Nullable type as a generic parameter possible?

I just encountered the same problem myself.

... = reader["myYear"] as int?; works and is clean.

It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

JavaScript DOM: Find Element Index In Container

2017 update

The original answer below assumes that the OP wants to include non-empty text node and other node types as well as elements. It doesn't seem clear to me now from the question whether this is a valid assumption.

Assuming instead you just want the element index, previousElementSibling is now well-supported (which was not the case in 2012) and is the obvious choice now. The following (which is the same as some other answers here) will work in everything major except IE <= 8.

function getElementIndex(node) {
    var index = 0;
    while ( (node = node.previousElementSibling) ) {
        index++;
    }
    return index;
}

Original answer

Just use previousSibling until you hit null. I'm assuming you want to ignore white space-only text nodes; if you want to filter other nodes then adjust accordingly.

function getNodeIndex(node) {
    var index = 0;
    while ( (node = node.previousSibling) ) {
        if (node.nodeType != 3 || !/^\s*$/.test(node.data)) {
            index++;
        }
    }
    return index;
}

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

Chain-calling parent initialisers in python

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".

XML Parsing - Read a Simple XML File and Retrieve Values

Try XmlSerialization

try this

[Serializable]
public class Task
{
    public string Name{get; set;}
    public string Location {get; set;}
    public string Arguments {get; set;}
    public DateTime RunWhen {get; set;}
}

public void WriteXMl(Task task)
{
    XmlSerializer serializer;
    serializer = new XmlSerializer(typeof(Task));

    MemoryStream stream = new MemoryStream();

    StreamWriter writer = new StreamWriter(stream, Encoding.Unicode);
    serializer.Serialize(writer, task);

    int count = (int)stream.Length;

     byte[] arr = new byte[count];
     stream.Seek(0, SeekOrigin.Begin);

     stream.Read(arr, 0, count);

     using (BinaryWriter binWriter=new BinaryWriter(File.Open(@"C:\Temp\Task.xml", FileMode.Create)))
     {
         binWriter.Write(arr);
     }
 }

 public Task GetTask()
 {
     StreamReader stream = new StreamReader(@"C:\Temp\Task.xml", Encoding.Unicode);
     return (Task)serializer.Deserialize(stream);
 }

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Have you tried Refinements?

module Nothingness
  refine String do
    alias_method :nothing?, :empty?
  end

  refine NilClass do
    alias_method :nothing?, :nil?
  end
end

using Nothingness

return my_string.nothing?

Stop mouse event propagation

Adding false after function will stop event propagation

<a (click)="foo(); false">click with stop propagation</a>

SQL: sum 3 columns when one column has a null value?

SELECT sum(isnull(TotalHoursM,0)) 
         + isnull(TotalHoursT,0) 
         + isnull(TotalHoursW,0) 
         + isnull(TotalHoursTH,0) 
         + isnull(TotalHoursF,0))
AS TOTAL FROM LeaveRequest

position: fixed doesn't work on iPad and iPhone

Even though the CSS attribute {position:fixed;} seems (mostly) working on newer iOS devices, it is possible to have the device quirk and fallback to {position:relative;} on occasion and without cause or reason. Usually clearing the cache will help, until something happens and the quirk happens again.

Specifically, from Apple itself Preparing Your Web Content for iPad:

Safari on iPad and Safari on iPhone do not have resizable windows. In Safari on iPhone and iPad, the window size is set to the size of the screen (minus Safari user interface controls), and cannot be changed by the user. To move around a webpage, the user changes the zoom level and position of the viewport as they double tap or pinch to zoom in or out, or by touching and dragging to pan the page. As a user changes the zoom level and position of the viewport they are doing so within a viewable content area of fixed size (that is, the window). This means that webpage elements that have their position "fixed" to the viewport can end up outside the viewable content area, offscreen.

What is ironic, Android devices do not seem to have this issue. Also it is entirely possible to use {position:absolute;} when in reference to the body tag and not have any issues.

I found the root cause of this quirk; that it is the scroll event not playing nice when used in conjunction with the HTML or BODY tag. Sometimes it does not like to fire the event, or you will have to wait until the scroll swing event is finished to receive the event. Specifically, the viewport is re-drawn at the end of this event and fixed elements can be re-positioned somewhere else in the viewport.

So this is what I do: (avoid using the viewport, and stick with the DOM!)

<html>
  <style>
    .fixed{
      position:fixed;
      /*you can set your other static attributes here too*/
      /*like height and width, margin, etc.*/
      }
    .scrollableDiv{
      position:relative;
      overflow-y:scroll;
      /*all children will scroll within this like the body normally would.*/
      } 
    .viewportSizedBody{
      position:relative;
      overflow:hidden;
      /*this will prevent the body page itself from scrolling.*/
      } 
  </style>
  <body class="viewportSizedBody">
    <div id="myFixedContainer" class="fixed">
       This part is fixed.
    </div>
    <div id="myScrollableBody" class="scrollableDiv">
       This part is scrollable.
    </div>
  </body>
  <script type="text/javascript" src="{your path to jquery}/jquery-1.7.2.min.js"></script>
  <script>
    var theViewportHeight=$(window).height();
    $('.viewportSizedBody').css('height',theViewportHeight);
    $('#myScrollableBody').css('height',theViewportHeight);
  </script>
</html>

In essence this will cause the BODY to be the size of the viewport and non-scrollable. The scrollable DIV nested inside will scroll as the BODY normally would (minus the swing effect, so the scrolling does stop on touchend.) The fixed DIV stays fixed without interference.

As a side note, a high z-index value on the fixed DIV is important to keep the scrollable DIV appear to be behind it. I normally add in window resize and scroll events also for cross-browser and alternate screen resolution compatibility.

If all else fails, the above code will also work with both the fixed and scrollable DIVs set to {position:absolute;}.

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

Implement a simple factory pattern with Spring 3 annotations

Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:

    public interface NamedService {
       String name();
    }

and add abstract class:

public abstract class AbstractFactory<T extends NamedService> {

    private final Map<String, T> map;

    protected AbstractFactory(List<T> list) {
        this.map = list
                .stream()
                .collect(Collectors.toMap(NamedService::name, Function.identity()));
    }

    /**
     * Factory method for getting an appropriate implementation of a service
     * @param name name of service impl.
     * @return concrete service impl.

     */
    public T getInstance(@NonNull final String name) {
        T t = map.get(name);
        if(t == null)
            throw new RuntimeException("Unknown service name: " + name);
        return t;
    }
}

Then we create a concrete factory of specific objects like MyService:

 public interface MyService extends NamedService {
           String name();
           void doJob();
 }

@Component
public class MyServiceFactory extends AbstractFactory<MyService> {

    @Autowired
    protected MyServiceFactory(List<MyService> list) {
        super(list);
    }
}

where List the list of implementations of MyService interface at compile time.

This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.

if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

How can I check if a string contains ANY letters from the alphabet?

Regex should be a fast approach:

re.search('[a-zA-Z]', the_string)

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

Base 64 encode and decode example code

'java.util.Base64' class provides functionality to encode and decode the information in Base64 format.

How to get Base64 Encoder?

Encoder encoder = Base64.getEncoder();

How to get Base64 Decoder?

Decoder decoder = Base64.getDecoder();

How to encode the data?

Encoder encoder = Base64.getEncoder();
String originalData = "java";
byte[] encodedBytes = encoder.encode(originalData.getBytes());

How to decode the data?

Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedBytes);
String decodedStr = new String(decodedBytes);

You can get more details at this link.

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

Is < faster than <=?

For floating point code, the <= comparison may indeed be slower (by one instruction) even on modern architectures. Here's the first function:

int compare_strict(double a, double b) { return a < b; }

On PowerPC, first this performs a floating point comparison (which updates cr, the condition register), then moves the condition register to a GPR, shifts the "compared less than" bit into place, and then returns. It takes four instructions.

Now consider this function instead:

int compare_loose(double a, double b) { return a <= b; }

This requires the same work as compare_strict above, but now there's two bits of interest: "was less than" and "was equal to." This requires an extra instruction (cror - condition register bitwise OR) to combine these two bits into one. So compare_loose requires five instructions, while compare_strict requires four.

You might think that the compiler could optimize the second function like so:

int compare_loose(double a, double b) { return ! (a > b); }

However this will incorrectly handle NaNs. NaN1 <= NaN2 and NaN1 > NaN2 need to both evaluate to false.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

orderBy multiple fields in Angular

Sorting can be done by using 'orderBy' filter in angular.

Two ways: 1. From view 2. From controller

  1. From view

Syntax:

{{array | orderBy : expression : reverse}} 

For example:

 <div ng-repeat="user in users | orderBy : ['name', 'age'] : true">{{user.name}}</div>
  1. From controller

Syntax:

$filter.orderBy(array, expression, reverse);

For example:

$scope.filteredArray = $filter.orderBy($scope.users, ['name', 'age'], true);

What are the differences between a HashMap and a Hashtable in Java?

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. ut there are many differences between HashMap and Hashtable classes that are given below.

enter image description here

How to call C++ function from C?

export your C++ functions as extern "C" (aka C style symbols), or use the .def file format to define undecorated export symbols for the C++ linker when it creates the C++ library, then the C linker should have no troubles reading it

Switch tabs using Selenium WebDriver with Java

To get parent window handles.

String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
    String currentHandle ="";
    Set<String> win  = ts.getDriver().getWindowHandles();   

    Iterator<String> it =  win.iterator();
    if(win.size() > 1){
        while(it.hasNext()){
            String handle = it.next();
            if (!handle.equalsIgnoreCase(parentHandle)){
                ts.getDriver().switchTo().window(handle);
                currentHandle = handle;
            }
        }
    }
    else{
        System.out.println("Unable to switch");
    }
    return currentHandle;
}

Can't append <script> element

This is what I think is the best solution. Google Analytics is injected this way.

var (function(){
    var p="https:" == document.location.protocol ? "https://" : "http://";
        d=document,
        g=d.createElement('script'),
        s=d.getElementsByTagName('script')[0];
        g.type='text/javascript';
        g.src=p+'url-to-your-script.js';
        s.parentNode.insertBefore(g,s); })();

How to gracefully handle the SIGKILL signal in Java

I would expect that the JVM gracefully interrupts (thread.interrupt()) all the running threads created by the application, at least for signals SIGINT (kill -2) and SIGTERM (kill -15).

This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.

But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode).

As other users commented, the usage of shutdown hooks seems mandatory.

So, how do I would handle it?

Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).

As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.

So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Interrupting threads");
        Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
        for (Thread th : runningThreads) {
            if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.getClass().getName().startsWith("org.brutusin")) {
                System.out.println("Interrupting '" + th.getClass() + "' termination");
                th.interrupt();
            }
        }
        for (Thread th : runningThreads) {
            try {
                if (th != Thread.currentThread() 
                && !th.isDaemon() 
                && th.isInterrupted()) {
                    System.out.println("Waiting '" + th.getName() + "' termination");
                    th.join();
                }
            } catch (InterruptedException ex) {
                System.out.println("Shutdown interrupted");
            }
        }
        System.out.println("Shutdown finished");
    }
});

Complete test application at github: https://github.com/idelvall/kill-test

PHP Adding 15 minutes to Time value

Current date and time

$current_date_time = date('Y-m-d H:i:s');

15 min ago Date and time

$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));

Redirecting unauthorized controller in ASP.NET MVC

You should build your own Authorize-filter attribute.

Here's mine to study ;)

Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
    Private _role As String

    Public Property Role() As String
        Get
            Return Me._role
        End Get
        Set(ByVal value As String)
            Me._role = value
        End Set
    End Property

    Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        If Not String.IsNullOrEmpty(Me.Role) Then
            If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
                Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
                Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
                Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

                filterContext.HttpContext.Response.Redirect(loginUrl, True)
            Else
                Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
                If Not hasAccess Then
                    Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
                End If
            End If
        Else
            Throw New InvalidOperationException("No Role Specified")
        End If

    End Sub
End Class

What is the difference between a URI, a URL and a URN?

After reading through the posts, I find some very relevant comments. In short, the confusion between the URL and URI definitions is based in part on which definition depends on which and also informal use of the word URI in software development.

By definition URL is a subset of URI [RFC2396]. URI contain URN and URL. Both URI and URL each have their own specific syntax that confers upon them the status of being either URI or URL. URN are for uniquely identifying a resource while URL are for locating a resource. Note that a resource can have more than one URL but only a single URN.[RFC2611]

As web developers and programmers we will almost always be concerned with URL and therefore URI. Now a URL is specifically defined to have all the parts scheme:scheme-specific-part, like for example https://stackoverflow.com/questions. This is a URL and it is also a URI. Now consider a relative link embedded in the page such as ../index.html. This is no longer a URL by definition. It is still what is referred to as a "URI-reference" [RFC2396].

I believe that when the word URI is used to refer to relative paths, "URI-reference" is actually what is being thought of. So informally, software systems use URI to refer to relative pathing and URL for the absolute address. So in this sense, a relative path is no longer a URL but still URI.

How to show alert message in mvc 4 controller?

Use this:

return JavaScript(alert("Hello this is an alert"));

or:

return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");

How to call a method after bean initialization is complete?

To further clear any confusion about the two approach i.e use of

  1. @PostConstruct and
  2. init-method="init"

From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.

Prevent line-break of span element

Put this in your CSS:

white-space:nowrap;

Get more information here: http://www.w3.org/wiki/CSS/Properties/white-space

white-space

The white-space property declares how white space inside the element is handled.

Values

normal This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre This value prevents user agents from collapsing sequences of white space. Lines are only broken at newlines in the source, or at occurrences of "\A" in generated content.

nowrap This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap This value prevents user agents from collapsing sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

pre-line This value directs user agents to collapse sequences of white space. Lines are broken at newlines in the source, at occurrences of "\A" in generated content, and as necessary to fill line boxes.

inherit Takes the same specified value as the property for the element's parent.

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

If you look at the PHP constant PATH_SEPARATOR, you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts.

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/php

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

For your first require, if that is being included from your index.php, then you dont need the dir stuff, just do...

require_once ( 'db/config.php');

Send value of submit button when form gets posted

Use this instead:

<input id='tea-submit' type='submit' name = 'submit'    value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>

Strip all non-numeric characters from string in JavaScript

Short function to remove all non-numeric characters but keep the decimal (and return the number):

_x000D_
_x000D_
parseNum = str => +str.replace(/[^.\d]/g, '');_x000D_
let str = 'a1b2c.d3e';_x000D_
console.log(parseNum(str));
_x000D_
_x000D_
_x000D_

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

Quick answer : Add proxy configuration with parameter for both install/update

gem install --http-proxy http://host:port/ package_name

gem update --http-proxy http://host:port/ package_name

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

Maven Installation OSX Error Unsupported major.minor version 51.0

The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

In my case my JDK installation is jdk1.8.0_40, make sure you type yours.

Then you can use maven commands.

Regards!

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

Just as others said, you can perform a case sensitive search. Or just change the collation format of a specified column as me. For the User/Password columns in my database I change them to collation through the following command:

ALTER TABLE `UserAuthentication` CHANGE `Password` `Password` VARCHAR(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL;

ETag vs Header Expires

They are slightly different - the ETag does not have any information that the client can use to determine whether or not to make a request for that file again in the future. If ETag is all it has, it will always have to make a request. However, when the server reads the ETag from the client request, the server can then determine whether to send the file (HTTP 200) or tell the client to just use their local copy (HTTP 304). An ETag is basically just a checksum for a file that semantically changes when the content of the file changes.

The Expires header is used by the client (and proxies/caches) to determine whether or not it even needs to make a request to the server at all. The closer you are to the Expires date, the more likely it is the client (or proxy) will make an HTTP request for that file from the server.

So really what you want to do is use BOTH headers - set the Expires header to a reasonable value based on how often the content changes. Then configure ETags to be sent so that when clients DO send a request to the server, it can more easily determine whether or not to send the file back.

One last note about ETag - if you are using a load-balanced server setup with multiple machines running Apache you will probably want to turn off ETag generation. This is because inodes are used as part of the ETag hash algorithm which will be different between the servers. You can configure Apache to not use inodes as part of the calculation but then you'd want to make sure the timestamps on the files are exactly the same, to ensure the same ETag gets generated for all servers.

How can I set a custom baud rate on Linux?

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;

ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);

The view or its master was not found or no view engine supports the searched locations

I had this same issue. I had copied a view "Movie" and renamed it "Customer" accordingly. I also did the same with the models and the controllers.

The resolution was this...I rename the Customer View to Customer1 and just created a new view and called it Customer....I then just copied the Customer1 code into Customer.

This worked.

I would love to know the real cause of the problem.

UPDATE Just for grins....I went back and replicated all the renaming scenario again...and did not get any errors.

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Printing PDFs from Windows Command Line

Looks like you are missing the printer name, driver, and port - in that order. Your final command should resemble:

AcroRd32.exe /t <file.pdf> <printer_name> <printer_driver> <printer_port>

For example:

"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "C:\Folder\File.pdf" "Brother MFC-7820N USB Printer" "Brother MFC-7820N USB Printer" "IP_192.168.10.110"

Note: To find the printer information, right click your printer and choose properties. In my case shown above, the printer name and driver name matched - but your information may differ.

Side-by-side list items as icons within a div (css)

Use the following code to float the items and make sure they are displayed inline.

ul.myclass li{float:left;display:inline}

Also make sure that the container you put them in is floated with width 100% or some other technique to ensure the floated items are contained within it and following items below it.

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

Rubymine: How to make Git ignore .idea files created by Rubymine

Close PHP Storm in terminal go to the project folder type

git rm -rf .idea; git commit -m "delete .idea"; git push;

Then go to project folder and delete the folder .idea

sudo rm -r .idea/

Start PhpStorm and you are done

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Am I doing that right, as far as iterating through the Arraylist goes?

No: by calling iterator twice in each iteration, you're getting new iterators all the time.

The easiest way to write this loop is using the for-each construct:

for (String s : arrayList)
    if (s.equals(value))
        // ...

As for

java.lang.ArrayIndexOutOfBoundsException: -1

You just tried to get element number -1 from an array. Counting starts at zero.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

Another simple way to exclude the auto configuration classes,

Add below similar configuration to your application.yml file,

---
spring:
  profiles: test
  autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Radio button checked event handling

Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.


$("input[type=radio]").change(function(){
    alert( $("input[type=radio][name="+ this.name + "]").val() );
});

How to convert dataframe into time series?

See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,

Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.

And further suggests an explicit conversion using order.by = as.POSIXct,

df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))

Where your format is assigned elswhere,

format <- "%m/%d/%Y" #see strptime for details

Split string into tokens and save them in an array

You can use strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

while(array[i]!=NULL)
{
   array[++i] = strtok(NULL,"/");
}

SQL Server Profiler - How to filter trace to only display events from one database?

Create a new template and check DBname. Use that template for your tracefile.

How to output (to a log) a multi-level array in a format that is human-readable?

I just wonder why nobody uses or recommends the way I prefer to debug an array:

error_log(json_encode($array));

Next to my browser I tail my server log in the console eg.

tail -f /var/log/apache2/error.log

Git cli: get user info from username

You can try this to get infos like:

  • username: git config --get user.name
  • user email: git config --get user.email

There's nothing like "first name" and "last name" for the user.

Hope this will help.

Remove Project from Android Studio

I had to remove my project from eclipse entirely. To do so I copied the folder of my project in workspace and pasted it onto my desktop. Then navigated back into eclipse right clicked selected delete and then check the box to delete the project from my workspace.

After this I closed eclipse. Opened Android studio and tried to open my imported project. At this point it told me the project didn't exist and provided me with an option to remove it from the list. After clicking this i closed Android Studio, and when i reopened it the project was gone.

Finally, I reopened eclipse and imported my project from existing sources to get it back inside eclipse.

NOTE

I would advise against using Android Studio on projects that you have that already work fine with eclipse. Android studio is cool when you are creating new projects but from my experience there are a lot of problems with build paths when I import a build.gradle from eclipse to Android Studio. Android Studio is great but remember it is still in the I/O pre-release!!!

--Just my 2 cents!

Fastest way to reset every value of std::vector<int> to 0

try

std::fill

and also

std::size siz = vec.size();
//no memory allocating
vec.resize(0);
vec.resize(siz, 0);

How to use setArguments() and getArguments() methods in Fragments?

in Frag1:

Bundle b = new Bundle();

b.putStringArray("arrayname that use to retrive in frag2",StringArrayObject);

Frag2.setArguments(b);

in Frag2:

Bundle b = getArguments();

String[] stringArray = b.getStringArray("arrayname that passed in frag1");

It's that simple.

Python Image Library fails with message "decoder JPEG not available" - PIL

I was already using Pillow and got the same error. Tried installing libjpeg or libjpeg-dev as suggested by others but was told that a (newer) version was already installed.

In the end all it took was reinstalling Pillow:

sudo pip uninstall Pillow
sudo pip install Pillow

Format date with Moment.js

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.

Set default time in bootstrap-datetimepicker

None of the above worked for me, however I had success setting the default at time of instantiation.

JQuery

<script type="text/javascript">
    $(function () {
        var dateNow = new Date();
        $('#datetimepicker').datetimepicker({
            defaultDate:dateNow
        });
    });
</script>

How to initialize an array in Java?

Rather than learning un-Official websites learn from oracle website

link follows:Click here

*You can find Initialization as well as declaration with full description *

int n; // size of array here 10
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
    a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
}

Input: 10//array size 10 20 30 40 50 60 71 80 90 91

Displaying data:

for (int i = 0; i < a.length; i++) 
{
    System.out.println(a[i] + " ");
}

Output: 10 20 30 40 50 60 71 80 90 91

Create an array with same element repeated multiple times

In the Node.js REPL:

> Array.from({length:5}).map(x => 2)
[ 2, 2, 2, 2, 2 ]

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I solved this converting the JSP from XHTML to HTML, doing this in the begining:

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
...

How to iterate over a JavaScript object?

For object iteration we usually use a for..in loop. This structure will loop through all enumerable properties, including ones who are inherited via prototypal inheritance. For example:

_x000D_
_x000D_
let obj = {_x000D_
  prop1: '1',_x000D_
  prop2: '2'_x000D_
}_x000D_
_x000D_
for(let el in obj) {_x000D_
  console.log(el);_x000D_
  console.log(obj[el]);_x000D_
}
_x000D_
_x000D_
_x000D_

However, for..in will loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys() function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:

_x000D_
_x000D_
let obj = {_x000D_
  prop1: '1',_x000D_
  prop2: '2',_x000D_
  prop3: '3',_x000D_
  prop4: '4',_x000D_
};_x000D_
_x000D_
const keys = Object.keys(obj);_x000D_
console.log(keys);_x000D_
_x000D_
_x000D_
for (let i = 0; i < 2; i++) {_x000D_
  console.log(obj[keys[i]]);_x000D_
}_x000D_
_x000D_
_x000D_
for (let i = 2; i < 4; i++) {_x000D_
  console.log(obj[keys[i]]);_x000D_
}
_x000D_
_x000D_
_x000D_

Upgrading Node.js to latest version

Just bundling node and npm updates to latest version into a single command for my ~/.bash_profile:

update-node(){
  sudo n latest;
  sudo npm install -g npm;
  node --version;
}

This assumes you've already installed "n" from Eldar Djafarov's answer. After saving this to your Bash profile, re-open the terminal and just type update-node and enter your sudo password:

? update-node
Password:
/usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
/usr/local/bin/npx -> /usr/local/lib/node_modules/npm/bin/npx-cli.js
+ [email protected]
updated 1 package in 7.232s
v8.2.1

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

A simple restart fixed it for me. I'm not sure what was the problem since I work with so much software but I have a feeling it was the VPN software or maybe the fact I put my laptop in sleep a lot and some file was corrupted. I really don't know but the restart fixed it.

jQuery get specific option tag text

This is an old Question which has not been updated in some time the correct way to do this now would be to use

$("#action").on('change',function() {
    alert($(this).find("option:selected").text()+' clicked!');
});

I hope this helps :-)

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

Python debugging tips

print statements

  • Some people recommend a debug_print function instead of print for easy disabling
  • The pprint module is invaluable for complex structures

How can I convert the "arguments" object to an array in JavaScript?

Lodash:

var args = _.toArray(arguments);

in action:

(function(){ console.log(_.toArray(arguments).splice(1)); })(1, 2, 3)

produces:

[2,3]

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I ran into a very similar issue.

I needed to use an old 32-bit DLL within a Web Application that was being developed on a 64-bit machine. I registered the 32-bit DLL into the windows\sysWOW64 folder using the version of regsrv32 in that folder.

Calls to the third party DLL worked from unit tests in Visual Studio but failed from the Web Application hosted in IIS on the same machine with the 80040154 error.

Changing the application pool to "Enable 32-Bit Applications" resolved the issue.

What's the difference between JavaScript and Java?

A Re-Introduction to Javascript by the Mozilla team (they make Firefox) should explain it.

Overriding interface property type defined in Typescript d.ts file

If someone else needs a generic utility type to do this, I came up with the following solution:

/**
 * Returns object T, but with T[K] overridden to type U.
 * @example
 * type MyObject = { a: number, b: string }
 * OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
 */
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };

I needed this because in my case, the key to override was a generic itself.

If you don't have Omit ready, see Exclude property from type.

React-Router open Link in new tab

We can use the following options:-

 // first option is:-
    <Link to="myRoute" params={myParams} target="_blank">

 // second option is:-
    var href = this.props.history.createHref('myRoute', myParams);
    <a href={href} target="_blank">

 //third option is:-
    var href = '/myRoute/' + myParams.foo + '/' + myParams.bar;
    <a href={href} target="_blank">

We can use either of three option to open in new tab by react routing.

Find IP address of directly connected device

To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.

I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.

Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.

Global Angular CLI version greater than local version

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest

Your existing configuration can be updated automatically by running the following command:

ng update @angular/cli

or:

npm install

An attempt was made to access a socket in a way forbidden by its access permissions

As per https://stackoverflow.com/a/33859341/446250, having internet connection sharing enabled for my ethernet adapter ended up causing this problem for me. Disabling the sharing fixed the problem

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

Best way to incorporate Volley (or other library) into Android Studio project

LATEST UPDATE:

Use the official version from jCenter instead.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

The dependencies below points to deprecated volley that is no longer maintained.

ORIGINAL ANSWER

You can use this in dependency section of your build.gradle file to use volley

  dependencies {
      compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  }

UPDATED:

Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.

https://github.com/mcxiaoke/android-volley

How can I get sin, cos, and tan to use degrees instead of radians?

Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Let's start with the problems these tools want to solve:

My system package manager don't have the Python versions I wanted or I want to install multiple Python versions side by side, Python 3.9.0 and Python 3.9.1, Python 3.5.3, etc

Then use pyenv.

I want to install and run multiple applications with different, conflicting dependencies.

Then use virtualenv or venv. These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.

I'm developing an /application/ and need to manage my dependencies, and manage the dependency resolution of the dependencies of my project.

Then use pipenv or poetry.

I'm developing a /library/ or a /package/ and want to specify the dependencies that my library users need to install

Then use setuptools.

I used virtualenv, but I don't like virtualenv folders being scattered around various project folders. I want a centralised management of the environments and some simple project management

Then use virtualenvwrapper. Variant: pyenv-virtualenvwrapper if you also use pyenv.


Not recommended

  • pyvenv. This is deprecated, use venv or virtualenv instead. Not to be confused with pipenv or pyenv.

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

Rolling or sliding window iterator?

I tested a few solutions and one I came up with and found the one I came up with to be the fastest so I thought I would share it.

import itertools
import sys

def windowed(l, stride):
    return zip(*[itertools.islice(l, i, sys.maxsize) for i in range(stride)])

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .lasttraces
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

Make Sure you have included this part in your layout (top below xmlns:android line)

xmlns:ads="http://schemas.android.com/apk/res/com.google.example" 
...........blah blah..

Also Check whether you have included attrs.xml in the res/values/

Check here for more details. http://code.google.com/mobile/ads/docs/android/banner_xml.html

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

convert datetime to date format dd/mm/yyyy

You can use the ToString() method, if you want a string representation of your date, with the correct formatting.

Like:

DateTime date = new DateTime(2011, 02, 19);
string strDate = date.ToString("dd/MM/yyyy");

Sending HTML mail using a shell script

The question asked specifically on shell script and the question tag mentioning only about sendmail package. So, if someone is looking for this, here is the simple script with sendmail usage that is working for me on CentOS 8:

#!/bin/sh
TOEMAIL="[email protected]"
REPORT_FILE_HTML="$REPORT_FILE.html"
echo "Subject: EMAIL SUBJECT" >> "${REPORT_FILE_HTML}"
echo "MIME-Version: 1.0" >> "${REPORT_FILE_HTML}"
echo "Content-Type: text/html" >> "${REPORT_FILE_HTML}"
echo "<html>" >> "${REPORT_FILE_HTML}"
echo "<head>" >> "${REPORT_FILE_HTML}"
echo "<title>Best practice to include title to view online email</title>" >> "${REPORT_FILE_HTML}"
echo "</head>" >> "${REPORT_FILE_HTML}"
echo "<body>" >> "${REPORT_FILE_HTML}"
echo "<p>Hello there, you can put email html body here</p>" >> "${REPORT_FILE_HTML}"
echo "</body>" >> "${REPORT_FILE_HTML}"
echo "</html>" >> "${REPORT_FILE_HTML}"

sendmail $TOEMAIL < $REPORT_FILE_HTML

Set a Fixed div to 100% width of the parent container

man your container is 40% of the width of the parent element

but when you use position:fixed, the width is based on viewport(document) width...

thinking about, i realized your parent element have 10% padding(left and right), it means your element have 80% of the total page width. so your fixed element must have 40% based on 80% of total width

so you just need to change your #fixed class to

#fixed{ 
    position:fixed;
    width: calc(80% * 0.4);
    height:10px;
    background-color:#333;
}

if you use sass, postcss or another css compiler, you can use variables to avoid breaking the layout when you change the padding value of parent element.

here is the updated fiddle http://jsfiddle.net/C93mk/2343/

i hope it helps, regards