Programs & Examples On #Degrafa

Removing carriage return and new-line from the end of a string in c#

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

Rendering HTML in a WebView with custom CSS

You can Use Online Css link To set Style over existing content.

For That you have to load data in webview and enable JavaScript Support.

See Below Code:

   WebSettings webSettings=web_desc.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    webSettings.setTextZoom(55);
    StringBuilder sb = new StringBuilder();
    sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
    sb.append(currentHomeContent.getDescription());
    sb.append("</body></HTML>");
    currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);

Here Use StringBuilder to append String for Style.

sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());

What's the difference between window.location and document.location in JavaScript?

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

How to restrict UITextField to take only numbers in Swift?

Accept decimal values in text fields with single (.)dot in Swift 3

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

    let components = string.components(separatedBy: inverseSet)

    let filtered = components.joined(separator: "")

    if filtered == string {
        return true
    } else {
        if string == "." {
            let countdots = textField.text!.components(separatedBy:".").count - 1
            if countdots == 0 {
                return true
            }else{
                if countdots > 0 && string == "." {
                    return false
                } else {
                    return true
                }
            }
        }else{
            return false
        }
    }
}

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.

the gps signal does indeed include a precise time signal, which is available with any "fix".

however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.

note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?

PHP display image BLOB from MySQL

Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

where: mime can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob in database.

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

How do I apply the for-each loop to every character in a String?

You can also use a lambda in this case.

    String s = "xyz";
    IntStream.range(0, s.length()).forEach(i -> {
        char c = s.charAt(i);
    });

Typescript : Property does not exist on type 'object'

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

How to call multiple functions with @click in vue?

Html:

<div id="example">
  <button v-on:click="multiple">Multiple</button>
</div>

JS:

var vm = new Vue({
  el: '#example',
  data: {
    name: 'Vue.js'
  },
  // define methods under the `methods` object
  methods: {
    multiple: function (event) {
      this.first()
      this.second()
    }
    first:  function (event) {
      //yourstuff
    }
    second: function (event) {
      //yourstuff
    }
  }
})

vm.multiple()

Adding an onclick function to go to url in JavaScript?

function URL() {
    location.href = 'http://your.url.here';
}

How to mock private method for testing using PowerMock?

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

  1. Change your private method to protected.
  2. In your test class extend the class
  3. override the previously-private method to return whatever constant you want

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

It can be done with the regular JavaScript function replace().

value.replace(".", ":");

How to "select distinct" across multiple data frame columns in pandas?

You can use the drop_duplicates method to get the unique rows in a DataFrame:

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

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

You can also provide the subset keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.

Inserting image into IPython notebook markdown

Last version of jupyter notebook accepts copy/paste of image natively

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.

<context:component-scan>: Bean registration + <context:annotation-config>


@Autowired and @Required are targets property level so bean should register in spring IOC before use these annotations. To enable these annotations either have to register respective beans or include <context:annotation-config />. i.e. <context:annotation-config /> works with registered beans only.

@Required enables RequiredAnnotationBeanPostProcessor processing tool
@Autowired enables AutowiredAnnotationBeanPostProcessor processing tool

Note: Annotation itself nothing to do, we need a Processing Tool, which is a class underneath, responsible for the core process.


@Repository, @Service and @Controller are @Component, and they targets class level.

<context:component-scan> it scans the package and find and register the beans, and it includes the work done by <context:annotation-config />.

Migrating XML to Annotations

How to generate keyboard events?

For both python3 and python2 you can use pyautogui (pip install pyautogui)

from pyautogui import press, typewrite, hotkey

press('a')
typewrite('quick brown fox')
hotkey('ctrl', 'w')

It's also crossplatform with Windows, OSX, and Ubuntu LTS.

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Read a text file line by line in Qt

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getline and is maybe faster as QTextStream::readLine, because it reuses the string:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

Remove non-numeric characters (except periods and commas) from a string

You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:

$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);

The pattern can also be expressed as /[^\d,.]+/

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

Can I recover a branch after its deletion in Git?

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha. another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

How to copy commits from one branch to another?

Suppose I have committed changes to master branch.I will get the commit id(xyz) of the commit now i have to go to branch for which i need to push my commits.

Single commit id xyx

git checkout branch-name
git cherry-pick xyz
git push origin branch-name

Multiple commit id's xyz abc qwe

git checkout branch-name
git cherry-pick xyz abc qwe
git push origin branch-name

What should be the sizeof(int) on a 64-bit machine?

In C++, the size of int isn't specified explicitly. It just tells you that it must be at least the size of short int, which must be at least as large as signed char. The size of char in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long to be at least 64 bits.

How can I run MongoDB as a Windows service?

For version 2.4.3 (current version as of posting date), create a config file and then execute the following:

C:\MongoDB\bin\mongod.exe --config C:\MongoDB\mongod.cfg --service

Leaflet - How to find existing markers, and delete markers?

Here's a jsFiddle that lets you to create markers using your onMapClick method, then delete them by clicking a link.

The process is similar to undefined's - add each new marker to a markers array so you can access a specific marker when you want to interact with it later.

Extracting Nupkg files using command line

NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.

React / JSX Dynamic Component Name

I figured out a new solution. Do note that I am using ES6 modules so I am requiring the class. You could also define a new React class instead.

var components = {
    example: React.createFactory( require('./ExampleComponent') )
};

var type = "example";

newComponent() {
    return components[type]({ attribute: "value" });
}

Show DataFrame as table in iPython Notebook

from IPython.display import display
display(df)  # OR
print df.to_html()

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

Just in case someone wants to do it for exact matches of strings, you can use the -w flag in grep - w for whole. That is, for example if you want to delete the lines that have number 11, but keep the lines with number 111:

-bash-4.1$ head file
1
11
111

-bash-4.1$ grep -v "11" file
1

-bash-4.1$ grep -w -v "11" file
1
111

It also works with the -f flag if you want to exclude several exact patterns at once. If "blacklist" is a file with several patterns on each line that you want to delete from "file":

grep -w -v -f blacklist file

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

How to get text from EditText?

The quickest solution to your problem I believe is that you simply are missing parentheses on your getText. Simply add () to edit.getText().toString() and that should solve it

The project type is not supported by this installation

I had the same problem opening the NuGet solution with VS 2010 Ultimate, but the following command fixed it:

devenv /ResetSkipPkgs

Bootstrap full-width text-input within inline-form

The bootstrap docs says about this:

Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.

The default width of 100% as all form elements gets when they got the class form-control didn't apply if you use the form-inline class on your form.

You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:

.form-inline {

  // Kick in the inline
  @media (min-width: @screen-sm-min) {
    // Inline-block all the things for "inline"
    .form-group {
      display: inline-block;
      margin-bottom: 0;
      vertical-align: middle;
    }

    // In navbar-form, allow folks to *not* use `.form-group`
    .form-control {
      display: inline-block;
      width: auto; // Prevent labels from stacking above inputs in `.form-group`
      vertical-align: middle;
    }
    // Input groups need that 100% width though
    .input-group > .form-control {
      width: 100%;
    }

    [...]
  }
}

Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):

<div class="row">
   <div class="col-lg-12">
    <div class="input-group input-group-lg">
      <input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
      <span class="input-group-btn">
        <button class="btn btn-default btn-lg" type="submit">Search</button>
      </span>
    </div>
  </div>
</div>

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

In the controller add following lines when you make the cunstructor

i.e, after

parent::Controller();

add below lines

    $this->load->helper('lang_translate');
    $this->lang->load('nl_site', 'nl'); // ('filename', 'directory')

create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers

function label($label, $obj)
{
    $return = $obj->lang->line($label);
    if($return)
        echo $return;
    else
        echo $label;
}

for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under system\application\languages

create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below

nl_site_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

en_site_lang.php

$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';

you can store multiple files for same language with differently as per the requirement e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');

nl_admin_lang.php

$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';

and finally to print the label in desired language, access labels as below in view

label('welcome', $this);

OR

label('hello word', $this);

note the space in hello & word you can use it like this way as well :)

whene there is no lable defined in the language file, it will simply print it what you passed to the function label.

Load HTML File Contents to Div [without the use of iframes]

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

How to retrieve GET parameters from JavaScript

If you are using AngularJS, you can use $routeParams using ngRoute module

You have to add a module to your app

angular.module('myApp', ['ngRoute'])

Now you can use service $routeParams:

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); // JSON object
}

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

I had the same problem in my code. I was concatenating a string to create a string. Below is the part of code.

int scannerId = 1;
std:strring testValue;
strInXml = std::string(std::string("<inArgs>" \
                        "<scannerID>" + scannerId) + std::string("</scannerID>" \
                        "<cmdArgs>" \
                        "<arg-string>" + testValue) + "</arg-string>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "</cmdArgs>"\
                        "</inArgs>");

javascript close current window

I know this is an old post, with a lot of changes since 2017, but I have found that I can close my current tab/window with:

onClick="javascript:window.close('','_parent','');", now in 2019.  

Converting Integer to String with comma for thousands

If the same has to be done in the JSP , use:

<fmt:formatNumber pattern="#,##0" value="${yourlist.yourintvalue}" var="formattedVariable" />
<c:out value="${formattedVariable}"></c:out>

ofcourse for multiple values use :

<c:forEach items="${yourlist}" var="yourlist">

    <fmt:formatNumber pattern="#,##0" value="${yourlist.yourintvalue}" var="formattedVariable" />
    <c:out value="${formattedVariable}"></c:out>
</c:forEach>

How to update RecyclerView Adapter Data?

This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:

  1. Update the data set
  2. Notify the adapter of the change

#Insert single item

Add "Pig" at index 2.

Insert single item
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

#Insert multiple items

Insert three more animals at index 2.

Insert multiple items
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

#Remove a single item

Remove "Pig" from the list.

Remove single item
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

#Remove multiple items

Remove "Camel" and "Sheep" from the list.

Remove multiple items
int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

#Remove all items

Clear the whole list.

Remove all items
data.clear();
adapter.notifyDataSetChanged();

#Replace old list with the new list

Clear the old list then add a new one.

Replace old list with new list
// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

The adapter has a reference to data, so it is important that I didn't set data to a new object. Instead, I cleared the old items from data and then added the new ones.

#Update single item

Change the "Sheep" item so that it says "I like sheep."

Update single item
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

#Move single item

Move "Sheep" from position 3 to position 1.

Move single item
int fromPosition = 3;
int toPosition = 1;

// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);

// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

#Code

Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    List<String> data;
    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        data = new ArrayList<>();
        data.add("Horse");
        data.add("Cow");
        data.add("Camel");
        data.add("Sheep");
        data.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void onButtonClick(View view) {
        insertSingleItem();
    }

    private void insertSingleItem() {
        String item = "Pig";
        int insertIndex = 2;
        data.add(insertIndex, item);
        adapter.notifyItemInserted(insertIndex);
    }

    private void insertMultipleItems() {
        ArrayList<String> items = new ArrayList<>();
        items.add("Pig");
        items.add("Chicken");
        items.add("Dog");
        int insertIndex = 2;
        data.addAll(insertIndex, items);
        adapter.notifyItemRangeInserted(insertIndex, items.size());
    }

    private void removeSingleItem() {
        int removeIndex = 2;
        data.remove(removeIndex);
        adapter.notifyItemRemoved(removeIndex);
    }

    private void removeMultipleItems() {
        int startIndex = 2; // inclusive
        int endIndex = 4;   // exclusive
        int count = endIndex - startIndex; // 2 items will be removed
        data.subList(startIndex, endIndex).clear();
        adapter.notifyItemRangeRemoved(startIndex, count);
    }

    private void removeAllItems() {
        data.clear();
        adapter.notifyDataSetChanged();
    }

    private void replaceOldListWithNewList() {
        // clear old list
        data.clear();

        // add new list
        ArrayList<String> newList = new ArrayList<>();
        newList.add("Lion");
        newList.add("Wolf");
        newList.add("Bear");
        data.addAll(newList);

        // notify adapter
        adapter.notifyDataSetChanged();
    }

    private void updateSingleItem() {
        String newValue = "I like sheep.";
        int updateIndex = 3;
        data.set(updateIndex, newValue);
        adapter.notifyItemChanged(updateIndex);
    }

    private void moveSingleItem() {
        int fromPosition = 3;
        int toPosition = 1;

        // update data array
        String item = data.get(fromPosition);
        data.remove(fromPosition);
        data.add(toPosition, item);

        // notify adapter
        adapter.notifyItemMoved(fromPosition, toPosition);
    }
}

