Programs & Examples On #Git cvs

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

Creating a very simple 1 username/password login in php

<?php
session_start();
  mysql_connect('localhost','root','');
    mysql_select_db('database name goes here');
    $error_msg=NULL;
    //log out code
    if(isset($_REQUEST['logout'])){
                unset($_SESSION['user']);
                unset($_SESSION['username']);
                unset($_SESSION['id']);
                unset($_SESSION['role']);
        session_destroy();
    }
    //

    if(!empty($_POST['submit'])){
        if(empty($_POST['username']))
            $error_msg='please enter username';
        if(empty($_POST['password']))
            $error_msg='please enter password';
        if(empty($error_msg)){
            $sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
            $sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
            $records=mysql_query($sql) or die(mysql_error());

            if($record_new=mysql_fetch_array($records)){

                $_SESSION['user']=$record_new;
                $_SESSION['id']=$record_new['id'];
                $_SESSION['username']=$record_new['username'];
                $_SESSION['role']=$record_new['role'];
                header('location:index.php');
                $error_msg='welcome';
                exit();
            }else{
                $error_msg='invalid details';
            }
        }       
    }

?>

// replace the location with whatever page u want the user to visit when he/she log in

Printing one character at a time from a string, using the while loop

   # make a list out of text - ['h','e','l','l','o']
   text = list('hello') 

   while text:
       print text.pop()

:)

In python empty object are evaluated as false. The .pop() removes and returns the last item on a list. And that's why it prints on reverse !

But can be fixed by using:

text.pop( 0 )

500 Internal Server Error for php file not for html

I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf

#LoadModule rewrite_module modules/mod_rewrite.so

to

LoadModule rewrite_module modules/mod_rewrite.so

Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.

Good luck!

How to vertically center content with variable height within a div?

This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.

It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.

_x000D_
_x000D_
.block {_x000D_
  height: 300px;_x000D_
  text-align: center;_x000D_
  background: #c0c0c0;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
  /* For visualization _x000D_
  background: #808080; width: 5px;_x000D_
  */_x000D_
}_x000D_
_x000D_
.centered {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  width: 300px;_x000D_
  padding: 10px 15px;_x000D_
  border: #a0a0a0 solid 1px;_x000D_
  background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
    <div class="centered">_x000D_
        <h1>Some text</h1>_x000D_
        <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
           shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
           towards that ship a while ago?"</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery: How to capture the TAB keypress within a Textbox

This worked for me:

$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });

Use Font Awesome icon as CSS content

Update for FontAwesome 5 Thanks to Aurelien

You need to change the font-family to Font Awesome 5 Brands OR Font Awesome 5 Free, based on the type of icon you are trying to render. Also, do not forget to declare font-weight: 900;

a:before {
   font-family: "Font Awesome 5 Free";
   content: "\f095";
   display: inline-block;
   padding-right: 3px;
   vertical-align: middle;
   font-weight: 900;
}

Demo

You can read the rest of the answer below to understand how it works and to know some workarounds for spacing between icon and the text.


FontAwesome 4 and below

That's the wrong way to use it. Open the font awesome style sheet, go to the class of the font you want to use say fa-phone, copy the content property under that class with the entity, and use it like:

a:before {
    font-family: FontAwesome;
    content: "\f095";
}

Demo

Just make sure that if you are looking to target a specific a tag, then consider using a class instead to make it more specific like:

a.class_name:before {
    font-family: FontAwesome;
    content: "\f095";
}

Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of them, make it display: inline-block; and use some padding-right:

a:before {
    font-family: FontAwesome;
    content: "\f095";
    display: inline-block;
    padding-right: 3px;
    vertical-align: middle;
}

Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover action:

a:hover:before {
    content: "\f099"; /* Code of the icon you want to change on hover */
}

Demo

Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width on the base declaration like

a:before {
    /* Other properties here, look in the above code snippets */
    width: 12px; /* add some desired width here to prevent nudge */
}

Demo

How to ignore deprecation warnings in Python

If you are using logging (https://docs.python.org/3/library/logging.html) to format or redirect your ERROR, NOTICE, and DEBUG messages, you can redirect the WARNINGS from the warning system to the logging system:

logging.captureWarnings(True)

See https://docs.python.org/3/library/warnings.html and https://docs.python.org/3/library/logging.html#logging.captureWarnings

In my case, I was formatting all the exceptions with the logging system, but warnings (e.g. scikit-learn) were not affected.

Can I position an element fixed relative to parent?

Let me provide answers to both possible questions. Note that your existing title (and original post) ask a question different than what you seek in your edit and subsequent comment.


To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element.

For example:

#parentDiv { position:relative; }
#childDiv { position:absolute; left:50px; top:20px; }

This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.


To position an element "fixed" relative to the window, you want position:fixed, and can use top:, left:, right:, and bottom: to position as you see fit.

For example:

#yourDiv { position:fixed; bottom:40px; right:40px; }

This will position yourDiv fixed relative to the web browser window, 40 pixels from the bottom edge and 40 pixels from the right edge.

How to detect query which holds the lock in Postgres?

One thing I find that is often missing from these is an ability to look up row locks. At least on the larger databases I have worked on, row locks are not shown in pg_locks (if they were, pg_locks would be much, much larger and there isn't a real data type to show the locked row in that view properly).

I don't know that there is a simple solution to this but usually what I do is look at the table where the lock is waiting and search for rows where the xmax is less than the transaction id present there. That usually gives me a place to start, but it is a bit hands-on and not automation friendly.

Note that shows you uncommitted writes on rows on those tables. Once committed, the rows are not visible in the current snapshot. But for large tables, that is a pain.

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

Can I use multiple versions of jQuery on the same page?

Absolutely, yes you can. This link contains details about how you can achieve that: https://api.jquery.com/jquery.noconflict/.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

How to select a CRAN mirror in R

Here is what I do, which is basically straight from the example(Startup) page:

## Default repo
local({r <- getOption("repos")
       r["CRAN"] <- "http://cran.r-project.org" 
       options(repos=r)
})

which is in ~/.Rprofile.

Edit: As it is now 2018, we can add that for the last few years the URL "https://cloud.r-project.org" has been preferable as it reflects a) https access and b) an "always-near-you" CDN.

Creating a static class with no instances

You could use a classmethod or staticmethod

class Paul(object):
    elems = []

    @classmethod
    def addelem(cls, e):
        cls.elems.append(e)

    @staticmethod
    def addelem2(e):
        Paul.elems.append(e)

Paul.addelem(1)
Paul.addelem2(2)

print(Paul.elems)

classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

module is certainly best though.

Pandas every nth row

Though @chrisb's accepted answer does answer the question, I would like to add to it the following.

A simple method I use to get the nth data or drop the nth row is the following:

df1 = df[df.index % 3 != 0]  # Excludes every 3rd row starting from 0
df2 = df[df.index % 3 == 0]  # Selects every 3rd raw starting from 0

This arithmetic based sampling has the ability to enable even more complex row-selections.

This assumes, of course, that you have an index column of ordered, consecutive, integers starting at 0.

How do I enable TODO/FIXME/XXX task tags in Eclipse?

In the distribution I use, the tasks are listed in the task list by default (at least for Java). For other content types, you may check the following settings.

Display the Tasks View: Window > Show View > Other > General > Tasks

For non-Java Task Tags: check the following settings: Window > Preferences > General > Editors > Structured Text Editors > Task Tags You can enable searching for task tags in the [Task Tags] tab and select the content types in the [Filters] tab.

For Java task tags, you should look in: Window > Preferences > Java > Compiler > Task Tags

J.

How to determine if a number is positive or negative?

// Returns 0 if positive, nonzero if negative
public long sign(long value) {
    return value & 0x8000000000000000L;
}

Call like:

long val1 = ...;
double val2 = ...;
float val3 = ...;
int val4 = ...;

sign((long) valN);

Casting from double / float / integer to long should preserve the sign, if not the actual value...

jQuery get specific option tag text

While "looping" through dynamically created select elements with a .each(function()...): $("option:selected").text(); and $(this + " option:selected").text() did not return the selected option text - instead it was null.

But Peter Mortensen's solution worked:

$(this).find("option:selected").text();

I do not know why the usual way does not succeed in a .each() (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it "for newbies coming through Google."

I would have started with $('#list option:selected").each() except I needed to grab stuff from the select element as well.

Make footer stick to bottom of page using Twitter Bootstrap

just add the class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

Update for Bootstrap 4 -

as mentioned by Sara Tibbetts - class is fixed-bottom

<div class="footer fixed-bottom">

Debug JavaScript in Eclipse

In 2015, there are at least six choices for JavaScript debugging in Eclipse:

Adding to the above, here are a couple of videos which focus on "debugging JavaScript using eclipse"

Outdated

Re-render React component when prop changes

I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.

This section of your code:

componentDidMount() {
      if (this.props.isManager) {
        this.props.dispatch(actions.fetchAllSites())
      } else {
        const currentUserId = this.props.user.get('id')
        this.props.dispatch(actions.fetchUsersSites(currentUserId))
      }  
    }

Should not be triggering in a component, it should be handled after executing your first request.

Have a look at this example from redux-thunk:

function makeASandwichWithSecretSauce(forPerson) {

  // Invert control!
  // Return a function that accepts `dispatch` so we can dispatch later.
  // Thunk middleware knows how to turn thunk async actions into actions.

  return function (dispatch) {
    return fetchSecretSauce().then(
      sauce => dispatch(makeASandwich(forPerson, sauce)),
      error => dispatch(apologize('The Sandwich Shop', forPerson, error))
    );
  };
}

You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.

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

Using this solution, you will also be able to put the cursor at the end of newly text.

final TextEditingController _controller = TextEditingController();

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(child: TextField(controller: _controller)),
    floatingActionButton: FloatingActionButton(
      onPressed: () {
        _controller.text = "Hello";

        // this changes cursor position
        _controller.selection = TextSelection.fromPosition(TextPosition(offset: _controller.text.length));
        setState(() {});
      },
    ),
  );
}

Create a zip file and download it

I just ran into this problem. For me the issue was with:

readfile("$archive_file_name");

It was resulting in a out of memory error.

Allowed memory size of 134217728 bytes exhausted (tried to allocate 292982784 bytes)

I was able to correct the problem by replacing readfile() with the following:

    $handle = fopen($zipPath, "rb");
    while (!feof($handle)){
        echo fread($handle, 8192);
    }
    fclose($handle);

Not sure if this is your same issue or not seeing that your file is only 1.2 MB. Maybe this will help someone else with a similar problem.

How to create an Oracle sequence starting with max value from a table?

Here I have my example which works just fine:

declare
 ex number;
begin
  select MAX(MAX_FK_ID)  + 1 into ex from TABLE;
  If ex > 0 then
    begin
            execute immediate 'DROP SEQUENCE SQ_NAME';
      exception when others then
        null;
    end;
    execute immediate 'CREATE SEQUENCE SQ_NAME INCREMENT BY 1 START WITH ' || ex || ' NOCYCLE CACHE 20 NOORDER';
  end if;
end;

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I was using a .Net Core 2.1 API with the [FromBody] attribute and I had to use the following solution to successfully Post to it:

_apiClient =  new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
    FirstName = "Me",
    LastName = "Myself"
};

var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));

How to set underline text on textview?

Following are the some approaches for underlined text in android:

1st Approach

You can define your string in strings.xml

<string name="your_string"><u>Underlined text</u></string>

And use that string in your xml file

<TextView
            android:id="@+id/txt_underlined"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/your_string"/>

Or you can use that string in your Activity/Fragment

txtView.setText(R.string.your_string);

2nd Approach

To underline the text in TextView, you can use SpannableString

String text="Underlined Text";
SpannableString content = new SpannableString(text);
content.setSpan(new UnderlineSpan(), 0, text.length(), 0);
txtView.setText(content);

3rd Approach

You can make use of setPaintFlags method of TextView to underline the text of TextView.

txtView.setPaintFlags(mTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtView.setText("Underlined Text");

4th Approach

Make use of Html.fromHtml(htmlString);

String htmlString="<u>Underlined Text</u>";
txtView.setText(Html.fromHtml(htmlString));

Or

txtView.setText(Html.fromHtml("<u>underlined</u> text"));

Note:

If you have added this line android:textAllCaps="true" in your layout, then none of the above will work. For that, you have to define your string in Caps and then any of the above approach.

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

For Unix

grep "ARCHITECTURE" $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml

And the output is:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/> 

For Windows

findstr "ARCHITECTURE" %ORACLE_HOME%\inventory\ContentsXML\oraclehomeproperties.xml

And the output can be:

<PROPERTY NAME="ARCHITECTURE" VAL="64"/>

How to count duplicate rows in pandas dataframe?

ran into this problem today and wanted to include NaNs so I replace them temporarily with "" (empty string). Please comment if you do not understand something :). This solution assumes that "" is not a relevant value for you. It should also work with numerical data (I have tested it sucessfully but not extensively) since pandas will infer the data type again after replacing "" with np.nan.

import pandas as pd

# create test data
df = pd.DataFrame({'test':['foo','bar',None,None,'foo'],
                  'test2':['bar',None,None,None,'bar'],
                  'test3':[None, 'foo','bar',None,None]})

# fill null values with '' to not lose them during groupby
# groupby all columns and calculate the length of the resulting groups
# rename the series obtained with groupby to "group_count"
# reset the index to get a DataFrame
# replace '' with np.nan (this reverts our first operation)
# sort DataFrame by "group_count" descending
df = (df.fillna('')\
      .groupby(df.columns.tolist()).apply(len)\
      .rename('group_count')\
      .reset_index()\
      .replace('',np.nan)\
      .sort_values(by = ['group_count'], ascending = False))
df
  test test2 test3  group_count
3  foo   bar   NaN            2
0  NaN   NaN   NaN            1
1  NaN   NaN   bar            1
2  bar   NaN   foo            1

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

A good Sorted List for Java

Phuong:

Sorting 40,000 random numbers:

0.022 seconds

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class test
{
    public static void main(String[] args)
    {
        List<Integer> nums = new ArrayList<Integer>();
        Random rand = new Random();
        for( int i = 0; i < 40000; i++ )
        {
            nums.add( rand.nextInt(Integer.MAX_VALUE) );
        }

        long start = System.nanoTime();
        Collections.sort(nums);
        long end = System.nanoTime();

        System.out.println((end-start)/1e9);
    }
}   

Since you rarely need sorting, as per your problem statement, this is probably more efficient than it needs to be.

How to find the sum of an array of numbers

Those are really great answers, but just in case if the numbers are in sequence like in the question ( 1,2,3,4) you can easily do that by applying the formula (n*(n+1))/2 where n is the last number

How can I find the maximum value and its index in array in MATLAB?

The function is max. To obtain the first maximum value you should do

[val, idx] = max(a);

val is the maximum value and idx is its index.

Multiple Java versions running concurrently under Windows

I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.

Article by: Ted Neward: Multiple Java Homes: Giving Java Apps Their Own JRE

With the exponential growth of Java as a server-side development language has come an equivablent exponential growth in Java development tools, environments, frameworks, and extensions. Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above, some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0 days, others require the "javax.swing" package names.

Worse yet, this problem can be found even within the corporate enterprise, as systems developed using Java from just six months ago may suddenly "not work" due to the installation of some Java Extension required by a new (seemingly unrelated) application release. This can complicate deployment of Java applications across the corporation, and lead customers to wonder precisely why, five years after the start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes, we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the infamous "DLL-Hell" problem just described.)

This paper describes how to configure a Java installation such that a given application receives its own, private, JRE, allowing multiple Java environments to coexist without driving customers (or system administrators) insane...

Search and replace a particular string in a file using Perl

A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile

How to save final model using keras?

you can save the model in json and weights in a hdf5 file format.

# keras library import  for Saving and loading model and weights

from keras.models import model_from_json
from keras.models import load_model

# serialize model to JSON
#  the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()


with open("model_num.json", "w") as json_file:
    json_file.write(model_json)

# serialize weights to HDF5
model.save_weights("model_num.h5")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

# load json and create model
json_file = open('model_num.json', 'r')

loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")

loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')

To predict for different data you can use this

loaded_model.predict_classes("your_test_data here")

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

I had similar issue but got solved when I corrected my zookeeper.yaml file which had the service name mismatch with file deployment's container names. It got resolved by making them same.

apiVersion: v1
kind: Service
metadata:
  name: zk1
  namespace: nbd-mlbpoc-lab
  labels:
    app: zk-1
spec:
  ports:
  - name: client
    port: 2181
    protocol: TCP
  - name: follower
    port: 2888
    protocol: TCP
  - name: leader
    port: 3888
    protocol: TCP
  selector:
    app: zk-1
---
kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: zk-deployment
  namespace: nbd-mlbpoc-lab