#Notes

  • If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.
  • Check out DiffUtil if you are making large or complex changes to a list.

#Further study

How to get first and last day of the current week in JavaScript

_x000D_
_x000D_
function getMonday(d) {
    d = new Date(d);
    var day = d.getDay(),
        diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
    return new Date(d.setDate(diff));
  }
  
 console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) )  // Mon Nov 08 2010
_x000D_
_x000D_
_x000D_

How to Display blob (.pdf) in an AngularJS app

First of all you need to set the responseType to arraybuffer. This is required if you want to create a blob of your data. See Sending_and_Receiving_Binary_Data. So your code will look like this:

$http.post('/postUrlHere',{myParams}, {responseType:'arraybuffer'})
  .success(function (response) {
       var file = new Blob([response], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
});

The next part is, you need to use the $sce service to make angular trust your url. This can be done in this way:

$scope.content = $sce.trustAsResourceUrl(fileURL);

Do not forget to inject the $sce service.

If this is all done you can now embed your pdf:

<embed ng-src="{{content}}" style="width:200px;height:200px;"></embed>

An established connection was aborted by the software in your host machine

This problem appear if two software use same port
generally Android studio use the port 5037
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

how to read certain columns from Excel using Pandas - Python

"usecols" should help, use range of columns (as per excel worksheet, A,B...etc.) below are the examples

  1. Selected Columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A,C,F")
  1. Range of Columns and selected column
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H")
  1. Multiple Ranges
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:F,H,J:N")
  1. Range of columns
df = pd.read_excel(file_location,sheet_name='Sheet1', usecols="A:N")

Make Iframe to fit 100% of container's remaining height

You can do this by measuring the body size on load/resize events and setting the height to the (full height - banner height).

Note that currently in IE8 Beta2 you can't do this onresize as that event is currently broken in IE8 Beta2.

How to create websockets server in PHP

I was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.

drag drop files into standard html file input

This is what I came out with.

Using Jquery and Html. This will add it to the insert files.

_x000D_
_x000D_
var dropzone = $('#dropzone')_x000D_
_x000D_
_x000D_
dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {_x000D_
    e.preventDefault();_x000D_
    e.stopPropagation();_x000D_
  })_x000D_
_x000D_
dropzone.on('dragover dragenter', function() {_x000D_
    $(this).addClass('is-dragover');_x000D_
  })_x000D_
dropzone.on('dragleave dragend drop', function() {_x000D_
    $(this).removeClass('is-dragover');_x000D_
  })  _x000D_
  _x000D_
dropzone.on('drop',function(e) {_x000D_
 var files = e.originalEvent.dataTransfer.files;_x000D_
 // Now select your file upload field _x000D_
 // $('input_field_file').prop('files',files)_x000D_
  });
_x000D_
input { margin: 15px 10px !important;}_x000D_
_x000D_
.dropzone {_x000D_
 padding: 50px;_x000D_
 border: 2px dashed #060;_x000D_
}_x000D_
_x000D_
.dropzone.is-dragover {_x000D_
  background-color: #e6ecef;_x000D_
}_x000D_
_x000D_
.dragover {_x000D_
 bg-color: red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<div class="" draggable='true' style='padding: 20px'>_x000D_
 <div id='dropzone' class='dropzone'>_x000D_
  Drop Your File Here_x000D_
 </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

"python" not recognized as a command

emphasis: Remember to always RESTART the CMD WINDOW after setting the PATH environmental variable for it to take effect!

Alternative for frames in html5 using iframes

Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:

Template File

<html>
<head>
<title>{insert script variable for title}</title>
</head>

<body>
  <div class="menu">
   {menu items inserted here by server-side scripting}
  </div>
  <div class="main-content">
   {main content inserted here by server-side scripting}
  </div>
</body>
</html>

If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.

But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.

You could emulate your example like this:

Frames Example

<html>
<head>
  <title>Frames Test</title>
  <style>
   .menu {
      float:left;
      width:20%;
      height:80%;
    }
    .mainContent {
      float:left;
      width:75%;
      height:80%;
    }
  </style>
</head>
<body>
  <iframe class="menu" src="menu.html"></iframe>
  <iframe class="mainContent" src="events.html"></iframe>
</body>
</html>

There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.

How to make function decorators and chain them together?

Python decorators add extra functionality to another function

An italics decorator could be like

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

So now I can change my class to

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

For more on decorators, check http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

How do I load a file from resource folder?

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
    // Process line
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.

UICollectionView spacing margins

Set the insetForSectionAt property of the UICollectionViewFlowLayout object attached to your UICollectionView

Make sure to add this protocol

UICollectionViewDelegateFlowLayout

Swift

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
    }

Objective - C

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

Simple dictionary in C++

This is the fastest, simplest, smallest space solution I can think of. A good optimizing compiler will even remove the cost of accessing the pair and name arrays. This solution works equally well in C.

#include <iostream>

enum Base_enum { A, C, T, G };
typedef enum Base_enum Base;
static const Base pair[4] = { T, G, A, C };
static const char name[4] = { 'A', 'C', 'T', 'G' };
static const Base base[85] = 
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1,  A, -1,  C, -1, -1,
    -1,  G, -1, -1, -1, -1, -1, -1, -1, -1, 
    -1, -1, -1, -1,  T };

const Base
base2 (const char b)
{
  switch (b)
    {
    case 'A': return A;
    case 'C': return C;
    case 'T': return T;
    case 'G': return G;
    default: abort ();
    }
}

int
main (int argc, char *args) 
{
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[b] << ":" 
                << name[pair[b]] << std::endl;
    }
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[base[name[b]]] << ":" 
                << name[pair[base[name[b]]]] << std::endl;
    }
  for (Base b = A; b <= G; b++)
    {
      std::cout << name[base2(name[b])] << ":" 
                << name[pair[base2(name[b])]] << std::endl;
    }
};

base[] is a fast ascii char to Base (i.e. int between 0 and 3 inclusive) lookup that is a bit ugly. A good optimizing compiler should be able to handle base2() but I'm not sure if any do.

JavaScript CSS how to add and remove multiple CSS classes to an element

You can add and remove multiple classes in same way with different in-built methods:

const myElem = document.getElementById('element-id');
//add multiple classes
myElem.classList.add('class-one', 'class-two', 'class-three');
//remove multiple classes
myElem.classList.remove('class-one', 'class-two', 'class-three');

Lumen: get URL parameter in a Blade view

Laravel 5.8

{{ request()->a }}

javascript filter array of objects

You can do this very easily with the [].filter method:

var filterednames = names.filter(function(obj) {
    return (obj.name === "Joe") && (obj.age < 30);
});

You will need to add a shim for browsers that don't support the [].filter method: this MDN page gives such code.

Rails Object to hash

You could definitely use the attributes to return all attributes but you could add an instance method to Post, call it "to_hash" and have it return the data you would like in a hash. Something like

def to_hash
 { name: self.name, active: true }
end

recyclerview No adapter attached; skipping layout

I was getting same issue, I did every thing correct excepted in xml file:

  • step first 1: initialize recyclerview & List & Adaptor:

    RecyclerView recyclerview;
    List<ModelName> list;
    ProvideBidAdaptor adaptor;
    
  • step 2: bind it in onCreate-

    recyclerview = findByViewId(R.id.providerBidRV);
    recyclerview.setLayoutManager(new LinearLayoutManager(this));
    recyclerview.setHasFixedSize(true);
    list = new ArrayList<>();
    
  • step 3: Where you getting response or list - add list- (i am getting from response)>

    responseList.addAll(response.getResponse());
    adaptor = new ProvideBidAdaptor(this, responseList);
    binding.detailsRV.setAdapter(adaptor);
    

Here is my xml file where i implement RecyclerView: I was forget orientation in LinearLayout, after this correction- RecyclerView attached.

<?xml version="1.0" encoding="utf-8"?>
    <layout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".activities.Bidding.ProvideBid">

        <include
            android:id="@+id/toolbar"
            layout="@layout/app_toolbar"/>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/providerBidRV"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
</layout> 

Here is Adaptor:

    public class ProvideBidAdaptor extends RecyclerView.Adapter<ProvideBidAdaptor.ViewHolder> {
    Context context;
    List<Response> responseList;
    DateTime dateTimeInstance = new DateTime();

    public ProvideBidAdaptor(Context context, List<Response> responseList) {
        this.context = context;
        this.responseList = responseList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.geo_presence_item_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Response detailsResponse = responseList.get(position);
        if (!detailsResponse.getUserId().isEmpty()) {

            holder.day.setText(detailsResponse.getDay());
            holder.locationType.setText(detailsResponse.getLocationType());

        }

    }

    @Override
    public int getItemCount() {
        return responseList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView date,locationType;
        CardView provideBidCV;
        LinearLayout dayLLayout,locationTypeLLayout;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            date = itemView.findViewById(R.id.date_value);
            day = itemView.findViewById(R.id.day_value);
            locationType = itemView.findViewById(R.id.locationType_value);

            locationTypeLLayout = itemView.findViewById(R.id.locationTypeLLayout);

        }
    }
}

Import CSV file as a pandas DataFrame

Try this

import pandas as pd
data=pd.read_csv('C:/Users/Downloads/winequality-red.csv')

Replace the file target location, with where your data set is found, refer this url https://medium.com/@kanchanardj/jargon-in-python-used-in-data-science-to-laymans-language-part-one-12ddfd31592f

How to pass parameters to a modal?

If you're not using AngularJS UI Bootstrap, here's how I did it.

I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.