spec:
  template:
    metadata:
      labels:
        app: zk-1
    spec:
      containers:
      - name: zk1
        image: digitalwonderland/zookeeper
        ports:
        - containerPort: 2181
        env:
        - name: ZOOKEEPER_ID
          value: "1"
        - name: ZOOKEEPER_SERVER_1
          value: zk1

What are Bearer Tokens and token_type in OAuth 2?

From RFC 6750, Section 1.2:

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

See also: Mozilla MDN Header Information.

input checkbox true or checked or yes

Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

disabled, readonly and ismap input's attributes go on the same way.

EDITED

empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

How to generate .json file with PHP?

You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

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

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

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

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

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

(Press STOP/RUN to run it again)

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

Are there any naming convention guidelines for REST APIs?

If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:

  • client_id
  • client_secret

I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.

See: https://tools.ietf.org/html/rfc6749

Using OpenSSL what does "unable to write 'random state'" mean?

I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in "Run As Administrator" mode for it to work. Otherwise you get the same: unable to write 'random state' error.

Unable to set default python version to python3 in ubuntu

get python path from

ls /usr/bin/python*

then set your python version

alias python="/usr/bin/python3"

How to put space character into a string name in XML?

Android doesn't support keeping the spaces at the end of the string in String.xml file so if you want space after string you need to use this unicode in between the words.

\u0020

It is a unicode space character.

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

Light red fill with dark red text.

{'bg_color':   '#FFC7CE', 'font_color': '#9C0006'})

Light yellow fill with dark yellow text.

{'bg_color':   '#FFEB9C', 'font_color': '#9C6500'})

Green fill with dark green text.

{'bg_color':   '#C6EFCE', 'font_color': '#006100'})

Pure CSS to make font-size responsive based on dynamic amount of characters

I used smth like this:

1.style.fontSize = 15.6/(document.getElementById("2").innerHTML.length)+ 'vw'

Where: 1 - parent div Id and 2 - Id of div with my text

Manually Set Value for FormBuilder Control

Aangular 2 final has updated APIs. They have added many methods for this.

To update the form control from controller do this:

this.form.controls['dept'].setValue(selected.id);

this.form.controls['dept'].patchValue(selected.id);

No need to reset the errors

References

https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

https://toddmotto.com/angular-2-form-controls-patch-value-set-value

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

Java code To convert byte to Hexadecimal

I am posting because none of the existing answers explain why their approaches work, which I think is really important for this problem. In some cases, this causes the proposed solution to appear unnecessarily complicated and subtle. To illustrate I will provide a fairly straightforward approach, but I'll provide a bit more detail to help illustrate why it works.

First off, what are we trying to do? We want to convert a byte value (or an array of bytes) to a string which represents a hexadecimal value in ASCII. So step one is to find out exactly what a byte in Java is:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

What does this mean? A few things: First and most importantly, it means we are working with 8-bits. So for example we can write the number 2 as 0000 0010. However, since it is two's complement, we write a negative 2 like this: 1111 1110. What is also means is that converting to hex is very straightforward. That is, you simply convert each 4 bit segment directly to hex. Note that to make sense of negative numbers in this scheme you will first need to understand two's complement. If you don't already understand two's complement, you can read an excellent explanation, here: http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html


Converting Two's Complement to Hex In General

Once a number is in two's complement it is dead simple to convert it to hex. In general, converting from binary to hex is very straightforward, and as you will see in the next two examples, you can go directly from two's complement to hex.

Examples

Example 1: Convert 2 to Hex.

1) First convert 2 to binary in two's complement:

2 (base 10) = 0000 0010 (base 2)

2) Now convert binary to hex:

0000 = 0x0 in hex
0010 = 0x2 in hex

therefore 2 = 0000 0010 = 0x02. 

Example 2: Convert -2 (in two's complement) to Hex.

1) First convert -2 to binary in two's complement:

-2 (base 10) = 0000 0010 (direct conversion to binary) 
               1111 1101 (invert bits)
               1111 1110 (add 1)
therefore: -2 = 1111 1110 (in two's complement)

2) Now Convert to Hex:

1111 = 0xF in hex
1110 = 0xE in hex

therefore: -2 = 1111 1110 = 0xFE.


Doing this In Java

Now that we've covered the concept, you'll find we can achieve what we want with some simple masking and shifting. The key thing to understand is that the byte you are trying to convert is already in two's complement. You don't do this conversion yourself. I think this is a major point of confusion on this issue. Take for example the follow byte array:

byte[] bytes = new byte[]{-2,2};

We just manually converted them to hex, above, but how can we do it in Java? Here's how:

Step 1: Create a StringBuffer to hold our computation.

StringBuffer buffer = new StringBuffer();

Step 2: Isolate the higher order bits, convert them to hex, and append them to the buffer

Given the binary number 1111 1110, we can isolate the higher order bits by first shifting them over by 4, and then zeroing out the rest of the number. Logically this is simple, however, the implementation details in Java (and many languages) introduce a wrinkle because of sign extension. Essentially, when you shift a byte value, Java first converts your value to an integer, and then performs sign extension. So while you would expect 1111 1110 >> 4 to be 0000 1111, in reality, in Java it is represented as the two's complement 0xFFFFFFFF!

So returning to our example:

1111 1110 >> 4 (shift right 4) = 1111 1111 1111 1111 1111 1111 1111 1111 (32 bit sign-extended number in two's complement)

We can then isolate the bits with a mask:

1111 1111 1111 1111 1111 1111 1111 1111 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1111
therefore: 1111 = 0xF in hex. 

In Java we can do this all in one shot:

Character.forDigit((bytes[0] >> 4) & 0xF, 16);

The forDigit function just maps the number you pass it onto the set of hexadecimal numbers 0-F.

Step 3: Next we need to isolate the lower order bits. Since the bits we want are already in the correct position, we can just mask them out:

1111 1110 & 0xF = 0000 0000 0000 0000 0000 0000 0000 1110 (recall sign extension from before)
therefore: 1110 = 0xE in hex.  

Like before, in Java we can do this all in one shot:

Character.forDigit((bytes[0] & 0xF), 16);

Putting this all together we can do it as a for loop and convert the entire array:

for(int i=0; i < bytes.length; i++){
    buffer.append(Character.forDigit((bytes[i] >> 4) & 0xF, 16));
    buffer.append(Character.forDigit((bytes[i] & 0xF), 16));
}

Hopefully this explanation makes things clearer for those of you wondering exactly what is going on in the many examples you will find on the internet. Hopefully I didn't make any egregious errors, but suggestions and corrections are highly welcome!

How do I setup a SSL certificate for an express.js server?

This is my working code for express 4.0.

express 4.0 is very different from 3.0 and others.

4.0 you have /bin/www file, which you are going to add https here.

"npm start" is standard way you start express 4.0 server.

readFileSync() function should use __dirname get current directory

while require() use ./ refer to current directory.

First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.

no such directory found error:

  key: fs.readFileSync('../private.key'),

  cert: fs.readFileSync('../public.cert')

error, no such directory found

  key: fs.readFileSync('./private.key'),

  cert: fs.readFileSync('./public.cert')

Working code should be

key: fs.readFileSync(__dirname + '/private.key', 'utf8'),

cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')

Complete https code is:

const https = require('https');
const fs = require('fs');

// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.

const options = {
   key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
  cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};


 // Create HTTPs server.

 var server = https.createServer(options, app);

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

How to linebreak an svg text within javascript?

I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:

 g.append('svg:text')
  .attr('x', 0)
  .attr('y', 30)
  .attr('class', 'id')
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 5)
  .text(function(d) { return d.name; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.sname; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.idcode; })

There are 3 lines separated with linebreak.

Is Java a Compiled or an Interpreted programming language ?

Java is compiled to bytecode, which then goes into the Java VM, which interprets it.

Why am I getting an OPTIONS request instead of a GET request?

According to MDN,

Preflighted requests

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

  • It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
  • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

sql select with column name like

This will show you the table name and column name

select table_name,column_name from information_schema.columns
where column_name like '%breakfast%'

Print text instead of value from C enum

enums in C don't really work the way you're expecting them to. You can think of them kind of like glorified constants (with a few additional benefits relating to being a collection of such constants), and the text you've written in for "Sunday" really gets resolved to a number during compilation, the text is ultimately discarded.

In short: to do what you really want you'll need to keep an array of the strings or create a function to map from the enum's value to the text you'd like to print.

Get IP address of visitors using Flask for Python

This should do the job. It provides the client IP address (remote host).

Note that this code is running on the server side.

from mod_python import apache

req.get_remote_host(apache.REMOTE_NOLOOKUP)

How to call external url in jquery?

All of these answers are wrong!

Like I said in my comment, the reason you're getting that error because the URL fails the "Same origin policy", but you can still us the AJAX function to hit another domain, see Nick Cravers answer on this similar question:

You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?",
function(data) {
    doSomethingWith(data); 
}); 

You can test it here.

Without using JSONP you're hitting the same-origin policy which is blocking the XmlHttpRequest from getting any data back.

With this in mind, the follow code should work:

var fbURL="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";

$.ajax({
    url: fbURL+"&callback=?",
    data: "message="+commentdata,
    type: 'POST',
    success: function (resp) {
        alert(resp);
    },
    error: function(e) {
        alert('Error: '+e);
    }  
});

Getting hold of the outer class object from the inner class object

Within the inner class itself, you can use OuterClass.this. This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this.

I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:

public OuterClass getOuter() {
    return OuterClass.this;
}

EDIT: By experimentation, it looks like the field holding the reference to the outer class has package level access - at least with the JDK I'm using.

EDIT: The name used (this$0) is actually valid in Java, although the JLS discourages its use:

The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

jquery get all input from specific form

To iterate through all the inputs in a form you can do this:

$("form#formID :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
});

This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :

$("form#formID input[type=text]")//...

etc.

How to read if a checkbox is checked in PHP?

I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

HTML Code: (for Add Page)

<input name="status" type="checkbox" value="1" checked>

Hint: remove "checkbox" if you want to show it as unchecked by default

HTML Code: (for Edit Page)

<input name="status" type="checkbox" value="1" 
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>

PHP Code: (use for Add/Edit pages)

$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}

Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

How to define a circle shape in an Android XML drawable file?

Just use

ShapeDrawable circle = new ShapeDrawable( new  OvalShape() );

Android getText from EditText field

EditText txt = (EditText)findviewbyid(R.id.txt);

Editable str = txt.getText().toString();

Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);  

toast.show();

Error "can't use subversion command line client : svn" when opening android project checked out from svn

I have fixed the issue after upgrading existing svn client on mac OS X with following link:(1.7.x to 1.9.x)

https://ahmadawais.com/installing-svn-subversion-on-yosemite-after-removing-the-old-version/

  1. Open Android Studio
  2. Go to Settings -> Version Control -> Subversion -> General -> User command line client ( Marked checkbox)

replace ‘svn’ with your svn installed path like ‘/usr/local/bin/svn’

How to check permissions of a specific directory?

In GNU/Linux, try to use ls, namei, getfacl, stat.

For Dir

[flying@lempstacker ~]$ ls -ldh /tmp
drwxrwxrwt. 23 root root 4.0K Nov  8 15:41 /tmp
[flying@lempstacker ~]$ namei -l /tmp
f: /tmp
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
[flying@lempstacker ~]$ getfacl /tmp
getfacl: Removing leading '/' from absolute path names
# file: tmp
# owner: root
# group: root
# flags: --t
user::rwx
group::rwx
other::rwx

[flying@lempstacker ~]$ 

or

[flying@lempstacker ~]$ stat -c "%a" /tmp
1777
[flying@lempstacker ~]$ stat -c "%n %a" /tmp
/tmp 1777
[flying@lempstacker ~]$ stat -c "%A" /tmp
drwxrwxrwt
[flying@lempstacker ~]$ stat -c "%n %A" /tmp
/tmp drwxrwxrwt
[flying@lempstacker ~]$

For file

[flying@lempstacker ~]$ ls -lh /tmp/anaconda.log
-rw-r--r-- 1 root root 0 Nov  8 08:31 /tmp/anaconda.log
[flying@lempstacker ~]$ namei -l /tmp/anaconda.log
f: /tmp/anaconda.log
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
-rw-r--r-- root root anaconda.log
[flying@lempstacker ~]$ getfacl /tmp/anaconda.log
getfacl: Removing leading '/' from absolute path names
# file: tmp/anaconda.log
# owner: root
# group: root
user::rw-
group::r--
other::r--

[flying@lempstacker ~]$

or

[flying@lempstacker ~]$ stat -c "%a" /tmp/anaconda.log
644
[flying@lempstacker ~]$ stat -c "%n %a" /tmp/anaconda.log
/tmp/anaconda.log 644
[flying@lempstacker ~]$ stat -c "%A" /tmp/anaconda.log
-rw-r--r--
[flying@lempstacker ~]$ stat -c "%n %A" /tmp/anaconda.log
/tmp/anaconda.log -rw-r--r--
[flying@lempstacker ~]$

How can I switch to another branch in git?

Check remote branch list:

git branch -a

Switch to another Branch:

git checkout -b <local branch name> <Remote branch name>
Example: git checkout -b Dev_8.4 remotes/gerrit/Dev_8.4

Check local Branch list:

git branch

Update everything:

git pull

gradlew command not found?

First thing is you need to run the gradle task that you mentioned for this wrapper. Ex : gradle wrapper After running this command, check your directory for gradlew and gradlew.bat files. gradlew is the shell script file & can be used in linux/Mac OS. gradlew.bat is the batch file for windows OS. Then run,

./gradlew build (linux/mac). It will work.

Adding a regression line on a ggplot

As I just figured, in case you have a model fitted on multiple linear regression, the above mentioned solution won't work.

You have to create your line manually as a dataframe that contains predicted values for your original dataframe (in your case data).

It would look like this:

# read dataset
df = mtcars

# create multiple linear model
lm_fit <- lm(mpg ~ cyl + hp, data=df)
summary(lm_fit)

# save predictions of the model in the new data frame 
# together with variable you want to plot against
predicted_df <- data.frame(mpg_pred = predict(lm_fit, df), hp=df$hp)

# this is the predicted line of multiple linear regression
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_line(color='red',data = predicted_df, aes(x=mpg_pred, y=hp))

Multiple LR

# this is predicted line comparing only chosen variables
ggplot(data = df, aes(x = mpg, y = hp)) + 
  geom_point(color='blue') +
  geom_smooth(method = "lm", se = FALSE)

Single LR

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

How to check if a double value has no decimal part

Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.

For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.

None of the answers that I can read now works in this way, so here is my solution:

public boolean isInteger(double n, double tolerance) {
    double absN = Math.abs(n);
    return Math.abs(absN - Math.round(absN)) <= tolerance;
}

And the unit test, to make sure it works:

@Test
public void checkIsInteger() {
    final double TOLERANCE = 1E-2;
    assertThat(solver.isInteger(1, TOLERANCE), is(true));

    assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
    assertThat(solver.isInteger(0.9, TOLERANCE), is(false));

    assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
    assertThat(solver.isInteger(1.1, TOLERANCE), is(false));

    assertThat(solver.isInteger(-1, TOLERANCE), is(true));

    assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
    assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));

    assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));        
    assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}

Error checking for NULL in VBScript

I will just add a blank ("") to the end of the variable and do the comparison. Something like below should work even when that variable is null. You can also trim the variable just in case of spaces.

If provider & "" <> "" Then 
    url = url & "&provider=" & provider 
End if

List of Java processes

pgrep -l java
ps -ef | grep java

Using "If cell contains" in VBA excel

Dim celltxt As String
Range("C6").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltext, "TOTAL") > 0 Then
Range("C7").Select 
Selection.End(xlToRight).Select
Selection.Value = "-"
End If

You declared "celltxt" and used "celltext" in the instr.

How to have jQuery restrict file types on upload?

This example allows to upload PNG image only.

HTML

<input type="file" class="form-control" id="FileUpload1" accept="image/png" />

JS

$('#FileUpload1').change(
                function () {
                    var fileExtension = ['png'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.png' format is allowed.");
                        this.value = ''; // Clean field
                        return false;
                    }
                });

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Android Studio (Preview) sometimes recommends updating to a Gradle Plugin that is not available yet (did Google forget to publish it?). Such as today with

'com.android.tools.build:gradle:3.1.0-beta1'

I found I can see current versions of com.android.tools.build:gradle here, and then I just pick the newest:

https://dl.google.com/dl/android/maven2/index.html

I just found this beta1 gradle bug in the Android Bug Tracker. I also just learned Android Studio > Help Menu > Submit Feedback brought me to the bug tracker.

Found temporary solution at androiddev reddit for the 3.1.0-beta1 problem: Either roll back to Preview Canary 8, or switch to gradle plugin 3.0.1 until Canary 10 is released shortly.

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

How to get css background color on <tr> tag to span entire row

Try this:

    .rowhighlight > td { background: green;}

Linux command to check if a shell script is running or not