angular.module('yourApp', []).
directive('myModal',
       ['$rootScope','$log','$compile',
function($rootScope,  $log,  $compile) {
    var _scope = null;
    var _element = null;
    var _onModalShow = function(event) {
        _element.after($compile(event.target)(_scope));
    };

    return {
        link: function(scope, element, attributes) {
            _scope = scope;
            _element = element;
            $(element).on('show.bs.modal',_onModalShow);
        }
    };
}]);

I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.

Note: The entire scope is now visible to your modal so you can also access $scope.users in it.

<div my-modal id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{aModel.userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

The requested operation cannot be performed on a file with a user-mapped section open

Happened to me after I have changed the project target CPU from 'Any CPU' to 'X64' and then back to 'Any CPU'.
Solved it by deleting the Obj folder (for beginners: don`t worry about deleting the obj folder, it will be recreated again in the next compile).

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

Is it possible to Turn page programmatically in UIPageViewController?

In Swift:

import UIKit

extension HomeViewController {

    // MARK: - Carousel management.

    func startTimerForMovingCarousel(let numberOfSecondsBetweenFiringsOfTheTimer: NSTimeInterval) {
        if (self.timerForMovingCarousel == nil) {
            self.timerForMovingCarousel = NSTimer.scheduledTimerWithTimeInterval(numberOfSecondsBetweenFiringsOfTheTimer,
                                                                            target: self,
                                                                            selector: "moveCarousel",
                                                                            userInfo: nil,
                                                                            repeats: true)
        }
    }

    func moveCarousel() {
        println("I move the carousel.")

        let currentContentViewControllerDisplayed = self.pageViewController!.viewControllers[0] as! ContentViewController

        var index: Int = currentContentViewControllerDisplayed.index

        if index == self.arrayViewControllers.count - 1 {
            index = 0
        } else {
            ++index
        }

        let contentViewControllerToDisplay = self.arrayViewControllers[index] as! ContentViewController

        self.pageViewController.setViewControllers([contentViewControllerToDisplay],
                                                    direction: UIPageViewControllerNavigationDirection.Forward,
                                                    animated: true,
                                                    completion: nil)

        self.pageControl.currentPage = contentViewControllerToDisplay.index
    }

    func invalidateTimerForMovingCarousel() {
        if (self.timerForMovingCarousel != nil) {
            self.timerForMovingCarousel.invalidate()
            self.timerForMovingCarousel = nil
        }
    }

}

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

How do I import an SQL file using the command line in MySQL?

Among all the answers, for the problem above, this is the best one:

 mysql> use db_name;
 mysql> source file_name.sql;

How do I set the default page of my application in IIS7?

Just go to web.config file and add following

<system.webServer>
    <defaultDocument>
      <files>
        <clear />
        <add value="Path of your Page" />
      </files>
    </defaultDocument>
</system.webServer>

Error while trying to run project: Unable to start program. Cannot find the file specified

I encountered a similar problem. And I found the solution to be totally unrelated to the error. The trick was renaming the assembly name. Solution: VS 2013 -> Project properties -> Application tab -> AssemblyName property changed to new name < 25 chars

How do I create a table based on another table

select * into newtable from oldtable

Safely casting long to int in Java

here is a solution, in case you don't care about value in case it is bigger then needed ;)

public static int safeLongToInt(long l) {
    return (int) Math.max(Math.min(Integer.MAX_VALUE, l), Integer.MIN_VALUE);
}

Stop form refreshing page on submit

This problem becomes more complex when you give the user 2 possibilities to submit the form:

  1. by clicking on an ad hoc button
  2. by hitting Enter key

In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.

And now comes the problem with IE (in any case version 11) Remark: This issue does not exist with Chrome nor with FireFox !

  • When you click the submit button the form is submitted once; fine.
  • When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.

Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks. This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)

The source code HTML & js are in the snippet. The principle is described there. Warning:

You can't test it in the snippet because the post action is not defined and hitting Enter key might interfer with stackoverflow.

If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.

_x000D_
_x000D_
/*_x000D_
 * inForm points to the form_x000D_
 */_x000D_
var inForm = document.getElementById('idGetUserFrm');_x000D_
/*_x000D_
 * IE submits the form twice_x000D_
 * To avoid this the boolean isSumbitted is:_x000D_
 *  1) initialized to false when the form is displayed 4 the first time_x000D_
 * Remark: it is not the same event as "body load"_x000D_
 */_x000D_
var isSumbitted = false;_x000D_
_x000D_
function checkEnter(e) {_x000D_
  if (e && e.keyCode == 13) {_x000D_
    inForm.submit();_x000D_
    /*_x000D_
      * 2) set to true after the form submission was invoked_x000D_
      */_x000D_
    isSumbitted = true;_x000D_
  }_x000D_
}_x000D_
function onSubmit () {_x000D_
  if (isSumbitted) {_x000D_
    /*_x000D_
    * 3) reset to false after the form submission executed_x000D_
    */_x000D_
    isSumbitted = false;_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">_x000D_
   First name:<br>_x000D_
   <input type="text" name="firstname" value="Mickey">_x000D_
   <input type="submit" value="Submit">_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I check if a command exists in a shell script?

A function which works in both bash and zsh:

# Return the first pathname in $PATH for name in $1
function cmd_path () {
  if [[ $ZSH_VERSION ]]; then
    whence -cp "$1" 2> /dev/null
  else  # bash
     type -P "$1"  # No output if not in $PATH
  fi
}

Non-zero is returned if the command is not found in $PATH.

ipad safari: disable scrolling, and bounce effect?

Code to To remove ipad safari: disable scrolling, and bounce effect

   document.addEventListener("touchmove", function (e) {
        e.preventDefault();
    }, { passive: false });

If you have canvas tag inside document, sometime it will affect the usability of object inside Canvas(example: movement of object); so add below code to fix it.

    document.getElementById("canvasId").addEventListener("touchmove", function (e) {
        e.stopPropagation();
    }, { passive: false });

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

Another example, more simple than some others with simple return of incremented value:

function testIncrement1(x) {
    return x++;
}

function testIncrement2(x) {
    return ++x;
}

function testIncrement3(x) {
    return x += 1;
}

console.log(testIncrement1(0)); // 0
console.log(testIncrement2(0)); // 1
console.log(testIncrement3(0)); // 1

As you can see, no post-increment/decrement should be used at return statement, if you want this operator to influence the result. But return doesn't "catch" post-increment/decrement operators:

function closureIncrementTest() {
    var x = 0;

    function postIncrementX() {
        return x++;
    }

    var y = postIncrementX();

    console.log(x); // 1
}

JFrame: How to disable window resizing?

Simply write one line in the constructor:

setResizable(false);

This will make it impossible to resize the frame.

How to replicate vector in c?

A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:

typedef struct dynamic_array_struct
{
  int* data;
  size_t capacity; /* total capacity */
  size_t size; /* number of elements in vector */
} vector;

Then they would have various API function calls which operate on the vector:

int vector_init(vector* v, size_t init_capacity)
{
  v->data = malloc(init_capacity * sizeof(int));
  if (!v->data) return -1;

  v->size = 0;
  v->capacity = init_capacity;

  return 0; /* success */
}

Then of course, you need functions for push_back, insert, resize, etc, which would call realloc if size exceeds capacity.

vector_resize(vector* v, size_t new_size);

vector_push_back(vector* v, int element);

Usually, when a reallocation is needed, capacity is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by std::vector, except typically std::vector won't call realloc because of C++ object construction/destruction. Rather, std::vector might allocate a new buffer, and then copy construct/move construct the objects (using placement new) into the new buffer.

An actual vector implementation in C might use void* pointers as elements rather than int, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c for an example vector implementation in C.

How can I use pointers in Java?

from the book named Decompiling Android by Godfrey Nolan

Security dictates that pointers aren’t used in Java so hackers can’t break out of an application and into the operating system. No pointers means that something else----in this case, the JVM----has to take care of the allocating and freeing memory. Memory leaks should also become a thing of the past, or so the theory goes. Some applications written in C and C++ are notorious for leaking memory like a sieve because programmers don’t pay attention to freeing up unwanted memory at the appropriate time----not that anybody reading this would be guilty of such a sin. Garbage collection should also make programmers more productive, with less time spent on debugging memory problems.

Find a string within a cell using VBA

you never change the value of rng so it always points to the initial cell

copy the Set rng = rng.Offset(1, 0) to a new line before loop

also, your InStr test will always fail
True is -1, but the return from InStr will be greater than 0 when the string is found. change the test to remove = True

new code:

Sub IfTest()
 'This should split the information in a table up into cells
 Dim Splitter() As String
 Dim LenValue As Integer     'Gives the number of characters in date string
 Dim LeftValue As Integer    'One less than the LenValue to drop the ")"
 Dim rng As Range, cell As Range
 Set rng = ActiveCell

Do While ActiveCell.Value <> Empty
    If InStr(rng, "%") Then
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "% Change")
        ActiveCell.Offset(0, 10).Select
        ActiveCell.Value = Splitter(1)
        ActiveCell.Offset(0, -1).Select
        ActiveCell.Value = "% Change"
        ActiveCell.Offset(1, -9).Select
    Else
        ActiveCell.Offset(0, 0).Select
        Splitter = Split(ActiveCell.Value, "(")
        ActiveCell.Offset(0, 9).Select
        ActiveCell.Value = Splitter(0)
        ActiveCell.Offset(0, 1).Select
        LenValue = Len(Splitter(1))
        LeftValue = LenValue - 1
        ActiveCell.Value = Left(Splitter(1), LeftValue)
        ActiveCell.Offset(1, -10).Select
    End If
Set rng = rng.Offset(1, 0)
Loop

End Sub

How can I check which version of Angular I'm using?

There are many way, you check angular version Just pent the comand prompt(for windows) and type

1. ng version
2. ng v
3. ng -v

check the angular version using comand line

4. You can pakage.json file

check the angular version on pakage.json file

5.You can check in browser by presing F12 then goto elements tab

check the angular version on your browser

Full understanding of subversion about(x.x.x) please see angular documentation angularJS and angular 2+

What is the OAuth 2.0 Bearer Token exactly?

Please read the example in rfc6749 sec 7.1 first.

The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.

PoP means kind of multi-factor authentication to make access token more secure. ref

Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).

Maybe it's not the case, but I would say,

  • access token = payment methods
  • bearer token = cash
  • access token with PoP mechanism = credit card (signature or password will be verified, sometimes need to show your ID to match the name on the card)

BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

Oracle sqlldr TRAILING NULLCOLS required, but why?

Last column in your input file must have some data in it (be it space or char, but not null). I guess, 1st record contains null after last ',' which sqlldr won't recognize unless specifically asked to recognize nulls using TRAILING NULLCOLS option. Alternatively, if you don't want to use TRAILING NULLCOLS, you will have to take care of those NULLs before you pass the file to sqlldr. Hope this helps

Error in spring application context schema

I have recently had same issue with JPA-1.3

Nothing worked until I used explicit tools.xsd link

xsi:schemaLocation=" ...
    http://www.springframework.org/schema/tool
    http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
    ... ">

like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tool
        http://www.springframework.org/schema/tool/spring-tool-3.2.xsd
        ">

Remove "Using default security password" on Spring Boot

Using Spring Boot 2.0.4 I came across the same issue.

Excluding SecurityAutoConfiguration.class did destroy my application.

Now I'm using @SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})

Works fine with @EnableResourceServer and JWT :)

detect back button click in browser

Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:

http://www.irt.org/script/311.htm

Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.

How to add a single item to a Pandas Series

Here is another thought n for appending multiple items in one line without changing the name of series. However, this may be not as efficient as the other answer.

>>> df = pd.Series(np.random.random(5), name='random')
>>> df

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
Name: random, dtype: float64


>>> df.to_frame().T.assign(a=3, b=2, c=5).squeeze()

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
a    3.000000
b    2.000000
c    5.000000
Name: random, dtype: float64

How to programmatically close a JFrame

Posting what was in the question body as CW answer.

Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a WindowEvent.WINDOW_CLOSING at the application's event queue. Here's a synopsis of what the solution looks like

// closing down the window makes sense as a method, so here are
// the salient parts of what happens with the JFrame extending class ..

    public class FooWindow extends JFrame {
        public FooWindow() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(5, 5, 400, 300);  // yeah yeah, this is an example ;P
            setVisible(true);
        }
        public void pullThePlug() {
                WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
                Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
        }
    }

// Here's how that would be employed from elsewhere -

    // someplace the window gets created ..
    FooWindow fooey = new FooWindow();
    ...
    // and someplace else, you can close it thusly
    fooey.pullThePlug();

Mongoose: findOneAndUpdate doesn't return updated document

This is the updated code for findOneAndUpdate. It works.

db.collection.findOneAndUpdate(    
  { age: 17 },      
  { $set: { name: "Naomi" } },      
  {
     returnNewDocument: true
  }    
)

How to import an Oracle database from dmp file and log file?

All this peace of code put into *.bat file and run all at once:

My code for creating user in oracle. crate_drop_user.sql file

drop user "USER" cascade;
DROP TABLESPACE "USER";

CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE 
    AUTOEXTEND 
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    SEGMENT SPACE MANAGEMENT  AUTO
/ 

CREATE  TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE 
    'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    UNIFORM SIZE 1M    
/

CREATE USER "USER"  PROFILE "DEFAULT" 
    IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER" 
    TEMPORARY TABLESPACE "USER_TEMP" 
/    

alter user USER quota unlimited on "USER";

GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";

create file import.bat and put this lines in it:

SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log

Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.

Good luck, Ivan

How to get exact browser name and version?

Use get_browser() function.

It can give you output like this:

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    .... 

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

You do not need to keep the system images unless you want to use the emulator on your desktop. Along with it you can remove other unwanted stuff to clear disk space.

Adding as an answer to my own question as I've had to narrate this to people in my team more than a few times. Hence this answer as a reference to share with other curious ones.

In the last few weeks there were several colleagues who asked me how to safely get rid of the unwanted stuff to release disk space (most of them were beginners). I redirected them to this question but they came back to me for steps. So for android beginners here is a step by step guide to safely remove unwanted stuff.

Note

  • Do not blindly delete everything directly from disk that you "think" is not required occupying. I did that once and had to re-download.
  • Make sure you have a list of all active projects with the kind of emulators (if any) and API Levels and Build tools required for those to continue working/compiling properly.

First, be sure you are not going to use emulators and will always do you development on a physical device. In case you are going to need emulators, note down the API Levels and type of emulators you'll need. Do not remove those. For the rest follow the below steps:

Steps to safely clear up unwanted stuff from Android SDK folder on the disk

  1. Open the Stand Alone Android SDK Manager. To open do one of the following:
  • Click the SDK Manager button on toolbar in android studio or eclipse
  • In Android Studio, go to settings and search "Android SDK". Click Android SDK -> "Open Standalone SDK Manager"
  • In Eclipse, open the "Window" menu and select "Android SDK Manager"
  • Navigate to the location of the android-sdk directory on your computer and run "SDK Manager.exe"

.

  1. Uncheck all items ending with "System Image". Each API Level will have more than a few. In case you need some and have figured the list already leave them checked to avoid losing them and having to re-download.

.

  1. Optional (may help save a marginally more amount of disk space): To free up some more space, you can also entirely uncheck unrequired API levels. Be careful again to avoid re-downloading something you are actually using in other projects.

.

  1. In the end make sure you have at least the following (check image below) for the remaining API levels to be able to seamlessly work with your physical device.

In the end the clean android sdk installed components should look something like this in the SDK manager.

enter image description here

Multiple line code example in Javadoc comment

Using Java SE 1.6, it looks like all UPPERCASE PRE identifiers is the best way to do this in Javadoc:

/**
 * <PRE>
 * insert code as you would anywhere else
 * </PRE>
 */

is the simplest way to do this.

An Example from a javadoc I got from a java.awt.Event method:

/**
 * <PRE>
 *    int onmask = SHIFT_DOWN_MASK | BUTTON1_DOWN_MASK;
 *    int offmask = CTRL_DOWN_MASK;
 *    if ((event.getModifiersEx() & (onmask | offmask)) == onmask) {
 *        ...
 *    }
 * </PRE>
 */

This produces output that looks exactly like the regular code, with the regular code spacings and new lines intact.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)

This jar is used for XML binding which is applicable for .xlsx files.

Ripple effect on Android Lollipop CardView

You should add following to CardView:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

What is android:weightSum in android, and how does it work?

One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height property (which must exist in your xml file) set to 0dp. Seems like any other value would mess things up in some cases.

How to use Object.values with typescript?

Having my tslint rules configuration here always replacing the line Object["values"](myObject) with Object.values(myObject).

Two options if you have same issue:

(Object as any).values(myObject)

or

/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`

How to change the display name for LabelFor in razor in mvc3?

You can change the labels' text by adorning the property with the DisplayName attribute.

[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }

Or, you could write the raw HTML explicitly:

<label for="SomekingStatus" class="control-label">Someking Status</label>

SQL Server: Invalid Column Name

Following procedure helped me solve this issue but i don't know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

how to stop a for loop

In order to jump out of a loop, you need to use the break statement.

n=L[0][0]
m=len(A)
for i in range(m):
 for j in range(m):
   if L[i][j]!=n:
       break;

Here you have the official Python manual with the explanation about break and continue, and other flow control statements:

http://docs.python.org/tutorial/controlflow.html

EDITED: As a commenter pointed out, this does only end the inner loop. If you need to terminate both loops, there is no "easy" way (others have given you a few solutions). One possiblity would be to raise an exception:

def f(L, A):
    try:
        n=L[0][0]
        m=len(A)
        for i in range(m):
             for j in range(m):
                 if L[i][j]!=n:
                     raise RuntimeError( "Not equal" )
        return True
    except:
        return False

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

Try using cURL.

<?php

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($curl_handle);
curl_close($curl_handle);

?>

AES Encrypt and Decrypt

This is a pretty old post but XCode 10 added the CommonCrypto module so you don't need a module map. Also with Swift 5, no need for the annoying casts.

You could do something like:

func decrypt(_ data: Data, iv: Data, key: Data) throws -> String {

    var buffer = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
    var bufferLen: Int = 0

    let status = CCCrypt(
        CCOperation(kCCDecrypt),
        CCAlgorithm(kCCAlgorithmAES128),
        CCOptions(kCCOptionPKCS7Padding),
        [UInt8](key),
        kCCBlockSizeAES128,
        [UInt8](iv),
        [UInt8](data),
        data.count,
        &buffer,
        buffer.count,
        &bufferLen
    )

    guard status == kCCSuccess,
        let str = String(data: Data(bytes: buffer, count: bufferLen),
                         encoding: .utf8) else {
                            throw NSError(domain: "AES", code: -1, userInfo: nil)
    }

    return str
}

MySQL select where column is not empty

SELECT phone, phone2 
FROM jewishyellow.users 
WHERE phone like '813%' and (phone2 <> "");

May need some tweakage depending on what your default value is. If you allowed Null fill, then you can do "Not NULL" instead, which is obviously better.

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

It really depends on what you mean by "learn". You could probably spend a week and get a couple of pages up on the web that had some minimal level of interactivity to save information entered by the user in some database, and then have some other pages for querying and displaying the information. You could then spend the next 10 years of your life learning all the intricacies of the .Net framework, SQL, and mastering using the IDE.

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

Convert string (without any separator) to list

A python string is a list of characters. You can iterate over it right now!

justdigits = ""
for char in string:
    if char.isdigit():
        justdigits += str(char)

Presenting modal in iOS 13 fullscreen

Initially, the default value is fullscreen for modalPresentationStyle, but in iOS 13 its changes to the UIModalPresentationStyle.automatic.

If you want to make the full-screen view controller you have to change the modalPresentationStyle to fullScreen.

Refer UIModalPresentationStyle apple documentation for more details and refer apple human interface guidelines for where should use which modality.

Project vs Repository in GitHub

GitHub recently introduced a new feature called Projects. This provides a visual board that is typical of many Project Management tools:

Project

A Repository as documented on GitHub:

A repository is the most basic element of GitHub. They're easiest to imagine as a project's folder. A repository contains all of the project files (including documentation), and stores each file's revision history. Repositories can have multiple collaborators and can be either public or private.

A Project as documented on GitHub:

Project boards on GitHub help you organize and prioritize your work. You can create project boards for specific feature work, comprehensive roadmaps, or even release checklists. With project boards, you have the flexibility to create customized workflows that suit your needs.

Part of the confusion is that the new feature, Projects, conflicts with the overloaded usage of the term project in the documentation above.

How do I convert a decimal to an int in C#?

int i = (int)d;

will give you the number rounded down.

If you want to round to the nearest even number (i.e. >.5 will round up) you can use

int i = (int)Math.Round(d, MidpointRounding.ToEven);

In general you can cast between all the numerical types in C#. If there is no information that will be lost during the cast you can do it implicitly:

int i = 10;
decimal d = i;

though you can still do it explicitly if you wish:

int i = 10;
decimal d = (decimal)i;

However, if you are going to be losing information through the cast you must do it explicitly (to show you are aware you may be losing information):

decimal d = 10.5M;
int i = (int)d;

Here you are losing the ".5". This may be fine, but you must be explicit about it and make an explicit cast to show you know you may be losing the information.

Determine version of Entity Framework I am using?

In Solution Explorer Under Project Click on Dependencies->NuGet->Microsoft.NetCore.All-> Here list of all Microsoft .NetCore pakcages will appear. Search for Microsoft.EntityFrameworkCore(2.0.3) in bracket version can be seen Like this

After finding package

Alternative to deprecated getCellType

    FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));

    //create workbook instance
    XSSFWorkbook wb = new XSSFWorkbook(fis);

    //create a sheet object to retrieve the sheet
    XSSFSheet sheet = wb.getSheetAt(0);

    //to evaluate cell type
    FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();

    for(Row row : sheet)
    {
        for(Cell cell : row)
        {
            switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
            {
            case NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                break;
            case STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                break;
            default:
                break;

            }
        }
        System.out.println();
    }