I was quite inspired by the last answer by mklement0 - I have few scripts/small programs I run at every reboot via /etc/crontab. I built on his answer and built a login script, which shows if my programs are still running. I execute this scripts.sh via .profile -file on every login, to get instant notification on each login.

cat scripts.sh 
#!/bin/bash

getscript() {
  pgrep -lf ".[ /]$1( |\$)"
}

script1=keepalive.sh
script2=logger_v3.py

# test if script 1 is running
if getscript "$script1" >/dev/null; then
  echo "$script1" is RUNNING
  else
    echo "$script1" is NOT running
fi

# test if script 2 is running:
if getscript "$script2" >/dev/null; then
  echo "$script2" is RUNNING
  else
    echo "$script2" is NOT running
fi

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

Accessing a Dictionary.Keys Key through a numeric index

Why don't you just extend the dictionary class to add in a last key inserted property. Something like the following maybe?

public class ExtendedDictionary : Dictionary<string, int>
{
    private int lastKeyInserted = -1;

    public int LastKeyInserted
    {
        get { return lastKeyInserted; }
        set { lastKeyInserted = value; }
    }

    public void AddNew(string s, int i)
    {
        lastKeyInserted = i;

        base.Add(s, i);
    }
}

How can you use optional parameters in C#?

I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.

Stock ticker symbol lookup API

Use YQL: a sql-like language to retrieve stuff from public api's: YQL Console (external link)

It gives you a nice XML file to work with!

How to set value to variable using 'execute' in t-sql?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
    @columnName varchar(255),
    @id int
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @columnVal TABLE (columnVal nvarchar(255));

    DECLARE @sql nvarchar(max);
    SET @sql = 'SELECT ' + @columnName + ' FROM regUsers WHERE id=' + CAST(@id AS varchar(10));
    INSERT @columnVal EXEC sp_executesql @sql;

    SELECT * FROM @columnVal;
END
GO

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

How to get thread id of a pthread in linux c program?

This single line gives you pid , each threadid and spid.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

How to calculate a mod b in Python?

you can also try divmod(x, y) which returns a tuple (x // y, x % y)

Update and left outer join statements

If what you need is UPDATE from SELECT statement you can do something like this:

UPDATE suppliers    
SET city = (SELECT customers.city FROM customers

WHERE customers.customer_name = suppliers.supplier_name)

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

How to read numbers from file in Python?

To make the answer simple here is a program that reads integers from the file and sorting them

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

After reading each line of the file converting each string to a digit

nums.sort()

Sorting the numbers

f.close()

f = open("input.txt", 'w')
for num in nums:
    f.write("%d\n" %num)

f.close()

Writing them back As easy as that, Hope this helps

Simulate low network connectivity for Android

Do you want to test for no network connection, or just a slow network connection? If the former, you can go to Settings > Wireless & networks > Airplane mode and turn Airplane mode on. That will let you test network unavailability on an actual device.

Why does CSS not support negative padding?

Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.

Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.

The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
  margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
  margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
  padding: 10px;_x000D_
  background: lightgray;_x000D_
}_x000D_
ul {_x000D_
  list-style: none;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  padding: 0;/* just to reset */_x000D_
  padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
  flex: 1 1 auto;_x000D_
  margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
  <li>a lacinia purus porttitor eget</li>_x000D_
  <li>donec ut nunc lorem</li>_x000D_
  <li>duis in est dictum</li>_x000D_
  <li>tempor metus non</li>_x000D_
  <li>dapibus sapien</li>_x000D_
  <li>phasellus bibendum tincidunt</li>_x000D_
  <li>quam vitae accumsan</li>_x000D_
  <li>ut interdum eget nisl in eleifend</li>_x000D_
  <li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
_x000D_
_x000D_

I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc(), or CSS preprocessors which only work when the units are the same, etc.

Best approach to real time http streaming to HTML5 video client

I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).

Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)

Check out https://github.com/131/h264-live-player on github.

Git and nasty "error: cannot lock existing info/refs fatal"

Update:

You might need to edit your ~/.netrc file:

https://bugs.launchpad.net/ubuntu/+source/git-core/+bug/293553

Original answer:

Why did you disable ssl? I think this might have to do with you not being able to push via https. I'd set it back and try to push again:

git config –global http.sslVerify true

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

Default values in a C Struct

You could address the problem with an X-Macro

You would change your struct definition into:

#define LIST_OF_foo_MEMBERS \
    X(int,id) \
    X(int,route) \
    X(int,backup_route) \
    X(int,current_route)


#define X(type,name) type name;
struct foo {
    LIST_OF_foo_MEMBERS 
};
#undef X

And then you would be able to easily define a flexible function that sets all fields to dont_care.

#define X(type,name) in->name = dont_care;    
void setFooToDontCare(struct foo* in) {
    LIST_OF_foo_MEMBERS 
}
#undef X

Following the discussion here, one could also define a default value in this way:

#define X(name) dont_care,
const struct foo foo_DONT_CARE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X

Which translates into:

const struct foo foo_DONT_CARE = {dont_care, dont_care, dont_care, dont_care,};

And use it as in hlovdal answer, with the advantage that here maintenance is easier, i.e. changing the number of struct members will automatically update foo_DONT_CARE. Note that the last "spurious" comma is acceptable.

I first learned the concept of X-Macros when I had to address this problem.

It is extremely flexible to new fields being added to the struct. If you have different data types, you could define different dont_care values depending on the data type: from here, you could take inspiration from the function used to print the values in the second example.

If you are ok with an all int struct, then you could omit the data type from LIST_OF_foo_MEMBERS and simply change the X function of the struct definition into #define X(name) int name;

How do I use CMake?

CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.

You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.

How to find the difference in days between two dates?

Another Python version:

python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

Android Studio Stuck at Gradle Download on create new project

Gradle is actually included with Android Studio (at least on the Mac OS X version.) I had to point it to the installed location, inside the Android Studio application "package contents" (can view by control/right-clicking on the application icon.)
Location of gradle inside Android Studio package

Java HashMap: How to get a key and value by index?

If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values() method

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

The values() method is part of the Map interface and returns a Collection view of the values in the map.

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

For React Native applications while running in debug add the xml block mentioned by @Xenolion to react_native_config.xml located in <project>/android/app/src/debug/res/xml

Similar to the following snippet:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">localhost</domain>
        <domain includeSubdomains="false">10.0.2.2</domain>
        <domain includeSubdomains="false">10.0.3.2</domain>
    </domain-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

Generate a random number in a certain range in MATLAB

If you need a floating random number between 13 and 20

(20-13).*rand(1) + 13

If you need an integer random number between 13 and 20

floor((21-13).*rand(1) + 13)

Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21

jQuery AJAX Character Encoding

I have been fiddling around with this problem and found out that this solution works for Firefox and safari (yes, im on a mac at the moment).

when getting the request, i made a content-type=iso-8859-1 here:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml; charset=ISO-8859-1');
        }
    }

Please tell me if someone finds out this doesn't work in ie.

How can I force WebKit to redraw/repaint to propagate style changes?

I use the transform: translateZ(0); method but in some cases it is not sufficient.

I'm not fan of adding and removing a class so i tried to find way to solve this and ended up with a new hack that works well :

@keyframes redraw{
    0% {opacity: 1;}
    100% {opacity: .99;}
}

// ios redraw fix
animation: redraw 1s linear infinite;

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

What is InputStream & Output Stream? Why and when do we use them?

you read from an InputStream and write to an OutputStream.

for example, say you want to copy a file. You would create a FileInputStream to read from the source file and a FileOutputStream to write to the new file.

If your data is a character stream, you could use a FileReader instead of an InputStream and a FileWriter instead of an OutputStream if you prefer.

InputStream input = ... // many different types
OutputStream output = ... // many different types

byte[] buffer = new byte[1024];
int n = 0;
while ((n = input.read(buffer)) != -1)
    output.write(buffer, 0, n);

input.close();
output.close();

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Redirect all output to file in Bash

That part is written to stderr, use 2> to redirect it. For example:

foo > stdout.txt 2> stderr.txt

or if you want in same file:

foo > allout.txt 2>&1

Note: this works in (ba)sh, check your shell for proper syntax

The 'json' native gem requires installed build tools

Followed the steps.

  1. Extract DevKit to path C:\Ruby193\DevKit
  2. cd C:\Ruby192\DevKit
  3. ruby dk.rb init
  4. ruby dk.rb review
  5. ruby dk.rb install

Then I wrote the command

gem install rails -r -y

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

How to restart kubernetes nodes?