This code will work fine. Use getCellTypeEnum() and to compare use just NUMERIC or STRING.

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

How to customize an end time for a YouTube video?

I just found out that the following works:

https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]

Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).

What's the difference between IFrame and Frame?

Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.

Convert Data URI to File then append to FormData

My preferred way is canvas.toBlob()

But anyhow here is yet another way to convert base64 to a blob using fetch ^^,

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="_x000D_
_x000D_
fetch(url)_x000D_
.then(res => res.blob())_x000D_
.then(blob => {_x000D_
  var fd = new FormData()_x000D_
  fd.append('image', blob, 'filename')_x000D_
  _x000D_
  console.log(blob)_x000D_
_x000D_
  // Upload_x000D_
  // fetch('upload', {method: 'POST', body: fd})_x000D_
})
_x000D_
_x000D_
_x000D_

LINQ: Distinct values

For any one still looking; here's another way of implementing a custom lambda comparer.

public class LambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _expression;

        public LambdaComparer(Func<T, T, bool> lambda)
        {
            _expression = lambda;
        }

        public bool Equals(T x, T y)
        {
            return _expression(x, y);
        }

        public int GetHashCode(T obj)
        {
            /*
             If you just return 0 for the hash the Equals comparer will kick in. 
             The underlying evaluation checks the hash and then short circuits the evaluation if it is false.
             Otherwise, it checks the Equals. If you force the hash to be true (by assuming 0 for both objects), 
             you will always fall through to the Equals check which is what we are always going for.
            */
            return 0;
        }
    }