I had an onpremises HA installation, a master and a worker stopped working returning a NOTReady status. Checking the kubelet logs on the nodes I found out this problem:

failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false

Disabling swap on nodes with

swapoff -a

and restarting the kubelet

systemctl restart kubelet

did the work.

Pure CSS collapse/expand div

Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary> and <detail> tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.

I've made an example here:

<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>

Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

How to delete from a text file, all lines that contain a specific string?

I was struggling with this on Mac. Plus, I needed to do it using variable replacement.

So I used:

sed -i '' "/$pattern/d" $file

where $file is the file where deletion is needed and $pattern is the pattern to be matched for deletion.

I picked the '' from this comment.

The thing to note here is use of double quotes in "/$pattern/d". Variable won't work when we use single quotes.

What is the optimal algorithm for the game 2048?

EDIT: This is a naive algorithm, modelling human conscious thought process, and gets very weak results compared to AI that search all possibilities since it only looks one tile ahead. It was submitted early in the response timeline.

I have refined the algorithm and beaten the game! It may fail due to simple bad luck close to the end (you are forced to move down, which you should never do, and a tile appears where your highest should be. Just try to keep the top row filled, so moving left does not break the pattern), but basically you end up having a fixed part and a mobile part to play with. This is your objective:

Ready to finish

This is the model I chose by default.

1024 512 256 128
  8   16  32  64
  4   2   x   x
  x   x   x   x

The chosen corner is arbitrary, you basically never press one key (the forbidden move), and if you do, you press the contrary again and try to fix it. For future tiles the model always expects the next random tile to be a 2 and appear on the opposite side to the current model (while the first row is incomplete, on the bottom right corner, once the first row is completed, on the bottom left corner).

Here goes the algorithm. Around 80% wins (it seems it is always possible to win with more "professional" AI techniques, I am not sure about this, though.)

initiateModel();

while(!game_over)
{    
    checkCornerChosen(); // Unimplemented, but it might be an improvement to change the reference point

    for each 3 possible move:
        evaluateResult()
    execute move with best score
    if no move is available, execute forbidden move and undo, recalculateModel()
 }

 evaluateResult() {
     calculatesBestCurrentModel()
     calculates distance to chosen model
     stores result
 }

 calculateBestCurrentModel() {
      (according to the current highest tile acheived and their distribution)
  }

A few pointers on the missing steps. Here: model change

The model has changed due to the luck of being closer to the expected model. The model the AI is trying to achieve is

 512 256 128  x
  X   X   x   x
  X   X   x   x
  x   x   x   x

And the chain to get there has become:

 512 256  64  O
  8   16  32  O
  4   x   x   x
  x   x   x   x

The O represent forbidden spaces...

So it will press right, then right again, then (right or top depending on where the 4 has created) then will proceed to complete the chain until it gets:

Chain completed

So now the model and chain are back to:

 512 256 128  64
  4   8  16   32
  X   X   x   x
  x   x   x   x

Second pointer, it has had bad luck and its main spot has been taken. It is likely that it will fail, but it can still achieve it:

Enter image description here

Here the model and chain is:

  O 1024 512 256
  O   O   O  128
  8  16   32  64
  4   x   x   x

When it manages to reach the 128 it gains a whole row is gained again:

  O 1024 512 256
  x   x  128 128
  x   x   x   x
  x   x   x   x

Understanding the results of Execute Explain Plan in Oracle SQL Developer

FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.

Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.

You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.

How to force Docker for a clean build of an image

There's a --no-cache option:

docker build --no-cache -t u12_core -f u12_core .

In older versions of Docker you needed to pass --no-cache=true, but this is no longer the case.

PHP - find entry by object property from an array of objects

I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk

RS256 vs HS256: What's the difference?

Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.

  • RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

  • HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.

Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.

Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.

The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json, which contains the public key (or keys) of the account.

If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

How permission can be checked at runtime without throwing SecurityException?

This is another solution as well

PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(
    android.Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
   // do stuff
}

Get the cell value of a GridView row

Windows Form Iteration Technique

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Selected)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            int index = cell.ColumnIndex;
            if (index == 0)
            {
                value = cell.Value.ToString();
                //do what you want with the value
            }
        }
    }
}

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I had this trouble when I moved to Microsoft.EntityFrameworkCore.SqlServer v3.0.0 and Microsoft.EntityFrameworkCore.Tools v3.0.0

When I changed back to v2.2.6 on both libraries, the error went away. This is more of a workaround than a solution but it'll get you up and running till the issue is fixed.

Force IE10 to run in IE10 Compatibility View?

I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.

My thanks to Scott Hanselman for this fix.

Here is the link -

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.

Rick

How to submit a form using PhantomJS

Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.

CasperJS

Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.

(Thanks to commenter Mr. M!)

Error Installing Homebrew - Brew Command Not Found

try this

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Linuxbrew/linuxbrew/go/install)"

Getting msbuild.exe without installing Visual Studio

Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))" 

How do you check what version of SQL Server for a database using TSQL?

For SQL Server 2000 and above, I prefer the following parsing of Joe's answer:

declare @sqlVers numeric(4,2)
select @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)

Gives results as follows:

Result   Server Version
8.00     SQL 2000
9.00     SQL 2005
10.00    SQL 2008
10.50    SQL 2008R2
11.00    SQL 2012
12.00    SQL 2014

Basic list of version numbers here, or exhaustive list from Microsoft here.

How to use a table type in a SELECT FROM statement?

In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

create type exch_row as object (
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);

create type exch_tbl as table of exch_row;

And then you can use it in SQL with TABLE operator, for example:

declare
   l_row     exch_row;
   exch_rt   exch_tbl;
begin
   l_row := exch_row('PLN', 100, 100);
   exch_rt  := exch_tbl(l_row);

   for r in (select i.*
               from item i, TABLE(exch_rt) rt
              where i.currency = rt.currency_cd) loop
      -- your code here
   end loop;
end;
/

ipynb import another ipynb file

Run

!pip install ipynb

and then import the other notebook as

from ipynb.fs.full.<notebook_name> import *

or

from ipynb.fs.full.<notebook_name> import <function_name>

Make sure that all the notebooks are in the same directory.

Edit 1: You can see the official documentation here - https://ipynb.readthedocs.io/en/stable/

Also, if you would like to import only class & function definitions from a notebook (and not the top level statements), you can use ipynb.fs.defs instead of ipynb.fs.full. Full uppercase variable assignment will get evaluated as well.

Basic HTTP authentication with Node and Express 4

We can implement the basic authorization without needing any module

//1.
var http = require('http');

//2.
var credentials = {
    userName: "vikas kohli",
    password: "vikas123"
};
var realm = 'Basic Authentication';

//3.
function authenticationStatus(resp) {
    resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
    resp.end('Authorization is needed');

};

//4.
var server = http.createServer(function (request, response) {
    var authentication, loginInfo;

    //5.
    if (!request.headers.authorization) {
        authenticationStatus (response);
        return;
    }

    //6.
    authentication = request.headers.authorization.replace(/^Basic/, '');

    //7.
    authentication = (new Buffer(authentication, 'base64')).toString('utf8');

    //8.
    loginInfo = authentication.split(':');

    //9.
    if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
        response.end('Great You are Authenticated...');
         // now you call url by commenting the above line and pass the next() function
    }else{

    authenticationStatus (response);

}

});
 server.listen(5050);

Source:- http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

What is href="#" and why is it used?

Putting the "#" symbol as the href for something means that it points not to a different URL, but rather to another id or name tag on the same page. For example:

<a href="#bottomOfPage">Click to go to the bottom of the page</a>
blah blah
blah blah
...
<a id="bottomOfPage"></a>

However, if there is no id or name then it goes "no where."

Here's another similar question asked HTML Anchors with 'name' or 'id'?

What causes a TCP/IP reset (RST) flag to be sent?

A 'router' could be doing anything - particularly NAT, which might involve any amount of bug-ridden messing with traffic...

One reason a device will send a RST is in response to receiving a packet for a closed socket.

It's hard to give a firm but general answer, because every possible perversion has been visited on TCP since its inception, and all sorts of people might be inserting RSTs in an attempt to block traffic. (Some 'national firewalls' work like this, for example.)

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

How do you decompile a swf file

erlswf is an opensource project written in erlang for decompiling .swf files.

Here's the site: https://github.com/bef/erlswf

In Python How can I declare a Dynamic Array

In python, A dynamic array is an 'array' from the array module. E.g.

from array import array
x = array('d')          #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop()                 # returns 2.2

This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.

However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.

See https://docs.python.org/2/library/array.html for details.