you can then create an extension for the linq Distinct that can take in lambda's

   public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list,  Func<T, T, bool> lambda)
        {
            return list.Distinct(new LambdaComparer<T>(lambda));
        }  

Usage:

var availableItems = list.Distinct((p, p1) => p.Id== p1.Id);

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

Find if listA contains any elements not in listB

listA.Any(_ => listB.Contains(_))

:)

Checking if a SQL Server login already exists

what are you exactly want check for login or user ? a login is created on server level and a user is created at database level so a login is unique in server

also a user is created against a login, a user without login is an orphaned user and is not useful as u cant carry out sql server login without a login

maybe u need this

check for login

select 'X' from master.dbo.syslogins where loginname=<username>

the above query return 'X' if login exists else return null

then create a login

CREATE LOGIN <username> with PASSWORD=<password>

this creates a login in sql server .but it accepts only strong passwords

create a user in each database you want to for login as

CREATE USER <username> for login <username>

assign execute rights to user

 GRANT EXECUTE TO <username>

YOU MUST HAVE SYSADMIN permissions or say 'sa' for short

you can write a sql procedure for that on a database

create proc createuser
(
@username varchar(50),
@password varchar(50)
)
as
begin
if not exists(select 'X' from master.dbo.syslogins where loginname=@username)
begin
 if not exists(select 'X' from sysusers where name=@username)
 begin