How to create .ipa file using Xcode?

In Xcode-11.2.1

You might be see different pattern for uploading IPA
Steps:-

i) Add your apple developer id in xcode preference -> account

ii)Clean Build Folder :-

enter image description here

iii) Archive

enter image description here

iv) Tap on Distribute App

enter image description here

v) Choose Ad-hoc to distribute on designated device

enter image description here

6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)

enter image description here

enter image description here

7)Click on export and you get ipa.

enter image description here

8)Visit https://www.diawi.com/ & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)

How to prevent user from typing in text field without disabling the field?

For a css-only solution, try setting pointer-events: none on the input.

What do Push and Pop mean for Stacks?

Simply:

  • pop: returns the item at the top then remove it from the stack

  • push: add an item onto the top of the stack.

space between divs - display table-cell

Use transparent borders if possible.

JSFiddle Demo

https://jsfiddle.net/74q3na62/

HTML

<div class="table">
    <div class="row">
        <div class="cell">Cell 1</div>
        <div class="cell">Cell 2</div>
        <div class="cell">Cell 3</div>
    </div>
</div>

CSS

.table {
  display: table;
  border: 1px solid black;
}

.row { display:table-row; }

.cell {
  display: table-cell;
  background-clip: padding-box;
  background-color: gold;
  border-right: 10px solid transparent;
}

.cell:last-child {
  border-right: 0 none;
}

Explanation

You could use the border-spacing property, as the accepted answer suggests, but this not only generates space between the table cells but also between the table cells and the table container. This may be unwanted.

If you don't need visible borders on your table cells you should therefore use transparent borders to generate cell margins. Transparent borders require setting background-clip: padding-box; because otherwise the background color of the table cells is displayed on the border.

Transparent borders and background-clip are supported in IE9 upwards (and all other modern browsers). If you need IE8 compatibility or don't need actual transparent space you can simply set a white border color and leave the background-clip out.

How to turn off Wifi via ADB?

adb shell "svc wifi enable"

This worked & it makes action in background without opening related option !!

How do I configure PyCharm to run py.test tests?

I'm using 2018.2

I do Run -> Edit Configurations... Then click the + in the upper left of the modal dialog. Select "python tests" -> py.test Then I give it a name like "All test with py.test"

I select Target: module name and put in the module where my tests are (that is 'tests' for me) or the module where all my code is if my tests are mixed in with my code. This was tripping me up.

I set the Python interpreter.

I set the working directory to the project directory.

Check if value exists in enum in TypeScript

There is a very simple and easy solution to your question:

var districtId = 210;

if (DistrictsEnum[districtId] != null) {

// Returns 'undefined' if the districtId not exists in the DistrictsEnum 
    model.handlingDistrictId = districtId;
}

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

On OS X, choose "Document Format", and select all lines that you need format.

Then Option + Shift + F.

Comparison of DES, Triple DES, AES, blowfish encryption for data

Use AES.

In more details:

  • DES is the old "data encryption standard" from the seventies. Its key size is too short for proper security (56 effective bits; this can be brute-forced, as has been demonstrated more than ten years ago). Also, DES uses 64-bit blocks, which raises some potential issues when encrypting several gigabytes of data with the same key (a gigabyte is not that big nowadays).
  • 3DES is a trick to reuse DES implementations, by cascading three instances of DES (with distinct keys). 3DES is believed to be secure up to at least "2112" security (which is quite a lot, and quite far in the realm of "not breakable with today's technology"). But it is slow, especially in software (DES was designed for efficient hardware implementation, but it sucks in software; and 3DES sucks three times as much).
  • Blowfish is a block cipher proposed by Bruce Schneier, and deployed in some softwares. Blowfish can use huge keys and is believed secure, except with regards to its block size, which is 64 bits, just like DES and 3DES. Blowfish is efficient in software, at least on some software platforms (it uses key-dependent lookup tables, hence performance depends on how the platform handles memory and caches).
  • AES is the successor of DES as standard symmetric encryption algorithm for US federal organizations (and as standard for pretty much everybody else, too). AES accepts keys of 128, 192 or 256 bits (128 bits is already very unbreakable), uses 128-bit blocks (so no issue there), and is efficient in both software and hardware. It was selected through an open competition involving hundreds of cryptographers during several years. Basically, you cannot have better than that.

So, when in doubt, use AES.

Note that a block cipher is a box which encrypts "blocks" (128-bit chunks of data with AES). When encrypting a "message" which may be longer than 128 bits, the message must be split into blocks, and the actual way you do the split is called the mode of operation or "chaining". The naive mode (simple split) is called ECB and has issues. Using a block cipher properly is not easy, and it is more important than selecting between, e.g., AES or 3DES.

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

How to compare strings in sql ignoring case?

SELECT STRCMP("string1", "string2");

this returns 0 if the strings are equal.

  • If string1 = string2, this function returns 0 (ignoring the case)
  • If string1 < string2, this function returns -1
  • If string1 > string2, this function returns 1

https://www.w3schools.com/sql/func_mysql_strcmp.asp

How to re-create database for Entity Framework?

This worked for me:

  1. Delete database from SQL Server Object Explorer in Visual Studio. Right-click and select delete.
  2. Delete mdf and ldf files from file system - if they are still there.
  3. Rebuild Solution.
  4. Start Application - database will be re-created.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

How to add results of two select commands in same query

UNION ALL once, aggregate once:

SELECT sum(hours) AS total_hours
FROM   (
   SELECT hours FROM resource
   UNION ALL
   SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
   ) x

Currency formatting in Python

My locale settings seemed incomplete, so I had too look beyond this SO answer and found:

http://docs.python.org/library/decimal.html#recipes

OS-independent

Just wanted to share here.

grep output to show only matching file

You can use the Unix-style -l switch – typically terse and cryptic – or the equivalent --files-with-matches – longer and more readable.

The output of grep --help is not easy to read, but it's there:

-l, --files-with-matches  print only names of FILEs containing matches

Example: Communication between Activity and Service using Messaging

Note: You don't need to check if your service is running, CheckIfServiceIsRunning(), because bindService() will start it if it isn't running.

Also: if you rotate the phone you don't want it to bindService() again, because onCreate() will be called again. Be sure to define onConfigurationChanged() to prevent this.

Iterate over the lines of a string

If I read Modules/cStringIO.c correctly, this should be quite efficient (although somewhat verbose):

from cStringIO import StringIO

def iterbuf(buf):
    stri = StringIO(buf)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip()
        else:
            raise StopIteration

TypeScript error TS1005: ';' expected (II)

I was injecting service like this:

private messageShowService MessageShowService

instead of:

private messageShowService: MessageShowService

and that was the reason of error, despite nothing related with ',' was there.

SQL conditional SELECT

Sounds like they want the ability to return only allowed fields, which means the number of fields returned also has to be dynamic. This will work with 2 variables. Anything more than that will be getting confusing.

IF (selectField1 = true AND selectField2 = true)
BEGIN
   SELECT Field1, Field2
   FROM Table
END
ELSE IF (selectField1 = true)
BEGIN
   SELECT Field1
   FROM Table
END
ELSE IF (selectField2 = true)
BEGIN
   SELECT Field2
   FROM Table
END

Dynamic SQL will help with multiples. This examples is assuming atleast 1 column is true.

DECLARE @sql varchar(MAX)
SET @sql = 'SELECT '
IF (selectField1 = true)
BEGIN
   SET @sql = @sql + 'Field1, '
END
IF (selectField2 = true)
BEGIN
   SET @sql = @sql + 'Field2, '
END
...
-- DROP ', '
@sql = SUBSTRING(@sql, 1, LEN(@sql)-2)

SET @sql = @sql + ' FROM Table'

EXEC(@sql)

How do I install Java on Mac OSX allowing version switching?

You can use asdf to install and switch between multiple java versions. It has plugins for other languages as well. You can install asdf with Homebrew

brew install asdf

When asdf is configured, install java plugin

asdf plugin-add java

Pick a version to install

asdf list-all java

For example to install and configure adoptopenjdk8

asdf install java adoptopenjdk-8.0.272+10
asdf global java adoptopenjdk-8.0.272+10

And finally if needed, configure JAVA_HOME for your shell. Just add to your shell init script such as ~/.zshrc in case of zsh:

. ~/.asdf/plugins/java/set-java-home.zsh

How do I use Assert.Throws to assert the type of the exception?

Assert.Throws returns the exception that's thrown which lets you assert on the exception.

var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));

So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.

By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException and derivatives, you can assert that the parameter name is correct:

var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));

You can also use the fluent API for doing these asserts:

Assert.That(() => foo.Bar(null), 
Throws.Exception
  .TypeOf<ArgumentNullException>()
  .With.Property("ParamName")
  .EqualTo("bar"));

or alternatively

Assert.That(
    Assert.Throws<ArgumentNullException>(() =>
        foo.Bar(null)
    .ParamName,
Is.EqualTo("bar"));

A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.

Allowing Untrusted SSL Certificates with HttpClient

A quick and dirty solution is to use the ServicePointManager.ServerCertificateValidationCallback delegate. This allows you to provide your own certificate validation. The validation is applied globally across the whole App Domain.

ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => true;

I use this mainly for unit testing in situations where I want to run against an endpoint that I am hosting in process and am trying to hit it with a WCF client or the HttpClient.

For production code you may want more fine grained control and would be better off using the WebRequestHandler and its ServerCertificateValidationCallback delegate property (See dtb's answer below). Or ctacke answer using the HttpClientHandler. I am preferring either of these two now even with my integration tests over how I used to do it unless I cannot find any other hook.

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

jQuery location href

This is easier:

location.href = 'http://address.com';

Or

location.replace('http://address.com'); // <-- No history saved.

Syntax error: Illegal return statement in JavaScript

This can happen in ES6 if you use the incorrect (older) syntax for static methods:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

MyClass.anotherMethod() //or
MyClass.anotherMethod = function()
{
   return something; //doesn't work
}

Whereas the correct syntax is:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }

    static anotherMethod()
    {
       return something; //works
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

How do you find out which version of GTK+ is installed on Ubuntu?

You can also just open synaptic and search for libgtk, it will show you exactly which lib is installed.

CSS: fixed to bottom and centered

I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look

#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}

then in html...

<div id="enclose">
    <div id="problem">
    <!--this is where the text/markup would go-->
    </div>
</div>

There ya go!
-Hypertextie

ld cannot find an existing library

The problem is the linker is looking for libmagic.so but you only have libmagic.so.1

A quick hack is to symlink libmagic.so.1 to libmagic.so

Getter and Setter declaration in .NET

The 1st one is default, when there is nothing special to return or write. 2nd and 3rd are basically the same where 3rd is a bit more expanded version of 2nd

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

Finding the length of a Character Array in C

By saying "Character array" you mean a string? Like "hello" or "hahaha this is a string of characters"..

Anyway, use strlen(). Read a bit about it, there's plenty of info about it, like here.

Is there a CSS parent selector?

Here's a hack using pointer-events with hover:

_x000D_
_x000D_
<!doctype html>
<html>
    <head>
        <title></title>
        <style>
/* accessory */
.parent {
    width: 200px;
    height: 200px;
    background: gray;
}
.parent, 
.selector {
    display: flex;
    justify-content: center;
    align-items: center;
}
.selector {
    cursor: pointer;
    background: silver;
    width: 50%;
    height: 50%;
}
        </style>
        <style>
/* pertinent */
.parent {
    background: gray;
    pointer-events: none;
}
.parent:hover {
    background: fuchsia;
}
.parent 
.selector {
    pointer-events: auto;
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="selector"></div>
        </div>
    </body>
</html>
_x000D_
_x000D_
_x000D_

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

Using Razor within JavaScript

There is also one more option than @: and <text></text>.

Using <script> block itself.

When you need to do large chunks of JavaScript depending on Razor code, you can do it like this:

@if(Utils.FeatureEnabled("Feature")) {
    <script>
        // If this feature is enabled
    </script>
}

<script>
    // Other JavaScript code
</script>

Pros of this manner is that it doesn't mix JavaScript and Razor too much, because mixing them a lot will cause readability issues eventually. Also large text blocks are not very readable either.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

enter image description here

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.

How do I use namespaces with TypeScript external modules?

The proper way to organize your code is to use separate directories in place of namespaces. Each class will be in it's own file, in it's respective namespace folder. index.ts will only re-export each file; no actual code should be in the index.ts file. Organizing your code like this makes it far easier to navigate, and is self-documenting based on directory structure.

// index.ts
import * as greeter from './greeter';
import * as somethingElse from './somethingElse';

export {greeter, somethingElse};

// greeter/index.ts
export * from './greetings.js';
...

// greeter/greetings.ts
export const helloWorld = "Hello World";

You would then use it as such:

import { greeter } from 'your-package'; //Import it like normal, be it from an NPM module or from a directory.
// You can also use the following syntax, if you prefer:
import * as package from 'your-package';

console.log(greeter.helloWorld);

Timestamp with a millisecond precision: How to save them in MySQL

CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );

INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

How can I access my localhost from my Android device?

Adding a solution for future developers.

Copy address of your ip address. right click on your network -> network and sharing-> click on the connection you currently have-> details-> then the address beside ipv4 address is your ip address, note this down somewhere

Go to control panel -> system and security -> windows firewall -> advanced settings -> inbound rules -> new rules (follow the steps to add a port e.g 80, its really simple to follow)

put your ip address that you noted down on your phone browser and the port number you created the rule for beside it. e.g 192.168.0.2:80 and wala.

Possible solution if it doesn't connect. right click network->open network and sharing-> look under view your active connections, under the name of your connection at the type of connection and click on it if it is public, and make sure to change it to a home network.

What is the difference between AF_INET and PF_INET in socket programming?

Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for).
That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.

Find text in string with C#

static void Main(string[] args)
    {

        int f = 0;
        Console.WriteLine("enter the string");
        string s = Console.ReadLine();
        Console.WriteLine("enter the word to be searched");
        string a = Console.ReadLine();
        int l = s.Length;
        int c = a.Length;

        for (int i = 0; i < l; i++)
        {
            if (s[i] == a[0])
            {
                for (int K = i + 1, j = 1; j < c; j++, K++)
                {
                    if (s[K] == a[j])
                    {
                        f++;
                    }
                }
            }
        }
        if (f == c - 1)
        {
            Console.WriteLine("matching");
        }
        else
        {
            Console.WriteLine("not found");
        }
        Console.ReadLine();
    }

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

How to get the contents of a webpage in a shell variable?

There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:

If you need the code source:

with curl:

curl $url

with wget:

wget -O - $url

but if you want to get what you can see with a browser, lynx can be useful:

lynx -dump $url

I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url by your URL :)

Good luck :)

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

How to use C++ in Go

Update: I've succeeded in linking a small test C++ class with Go

If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp).

I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.

Here's an example:

I have a C++ class defined as:

// foo.hpp
class cxxFoo {
public:
  int a;
  cxxFoo(int _a):a(_a){};
  ~cxxFoo(){};
  void Bar();
};

// foo.cpp
#include <iostream>
#include "foo.hpp"
void
cxxFoo::Bar(void){
  std::cout<<this->a<<std::endl;
}

which I want to use in Go. I'll use the C interface

// foo.h
#ifdef __cplusplus
extern "C" {
#endif
  typedef void* Foo;
  Foo FooInit(void);
  void FooFree(Foo);
  void FooBar(Foo);
#ifdef __cplusplus
}
#endif

(I use a void* instead of a C struct so the compiler knows the size of Foo)

The implementation is:

//cfoo.cpp
#include "foo.hpp"
#include "foo.h"
Foo FooInit()
{
  cxxFoo * ret = new cxxFoo(1);
  return (void*)ret;
}
void FooFree(Foo f)
{
  cxxFoo * foo = (cxxFoo*)f;
  delete foo;
}
void FooBar(Foo f)
{
  cxxFoo * foo = (cxxFoo*)f;
  foo->Bar();
}

with all that done, the Go file is:

// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
     foo C.Foo;
}
func New()(GoFoo){
     var ret GoFoo;
     ret.foo = C.FooInit();
     return ret;
}
func (f GoFoo)Free(){
     C.FooFree(unsafe.Pointer(f.foo));
}
func (f GoFoo)Bar(){
     C.FooBar(unsafe.Pointer(f.foo));
}

The makefile I used to compile this was:

// makefile
TARG=foo
CGOFILES=foo.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
foo.o:foo.cpp
    g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
cfoo.o:cfoo.cpp
    g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
CGO_LDFLAGS+=-lstdc++
$(elem)_foo.so: foo.cgo4.o foo.o cfoo.o
    gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $@ $^ $(CGO_LDFLAGS)

Try testing it with:

// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
    foo := New();
    foo.Bar();
    foo.Free();
}

You'll need to install the shared library with make install, then run make test. Expected output is:

gotest
rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6  foo.cgo3.6
1
PASS