exec('CREATE LOGIN '+@username+' WITH PASSWORD='''+@password+'''')
exec('CREATE USER '+@username+' FOR LOGIN '+@username)
exec('GRANT EXECUTE TO '+@username)
end
end
end

How can I check if string contains characters & whitespace, not just whitespace?

if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

Check if a varchar is a number (TSQL)

you can check like this

declare @vchar varchar(50)
set @vchar ='34343';
select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end

How to download videos from youtube on java?

Regarding the format (mp4 or flv) decide which URL you want to use. Then use this tutorial to download the video and save it into a local directory.

AngularJS ng-if with multiple conditions

HTML code

<div ng-app>
<div ng-controller='ctrl'>
    <div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
    <div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
    <div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
    <div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
    <div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
    <div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
    <div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
    <div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>

JavaScript Code

function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}


$scope.whatClassIsIt= function(someValue){
     if(someValue=="first")
            return "ClassA"
     else if(someValue=="second")
         return "ClassB";
    else
         return "ClassC";
}
}

Equivalent of shell 'cd' command to change the working directory?

If You would like to perform something like "cd.." option, just type:

os.chdir("..")

it is the same as in Windows cmd: cd.. Of course import os is neccessary (e.g type it as 1st line of your code)

Executing an EXE file using a PowerShell script

In the Powershell, cd to the .exe file location. For example:

cd C:\Users\Administrators\Downloads

PS C:\Users\Administrators\Downloads> & '.\aaa.exe'

The installer pops up and follow the instruction on the screen.

How do I compile a .c file on my Mac?

You will need to install the Apple Developer Tools. Once you have done that, the easiest thing is to either use the Xcode IDE or use gcc, or nowadays better cc (the clang LLVM compiler), from the command line.

According to Apple's site, the latest version of Xcode (3.2.1) only runs on Snow Leopard (10.6) so if you have an earlier version of OS X you will need to use an older version of Xcode. Your Mac should have come with a Developer Tools DVD which will contain a version that should run on your system. Also, the Apple Developer Tools site still has older versions available for download. Xcode 3.1.4 should run on Leopard (10.5).

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

Refer this link : https://github.com/TeehanLax/UITableViewCell-Swipe-for-Options

And customize your uitableviewcell with multiple button.

 UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds) + kCatchWidth, CGRectGetHeight(self.bounds));
scrollView.delegate = self;
scrollView.showsHorizontalScrollIndicator = NO;

[self.contentView addSubview:scrollView];
self.scrollView = scrollView;

UIView *scrollViewButtonView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) - kCatchWidth, 0, kCatchWidth, CGRectGetHeight(self.bounds))];
self.scrollViewButtonView = scrollViewButtonView;
[self.scrollView addSubview:scrollViewButtonView];

// Set up our two buttons
UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
moreButton.backgroundColor = [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0f];
moreButton.frame = CGRectMake(0, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[moreButton setTitle:@"More" forState:UIControlStateNormal];
[moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[moreButton addTarget:self action:@selector(userPressedMoreButton:) forControlEvents:UIControlEventTouchUpInside];

[self.scrollViewButtonView addSubview:moreButton];

UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
shareButton.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:1.0f];
shareButton.frame = CGRectMake(kCatchWidth / 3.0f, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[shareButton setTitle:@"Share" forState:UIControlStateNormal];
[shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[shareButton addTarget:self action:@selector(userPressedMoreButton:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewButtonView addSubview:shareButton];

UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.backgroundColor = [UIColor colorWithRed:1.0f green:0.231f blue:0.188f alpha:1.0f];
deleteButton.frame = CGRectMake(kCatchWidth / 3.0f+kCatchWidth / 3.0f, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[deleteButton setTitle:@"Delete" forState:UIControlStateNormal];
[deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[deleteButton addTarget:self action:@selector(userPressedDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewButtonView addSubview:deleteButton];

UIView *scrollViewContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
scrollViewContentView.backgroundColor = [UIColor whiteColor];
[self.scrollView addSubview:scrollViewContentView];
self.scrollViewContentView = scrollViewContentView;

UILabel *scrollViewLabel = [[UILabel alloc] initWithFrame:CGRectInset(self.scrollViewContentView.bounds, 10, 0)];
self.scrollViewLabel = scrollViewLabel;
[self.scrollViewContentView addSubview:scrollViewLabel];
  • I have implemented this code with my app got such result. You can add number of button in swipe cell.

    Here is implemented screen shots

    enter image description hereAfter swipe the cell 3 buttons appears "More","Share","Delete".

Better techniques for trimming leading zeros in SQL Server?

My version of this is an adaptation of Arvo's work, with a little more added on to ensure two other cases.

1) If we have all 0s, we should return the digit 0.

2) If we have a blank, we should still return a blank character.

CASE 
    WHEN PATINDEX('%[^0]%', str_col + '.') > LEN(str_col) THEN RIGHT(str_col, 1) 
    ELSE SUBSTRING(str_col, PATINDEX('%[^0]%', str_col + '.'), LEN(str_col))
 END

Set EditText cursor color

The only valid answer should be to change the theme of the activity: <item name="colorAccent">#000000</item> You should not use the android:textCursorDrawable to @null because this only concerns the cursor itself but not the pin below the cursor if you want to drag that cursor. The theming solution is the most serious one.

Cannot use object of type stdClass as array?

Use the second parameter of json_decode to make it return an array:

$result = json_decode($data, true);

Java JDBC connection status

Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.

If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.

That said, a lot of connection pools validate a connection by doing something like SELECT 1 before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.

PHP check if date between two dates

You cannot compare date-strings. It is good habit to use PHP's DateTime object instead:

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

if (
  $paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() && 
  $paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
  echo "is between";
}else{
   echo "NO GO!";  
}

Regular expression - starting and ending with a letter, accepting only letters, numbers and _

Here's a solution using a negative lookahead (not supported in all regex engines):

^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$

Test that it works as expected:

import re
tests = [
   ('a', True),
   ('_', False),
   ('zz', True),
   ('a0', True),
   ('A_', False),
   ('a0_b', True),
   ('a__b', False),
   ('a_1_c', True),
]

regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
   is_match = re.match(regex, test[0]) is not None
   if is_match != test[1]:
       print "fail: "  + test[0]

ORA-28040: No matching authentication protocol exception

Adding

SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

is the perfect solution sql.ora directory ..\product\12.1.0\dbhome_1\NETWORK\ADMIN

JavaScript/regex: Remove text between parentheses

"Hello, this is Mike (example)".replace(/ *\([^)]*\) */g, "");

Result:

"Hello, this is Mike"

What's the difference between .bashrc, .bash_profile, and .environment?

I found information about .bashrc and .bash_profile here to sum it up:

.bash_profile is executed when you login. Stuff you put in there might be your PATH and other important environment variables.

.bashrc is used for non login shells. I'm not sure what that means. I know that RedHat executes it everytime you start another shell (su to this user or simply calling bash again) You might want to put aliases in there but again I am not sure what that means. I simply ignore it myself.

.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)

There is also .bash_logout wich executes at, yeah good guess...logout. You might want to stop deamons or even make a little housekeeping . You can also add "clear" there if you want to clear the screen when you log out.

Also there is a complete follow up on each of the configurations files here

These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.

Is there a built-in function to print all the current properties and values of an object?

This prints out all the object contents recursively in json or yaml indented format:

import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml

serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)

PHP multidimensional array search by value

I had to use un function which finds every elements in an array. So I modified the function done by Jakub Trunecek as follow:

function search_in_array_r($needle, $array) {
    $found = array();
    foreach ($array as $key => $val) {
        if ($val[1] == $needle) {
            array_push($found, $val[1]);
        }
    }
    if (count($found) != 0)
        return $found;
    else
        return null;
}

Get value from JToken that may not exist (best practices)

Here is how you can check if the token exists:

if (jobject["Result"].SelectToken("Items") != null) { ... }

It checks if "Items" exists in "Result".

This is a NOT working example that causes exception:

if (jobject["Result"]["Items"] != null) { ... }

Passing arguments to "make run"

Here's another solution that could help with some of these use cases:

test-%:
    $(PYTHON) run-tests.py $@

In other words, pick some prefix (test- in this case), and then pass the target name directly to the program/runner. I guess this is mostly useful if there is some runner script involved that can unwrap the target name into something useful for the underlying program.

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

counting number of directories in a specific directory

Using zsh:

a=(*(/N)); echo ${#a}

The N is a nullglob, / makes it match directories, # counts. It will neatly cope with spaces in directory names as well as returning 0 if there are no directories.

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

How do you create a daemon in Python?

Though you may prefer the pure Python solution provided by the python-daemon module, there is a daemon(3) function in libc -- at least, on BSD and Linux -- which will do the right thing.

Calling it from python is easy:

import ctypes

ctypes.CDLL(None).daemon(0, 0) # Read the man-page for the arguments' meanings

The only remaining thing to do is creation (and locking) of the PID-file. But that you can handle yourself...

How to convert a Kotlin source file to a Java source file

you can go to Tools > Kotlin > Show kotlin bytecode

enter image description here

enter image description here

enter image description here

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

Documentation for using JavaScript code inside a PDF file

I'm pretty sure it's an Adobe standard, bearing in mind the whole PDF standard is theirs to begin with; despite being open now.

My guess would be no for all PDF viewers supporting it, as some definitely will not have a JS engine. I doubt you can rely on full support outside the most recent versions of Acrobat (Reader). So I guess it depends on how you imagine it being used, if mainly via a browser display, then the majority of the market is catered for by Acrobat (Reader) and Chrome's built-in viewer - dare say there is documentation on whether Chrome's PDF viewer supports JS fully.

How to compare two dates in Objective-C

Here's the Swift variant on Pascal's answer:

extension NSDate {

    func isLaterThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedAscending)
    }

    func isEarlierThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isLaterThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isEarlierThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedAscending)
    }
}

Which can be used as:

self.expireDate.isEarlierThanOrEqualTo(NSDate())

Are querystring parameters secure in HTTPS (HTTP + SSL)?

remember, SSL/TLS operates at the Transport Layer, so all the crypto goo happens under the application-layer HTTP stuff.

http://en.wikipedia.org/wiki/File:IP_stack_connections.svg

that's the long way of saying, "Yes!"

'this' vs $scope in AngularJS controllers

"How does this and $scope work in AngularJS controllers?"

Short answer:

  • this
    • When the controller constructor function is called, this is the controller.
    • When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on. So, inside the function, this and $scope may not be the same.
  • $scope
    • Every controller has an associated $scope object.
    • A controller (constructor) function is responsible for setting model properties and functions/behaviour on its associated $scope.
    • Only methods defined on this $scope object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click, filters, etc.

Long answer:

A controller function is a JavaScript constructor function. When the constructor function executes (e.g., when a view loads), this (i.e., the "function context") is set to the controller object. So in the "tabs" controller constructor function, when the addPane function is created

this.addPane = function(pane) { ... }

it is created on the controller object, not on $scope. Views cannot see the addPane function -- they only have access to functions defined on $scope. In other words, in the HTML, this won't work:

<a ng-click="addPane(newPane)">won't work</a>

After the "tabs" controller constructor function executes, we have the following:

after tabs controller constructor function

The dashed black line indicates prototypal inheritance -- an isolate scope prototypically inherits from Scope. (It does not prototypically inherit from the scope in effect where the directive was encountered in the HTML.)

Now, the pane directive's link function wants to communicate with the tabs directive (which really means it needs to affect the tabs isolate $scope in some way). Events could be used, but another mechanism is to have the pane directive require the tabs controller. (There appears to be no mechanism for the pane directive to require the tabs $scope.)

So, this begs the question: if we only have access to the tabs controller, how do we get access to the tabs isolate $scope (which is what we really want)?

Well, the red dotted line is the answer. The addPane() function's "scope" (I'm referring to JavaScript's function scope/closures here) gives the function access to the tabs isolate $scope. I.e., addPane() has access to the "tabs IsolateScope" in the diagram above because of a closure that was created when addPane() was defined. (If we instead defined addPane() on the tabs $scope object, the pane directive would not have access to this function, and hence it would have no way to communicate with the tabs $scope.)

To answer the other part of your question: how does $scope work in controllers?:

Within functions defined on $scope, this is set to "the $scope in effect where/when the function was called". Suppose we have the following HTML:

<div ng-controller="ParentCtrl">
   <a ng-click="logThisAndScope()">log "this" and $scope</a> - parent scope
   <div ng-controller="ChildCtrl">
      <a ng-click="logThisAndScope()">log "this" and $scope</a> - child scope
   </div>
</div>

And the ParentCtrl (Solely) has

$scope.logThisAndScope = function() {
    console.log(this, $scope)
}

Clicking the first link will show that this and $scope are the same, since "the scope in effect when the function was called" is the scope associated with the ParentCtrl.

Clicking the second link will reveal this and $scope are not the same, since "the scope in effect when the function was called" is the scope associated with the ChildCtrl. So here, this is set to ChildCtrl's $scope. Inside the method, $scope is still the ParentCtrl's $scope.

Fiddle

I try to not use this inside of a function defined on $scope, as it becomes confusing which $scope is being affected, especially considering that ng-repeat, ng-include, ng-switch, and directives can all create their own child scopes.

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

Setting the Textbox read only property to true using JavaScript

You can try

document.getElementById("textboxid").readOnly = true;

How to run a Python script in the background even after I logout SSH?

You might consider turning your python script into a proper python daemon, as described here.

python-daemon is a good tool that can be used to run python scripts as a background daemon process rather than a forever running script. You will need to modify existing code a bit but its plain and simple.

If you are facing problems with python-daemon, there is another utility supervisor that will do the same for you, but in this case you wont have to write any code (or modify existing) as this is a out of the box solution for daemonizing processes.

Angular 2 / 4 / 5 not working in IE11

I ran into this issue today. I found an solution on GitHub that does not require going to a later version of the beta.

Add the following script to your html:

<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>

This resolved the problem for me. For more details, you can follow the github issue here: https://github.com/angular/angular/issues/7144

ORA-01036: illegal variable name/number when running query through C#

You cannot pass user/table name to pl/sql with a parameter. You can create a procedure and build sql and then execute immediately to achieve that.

How to loop through file names returned by find?

If you can assume the file names don't contain newlines, you can read the output of find into a Bash array using the following command:

readarray -t x < <(find . -name '*.txt')

Note:

  • -t causes readarray to strip newlines.
  • It won't work if readarray is in a pipe, hence the process substitution.
  • readarray is available since Bash 4.

Bash 4.4 and up also supports the -d parameter for specifying the delimiter. Using the null character, instead of newline, to delimit the file names works also in the rare case that the file names contain newlines:

readarray -d '' x < <(find . -name '*.txt' -print0)

readarray can also be invoked as mapfile with the same options.

Reference: https://mywiki.wooledge.org/BashFAQ/005#Loading_lines_from_a_file_or_stream

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

There are still no native methods that perform the requested task.

Here is the code that I am using. It mimics the behaviour of String.prototype.indexOf and String.prototype.lastIndexOf methods but they also accept a RegExp as the search argument in addition to a string representing the value to search for.

Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of JSDOC comments. However, once minified, the code is only 2.27k and once gzipped for transmission it is only 1023 bytes.

The 2 methods that this adds to String.prototype (using Object.defineProperty where available) are:

  1. searchOf
  2. searchLastOf

It passes all the tests that the OP posted and additionally I have tested the routines quite thoroughly in my daily usage, and have attempted to be sure that they work across multiple environments, but feedback/issues are always welcome.

_x000D_
_x000D_
/*jslint maxlen:80, browser:true */_x000D_
_x000D_
/*_x000D_
 * Properties used by searchOf and searchLastOf implementation._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    MAX_SAFE_INTEGER, abs, add, apply, call, configurable, defineProperty,_x000D_
    enumerable, exec, floor, global, hasOwnProperty, ignoreCase, index,_x000D_
    lastIndex, lastIndexOf, length, max, min, multiline, pow, prototype,_x000D_
    remove, replace, searchLastOf, searchOf, source, toString, value, writable_x000D_
*/_x000D_
_x000D_
/*_x000D_
 * Properties used in the testing of searchOf and searchLastOf implimentation._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    appendChild, createTextNode, getElementById, indexOf, lastIndexOf, length,_x000D_
    searchLastOf, searchOf, unshift_x000D_
*/_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1,_x000D_
        getNativeFlags = new RegExp('\\/([a-z]*)$', 'i'),_x000D_
        clipDups = new RegExp('([\\s\\S])(?=[\\s\\S]*\\1)', 'g'),_x000D_
        pToString = Object.prototype.toString,_x000D_
        pHasOwn = Object.prototype.hasOwnProperty,_x000D_
        stringTagRegExp;_x000D_
_x000D_
    /**_x000D_
     * Defines a new property directly on an object, or modifies an existing_x000D_
     * property on an object, and returns the object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {Object} object_x000D_
     * @param {string} property_x000D_
     * @param {Object} descriptor_x000D_
     * @returns {Object}_x000D_
     * @see https://goo.gl/CZnEqg_x000D_
     */_x000D_
    function $defineProperty(object, property, descriptor) {_x000D_
        if (Object.defineProperty) {_x000D_
            Object.defineProperty(object, property, descriptor);_x000D_
        } else {_x000D_
            object[property] = descriptor.value;_x000D_
        }_x000D_
_x000D_
        return object;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operands are strictly equal with no type conversion._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} a_x000D_
     * @param {*} b_x000D_
     * @returns {boolean}_x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4_x000D_
     */_x000D_
    function $strictEqual(a, b) {_x000D_
        return a === b;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is undefined._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     */_x000D_
    function $isUndefined(inputArg) {_x000D_
        return $strictEqual(typeof inputArg, 'undefined');_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Provides a string representation of the supplied object in the form_x000D_
     * "[object type]", where type is the object type._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object for which a class string represntation_x000D_
     *                     is required._x000D_
     * @returns {string} A string value of the form "[object type]"._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2_x000D_
     */_x000D_
    function $toStringTag(inputArg) {_x000D_
        var val;_x000D_
        if (inputArg === null) {_x000D_
            val = '[object Null]';_x000D_
        } else if ($isUndefined(inputArg)) {_x000D_
            val = '[object Undefined]';_x000D_
        } else {_x000D_
            val = pToString.call(inputArg);_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The string tag representation of a RegExp object._x000D_
     *_x000D_
     * @private_x000D_
     * @type {string}_x000D_
     */_x000D_
    stringTagRegExp = $toStringTag(getNativeFlags);_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is a RegExp._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     */_x000D_
    function $isRegExp(inputArg) {_x000D_
        return $toStringTag(inputArg) === stringTagRegExp &&_x000D_
                pHasOwn.call(inputArg, 'ignoreCase') &&_x000D_
                typeof inputArg.ignoreCase === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'global') &&_x000D_
                typeof inputArg.global === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'multiline') &&_x000D_
                typeof inputArg.multiline === 'boolean' &&_x000D_
                pHasOwn.call(inputArg, 'source') &&_x000D_
                typeof inputArg.source === 'string';_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation throws an error if its argument is a value that_x000D_
     * cannot be converted to an Object, otherwise returns the argument._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be tested._x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @returns {*} The inputArg if coercible._x000D_
     * @see https://goo.gl/5GcmVq_x000D_
     */_x000D_
    function $requireObjectCoercible(inputArg) {_x000D_
        var errStr;_x000D_
_x000D_
        if (inputArg === null || $isUndefined(inputArg)) {_x000D_
            errStr = 'Cannot convert argument to object: ' + inputArg;_x000D_
            throw new TypeError(errStr);_x000D_
        }_x000D_
_x000D_
        return inputArg;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation converts its argument to a value of type string_x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {string}_x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring_x000D_
     */_x000D_
    function $toString(inputArg) {_x000D_
        var type,_x000D_
            val;_x000D_
_x000D_
        if (inputArg === null) {_x000D_
            val = 'null';_x000D_
        } else {_x000D_
            type = typeof inputArg;_x000D_
            if (type === 'string') {_x000D_
                val = inputArg;_x000D_
            } else if (type === 'undefined') {_x000D_
                val = type;_x000D_
            } else {_x000D_
                if (type === 'symbol') {_x000D_
                    throw new TypeError('Cannot convert symbol to string');_x000D_
                }_x000D_
_x000D_
                val = String(inputArg);_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns a string only if the arguments is coercible otherwise throws an_x000D_
     * error._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @returns {string}_x000D_
     */_x000D_
    function $onlyCoercibleToString(inputArg) {_x000D_
        return $toString($requireObjectCoercible(inputArg));_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The function evaluates the passed value and converts it to an integer._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to an integer._x000D_
     * @returns {number} If the target value is NaN, null or undefined, 0 is_x000D_
     *                   returned. If the target value is false, 0 is returned_x000D_
     *                   and if true, 1 is returned._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4_x000D_
     */_x000D_
    function $toInteger(inputArg) {_x000D_
        var number = +inputArg,_x000D_
            val = 0;_x000D_
_x000D_
        if ($strictEqual(number, number)) {_x000D_
            if (!number || number === Infinity || number === -Infinity) {_x000D_
                val = number;_x000D_
            } else {_x000D_
                val = (number > 0 || -1) * Math.floor(Math.abs(number));_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Copies a regex object. Allows adding and removing native flags while_x000D_
     * copying the regex._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {RegExp} regex Regex to copy._x000D_
     * @param {Object} [options] Allows specifying native flags to add or_x000D_
     *                           remove while copying the regex._x000D_
     * @returns {RegExp} Copy of the provided regex, possibly with modified_x000D_
     *                   flags._x000D_
     */_x000D_
    function $copyRegExp(regex, options) {_x000D_
        var flags,_x000D_
            opts,_x000D_
            rx;_x000D_
_x000D_
        if (options !== null && typeof options === 'object') {_x000D_
            opts = options;_x000D_
        } else {_x000D_
            opts = {};_x000D_
        }_x000D_
_x000D_
        // Get native flags in use_x000D_
        flags = getNativeFlags.exec($toString(regex))[1];_x000D_
        flags = $onlyCoercibleToString(flags);_x000D_
        if (opts.add) {_x000D_
            flags += opts.add;_x000D_
            flags = flags.replace(clipDups, '');_x000D_
        }_x000D_
_x000D_
        if (opts.remove) {_x000D_
            // Would need to escape `options.remove` if this was public_x000D_
            rx = new RegExp('[' + opts.remove + ']+', 'g');_x000D_
            flags = flags.replace(rx, '');_x000D_
        }_x000D_
_x000D_
        return new RegExp(regex.source, flags);_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation ToLength converts its argument to an integer_x000D_
     * suitable for use as the length of an array-like object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to a length._x000D_
     * @returns {number} If len <= +0 then +0 else if len is +INFINITY then_x000D_
     *                   2^53-1 else min(len, 2^53-1)._x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength_x000D_
     */_x000D_
    function $toLength(inputArg) {_x000D_
        return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Copies a regex object so that it is suitable for use with searchOf and_x000D_
     * searchLastOf methods._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {RegExp} regex Regex to copy._x000D_
     * @returns {RegExp}_x000D_
     */_x000D_
    function $toSearchRegExp(regex) {_x000D_
        return $copyRegExp(regex, {_x000D_
            add: 'g',_x000D_
            remove: 'y'_x000D_
        });_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is a member of one of the types_x000D_
     * Undefined, Null, Boolean, Number, Symbol, or String._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @returns {boolean}_x000D_
     * @see https://goo.gl/W68ywJ_x000D_
     * @see https://goo.gl/ev7881_x000D_
     */_x000D_
    function $isPrimitive(inputArg) {_x000D_
        var type = typeof inputArg;_x000D_
_x000D_
        return type === 'undefined' ||_x000D_
                inputArg === null ||_x000D_
                type === 'boolean' ||_x000D_
                type === 'string' ||_x000D_
                type === 'number' ||_x000D_
                type === 'symbol';_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation converts its argument to a value of type Object_x000D_
     * but fixes some environment bugs._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The argument to be converted to an object._x000D_
     * @throws {TypeError} If inputArg is not coercible to an object._x000D_
     * @returns {Object} Value of inputArg as type Object._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.9_x000D_
     */_x000D_
    function $toObject(inputArg) {_x000D_
        var object;_x000D_
_x000D_
        if ($isPrimitive($requireObjectCoercible(inputArg))) {_x000D_
            object = Object(inputArg);_x000D_
        } else {_x000D_
            object = inputArg;_x000D_
        }_x000D_
_x000D_
        return object;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Converts a single argument that is an array-like object or list (eg._x000D_
     * arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap_x000D_
     * (used by attributes property)) into a new Array() and returns it._x000D_
     * This is a partial implementation of the ES6 Array.from_x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {Object} arrayLike_x000D_
     * @returns {Array}_x000D_
     */_x000D_
    function $toArray(arrayLike) {_x000D_
        var object = $toObject(arrayLike),_x000D_
            length = $toLength(object.length),_x000D_
            array = [],_x000D_
            index = 0;_x000D_
_x000D_
        array.length = length;_x000D_
        while (index < length) {_x000D_
            array[index] = object[index];_x000D_
            index += 1;_x000D_
        }_x000D_
_x000D_
        return array;_x000D_
    }_x000D_
_x000D_
    if (!String.prototype.searchOf) {_x000D_
        /**_x000D_
         * This method returns the index within the calling String object of_x000D_
         * the first occurrence of the specified value, starting the search at_x000D_
         * fromIndex. Returns -1 if the value is not found._x000D_
         *_x000D_
         * @function_x000D_
         * @this {string}_x000D_
         * @param {RegExp|string} regex A regular expression object or a String._x000D_
         *                              Anything else is implicitly converted to_x000D_
         *                              a String._x000D_
         * @param {Number} [fromIndex] The location within the calling string_x000D_
         *                             to start the search from. It can be any_x000D_
         *                             integer. The default value is 0. If_x000D_
         *                             fromIndex < 0 the entire string is_x000D_
         *                             searched (same as passing 0). If_x000D_
         *                             fromIndex >= str.length, the method will_x000D_
         *                             return -1 unless searchValue is an empty_x000D_
         *                             string in which case str.length is_x000D_
         *                             returned._x000D_
         * @returns {Number} If successful, returns the index of the first_x000D_
         *                   match of the regular expression inside the_x000D_
         *                   string. Otherwise, it returns -1._x000D_
         */_x000D_
        $defineProperty(String.prototype, 'searchOf', {_x000D_
            enumerable: false,_x000D_
            configurable: true,_x000D_
            writable: true,_x000D_
            value: function (regex) {_x000D_
                var str = $onlyCoercibleToString(this),_x000D_
                    args = $toArray(arguments),_x000D_
                    result = -1,_x000D_
                    fromIndex,_x000D_
                    match,_x000D_
                    rx;_x000D_
_x000D_
                if (!$isRegExp(regex)) {_x000D_
                    return String.prototype.indexOf.apply(str, args);_x000D_
                }_x000D_
_x000D_
                if ($toLength(args.length) > 1) {_x000D_
                    fromIndex = +args[1];_x000D_
                    if (fromIndex < 0) {_x000D_
                        fromIndex = 0;_x000D_
                    }_x000D_
                } else {_x000D_
                    fromIndex = 0;_x000D_
                }_x000D_
_x000D_
                if (fromIndex >= $toLength(str.length)) {_x000D_
                    return result;_x000D_
                }_x000D_
_x000D_
                rx = $toSearchRegExp(regex);_x000D_
                rx.lastIndex = fromIndex;_x000D_
                match = rx.exec(str);_x000D_
                if (match) {_x000D_
                    result = +match.index;_x000D_
                }_x000D_
_x000D_
                return result;_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
_x000D_
    if (!String.prototype.searchLastOf) {_x000D_
        /**_x000D_
         * This method returns the index within the calling String object of_x000D_
         * the last occurrence of the specified value, or -1 if not found._x000D_
         * The calling string is searched backward, starting at fromIndex._x000D_
         *_x000D_
         * @function_x000D_
         * @this {string}_x000D_
         * @param {RegExp|string} regex A regular expression object or a String._x000D_
         *                              Anything else is implicitly converted to_x000D_
         *                              a String._x000D_
         * @param {Number} [fromIndex] Optional. The location within the_x000D_
         *                             calling string to start the search at,_x000D_
         *                             indexed from left to right. It can be_x000D_
         *                             any integer. The default value is_x000D_
         *                             str.length. If it is negative, it is_x000D_
         *                             treated as 0. If fromIndex > str.length,_x000D_
         *                             fromIndex is treated as str.length._x000D_
         * @returns {Number} If successful, returns the index of the first_x000D_
         *                   match of the regular expression inside the_x000D_
         *                   string. Otherwise, it returns -1._x000D_
         */_x000D_
        $defineProperty(String.prototype, 'searchLastOf', {_x000D_
            enumerable: false,_x000D_
            configurable: true,_x000D_
            writable: true,_x000D_
            value: function (regex) {_x000D_
                var str = $onlyCoercibleToString(this),_x000D_
                    args = $toArray(arguments),_x000D_
                    result = -1,_x000D_
                    fromIndex,_x000D_
                    length,_x000D_
                    match,_x000D_
                    pos,_x000D_
                    rx;_x000D_
_x000D_
                if (!$isRegExp(regex)) {_x000D_
                    return String.prototype.lastIndexOf.apply(str, args);_x000D_
                }_x000D_
_x000D_
                length = $toLength(str.length);_x000D_
                if (!$strictEqual(args[1], args[1])) {_x000D_
                    fromIndex = length;_x000D_
                } else {_x000D_
                    if ($toLength(args.length) > 1) {_x000D_
                        fromIndex = $toInteger(args[1]);_x000D_
                    } else {_x000D_
                        fromIndex = length - 1;_x000D_
                    }_x000D_
                }_x000D_
_x000D_
                if (fromIndex >= 0) {_x000D_
                    fromIndex = Math.min(fromIndex, length - 1);_x000D_
                } else {_x000D_
                    fromIndex = length - Math.abs(fromIndex);_x000D_
                }_x000D_
_x000D_
                pos = 0;_x000D_
                rx = $toSearchRegExp(regex);_x000D_
                while (pos <= fromIndex) {_x000D_
                    rx.lastIndex = pos;_x000D_
                    match = rx.exec(str);_x000D_
                    if (!match) {_x000D_
                        break;_x000D_
                    }_x000D_
_x000D_
                    pos = +match.index;_x000D_
                    if (pos <= fromIndex) {_x000D_
                        result = pos;_x000D_
                    }_x000D_
_x000D_
                    pos += 1;_x000D_
                }_x000D_
_x000D_
                return result;_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
}());_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    /*_x000D_
     * testing as follow to make sure that at least for one character regexp,_x000D_
     * the result is the same as if we used indexOf_x000D_
     */_x000D_
_x000D_
    var pre = document.getElementById('out');_x000D_
_x000D_
    function log(result) {_x000D_
        pre.appendChild(document.createTextNode(result + '\n'));_x000D_
    }_x000D_
_x000D_
    function test(str) {_x000D_
        var i = str.length + 2,_x000D_
            r,_x000D_
            a,_x000D_
            b;_x000D_
_x000D_
        while (i) {_x000D_
            a = str.indexOf('a', i);_x000D_
            b = str.searchOf(/a/, i);_x000D_
            r = ['Failed', 'searchOf', str, i, a, b];_x000D_
            if (a === b) {_x000D_
                r[0] = 'Passed';_x000D_
            }_x000D_
_x000D_
            log(r);_x000D_
            a = str.lastIndexOf('a', i);_x000D_
            b = str.searchLastOf(/a/, i);_x000D_
            r = ['Failed', 'searchLastOf', str, i, a, b];_x000D_
            if (a === b) {_x000D_
                r[0] = 'Passed';_x000D_
            }_x000D_
_x000D_
            log(r);_x000D_
            i -= 1;_x000D_
        }_x000D_
    }_x000D_
_x000D_
    /*_x000D_
     * Look for the a among the xes_x000D_
     */_x000D_
_x000D_
    test('xxx');_x000D_
    test('axx');_x000D_
    test('xax');_x000D_
    test('xxa');_x000D_
    test('axa');_x000D_
    test('xaa');_x000D_
    test('aax');_x000D_
    test('aaa');_x000D_
}());
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000 to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

Eclipse Indigo - Cannot install Android ADT Plugin

I've also had this problem. I solved it by going to:

Clicking -> available software sites
Select "Helios" and click Reload.
Select "ADT Plugin" and click Reload.
Then went back, tried again and it worked.

If you still can't get it working there are directions for doing it manually here:
http://developer.android.com/sdk/eclipse-adt.html#installing

(also: I'm using 3.7 64x, it's working fine, not having any issues.)

How to fix missing dependency warning when using useEffect React Hook?

just disable eslint for the next line;

useEffect(() => {
   fetchBusinesses();
// eslint-disable-next-line
}, []);

in this way you are using it just like a component did mount (called once)

updated

or

const fetchBusinesses = useCallback(() => {
 // your logic in here
 }, [someDeps])

useEffect(() => {
   fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]); 

fetchBusinesses will be called everytime someDeps will change

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

What IDE (if any) are you using? Does this happen when you're working within an IDE, or only on deployment? If it's deployment, it might be because whatever mechanism of deployment you use -- maven-assembly making a single JAR with dependencies is a known culprit -- is collapsing all your JARs into a single directory and the Spring schema and handler files are overwriting each other.

What is an IIS application pool?

An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Application pools are used to separate sets of IIS worker processes that share the same configuration and application boundaries. Application pools are used to isolate our web application for better security, reliability, availability and performance, and they keep running without impacting each other.

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Agreed with jcadcell comments, but had to use JDK 1.8 because my eclipse need that. So I just copied the MSVCR71.DLL from jdk1.6 and pasted into jdk1.8 in both the folder jdk1.8.0_121\bin and jdk1.8.0_121\jre\bin

and it Worked .... Wow... Thanks :)

'namespace' but is used like a 'type'

namespace TestApplication // Remove .Controller
{
    public class HomeController : Controller
    {
       public ActionResult Index()
        {
            return View();
        }
    }
}

Remove the controller word from namepsace

Create 3D array using Python

def n_arr(n, default=0, size=1):
    if n is 0:
        return default

    return [n_arr(n-1, default, size) for _ in range(size)]

arr = n_arr(3, 42, 3)
assert arr[2][2][2], 42

Is Java a Compiled or an Interpreted programming language ?

Kind of both. Firstly java compiled(some would prefer to say "translated") to bytecode, which then either compiled, or interpreted depending on mood of JIT.

Convert InputStream to BufferedReader

BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

PHP cURL not working - WAMP on Windows 7 64 bit

I think cURL doesn't work with WAMP 2.2e. I tried all your solutions, but it still did not work. I got the previous version, (2.2d) and it works.

So just download the previous version :D

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

Cannot open new Jupyter Notebook [Permission Denied]

I had to run chown recursively for all subfolders With /* . Than it worked:

sudo chown -R user:usergroup /home/user/.local/share/jupyter/*

Link a .css on another folder

I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :

    <link rel="stylesheet" type="text/css" href="file.css">

so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :

    <link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
    <link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

Combining peices from other answers, here is a solution that can open many levels of nested tabs:

// opens all tabs down to the specified tab
var hash = location.hash.split('?')[0];
if(hash) {
  var $link = $('[href=' + hash + ']');
  var parents = $link.parents('.tab-pane').get();
  $(parents.reverse()).each(function() {
    $('[href=#' + this.id + ']').tab('show') ;
  });
  $link.tab('show');
}

Pass Method as Parameter using C#

You should use a Func<string, int> delegate, that represents a function taking a string argument and returning an int value:

public bool RunTheMethod(Func<string, int> myMethod)
{
    // Do stuff
    myMethod.Invoke("My String");
    // Do stuff
    return true;
}

Then invoke it this way:

public bool Test()
{
    return RunTheMethod(Method1);
}

Display number always with 2 decimal places in <input>

Another shorthand to (@maudulus's answer) to remove {maxFractionDigits} since it's optional.

You can use {{numberExample | number : '1.2'}}

Difference between drop table and truncate table?

DROP Table

DROP TABLE [table_name];

The DROP command is used to remove a table from the database. It is a DDL command. All the rows, indexes and privileges of the table will also be removed. DROP operation cannot be rolled back.

DELETE Table

DELETE FROM [table_name]
WHERE [condition];

DELETE FROM [table_name];

The DELETE command is a DML command. It can be used to delete all the rows or some rows from the table based on the condition specified in WHERE clause. It is executed using a row lock, each row in the table is locked for deletion. It maintain the transaction log, so it is slower than TRUNCATE. DELETE operations can be rolled back.

TRUNCATE Table

TRUNCATE TABLE [table_name];

The TRUNCATE command removes all rows from a table. It won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster than DELETE. It is executed using a table lock and whole table is locked for remove all records. It is a DDL command. TRUNCATE operations cannot be rolled back.

PHP: merge two arrays while keeping keys instead of reindexing?

While this question is quite old I just want to add another possibility of doing a merge while keeping keys.

Besides adding key/values to existing arrays using the + sign you could do an array_replace.

$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');

$merged = array_replace($a, $b);

The result will be:

Array
(
  [foo] => bar
  [some] => string
  [42] => answer to the life and everything
  [1337] => leet
)

Same keys will be overwritten by the latter array.
There is also an array_replace_recursive, which do this for subarrays, too.

Live example on 3v4l.org

Optional Parameters in Go?

A nice way to achieve something like optional parameters is to use variadic args. The function actually receives a slice of whatever type you specify.

func foo(params ...int) {
    fmt.Println(len(params))
}

func main() {
    foo()
    foo(1)
    foo(1,2,3)
}

Android Fragment onClick button Method

The others have already said that methods in onClick are searched in activities, not fragments. Nevertheless, if you really want it, it is possible.

Basically, each view has a tag (probably null). We set the root view's tag to the fragment that inflated that view. Then, it is easy to search the view parents and retrieve the fragment containing the clicked button. Now, we find out the method name and use reflection to call the same method from the retrieved fragment. Easy!

in a class that extends Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_id, container, false);

    OnClickFragments.registerTagFragment(rootView, this); // <========== !!!!!

    return rootView;
}

public void onButtonSomething(View v) {
    Log.d("~~~","~~~ MyFragment.onButtonSomething");
    // whatever
}

all activities are derived from the same ButtonHandlingActivity:

public class PageListActivity extends ButtonHandlingActivity

ButtonHandlingActivity.java:

public class ButtonHandlingActivity extends Activity {

    public void onButtonSomething(View v) {
        OnClickFragments.invokeFragmentButtonHandlerNoExc(v);
//or, if you want to handle exceptions:
//      try {
//          OnClickFragments.invokeFragmentButtonHandler(v);
//      } catch ...
    }

}

It has to define methods for all xml onClick handlers.

com/example/customandroid/OnClickFragments.java:

package com.example.customandroid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Fragment;
import android.view.View;

public abstract class OnClickFragments {
    public static class FragmentHolder {
        Fragment fragment;
        public FragmentHolder(Fragment fragment) {
            this.fragment = fragment;
        }
    }
    public static Fragment getTagFragment(View view) {
        for (View v = view; v != null; v = (v.getParent() instanceof View) ? (View)v.getParent() : null) {
            Object tag = v.getTag();
            if (tag != null && tag instanceof FragmentHolder) {
                return ((FragmentHolder)tag).fragment;
            }
        }
        return null;
    }
    public static String getCallingMethodName(int callsAbove) {
        Exception e = new Exception();
        e.fillInStackTrace();
        String methodName = e.getStackTrace()[callsAbove+1].getMethodName();
        return methodName;
    }
    public static void invokeFragmentButtonHandler(View v, int callsAbove) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        String methodName = getCallingMethodName(callsAbove+1);
        Fragment f = OnClickFragments.getTagFragment(v);
        Method m = f.getClass().getMethod(methodName, new Class[] { View.class });
        m.invoke(f, v);
    }
    public static void invokeFragmentButtonHandler(View v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        invokeFragmentButtonHandler(v,1);
    }
    public static void invokeFragmentButtonHandlerNoExc(View v) {
        try {
            invokeFragmentButtonHandler(v,1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static void registerTagFragment(View rootView, Fragment fragment) {
        rootView.setTag(new FragmentHolder(fragment));
    }
}

And the next adventure will be proguard obfuscation...

PS

It is of course up to you to design your application so that the data live in the Model rather than in Activities or Fragments (which are Controllers from the MVC, Model-View-Controller point of view). The View is what you define via xml, plus the custom view classes (if you define them, most people just reuse what already is). A rule of thumb: if some data definitely must survive the screen turn, they belong to Model.

Installing and Running MongoDB on OSX

additionally you may want mongo to run on another port, then paste this command on terminal,

mongod --dbpath /data/db/ --port 27018

where 27018 is the port we want mongo to run on

assumptions

  1. mongod exists in your bin i.e /usr/local/bin/ for mac ( which would be if you installed with brew), otherwise you'd need to navigate to the path where mongo is installed
  2. the folder /data/db/ exists