Programs & Examples On #Build rules

Error "library not found for" after putting application in AdMob

I tried renaming my build configuration Release to Production, but apparently cocoa pods doesn't like it. I renamed it again to Release, and everything builds just fine.

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

How do I install g++ on MacOS X?

Installing XCode requires:

  • Enrolling on the Apple website (not fun)
  • Downloading a 4.7G installer

To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:

https://github.com/kennethreitz/osx-gcc-installer

The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.

The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.

Executing periodic actions in Python

Perhaps the sched module will meet your needs.

Alternatively, consider using a Timer object.

Breaking out of a nested loop

Don't quote me on this, but you could use goto as suggested in the MSDN. There are other solutions, as including a flag that is checked in each iteration of both loops. Finally you could use an exception as a really heavyweight solution to your problem.

GOTO:

for ( int i = 0; i < 10; ++i ) {
   for ( int j = 0; j < 10; ++j ) {
      // code
      if ( break_condition ) goto End;
      // more code
   }
}
End: ;

Condition:

bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
   for ( int j = 0; j < 10 && !exit; ++j ) {
      // code
      if ( break_condition ) {
         exit = true;
         break; // or continue
      }
      // more code
   }
}

Exception:

try {
    for ( int i = 0; i < 10 && !exit; ++i ) {
       for ( int j = 0; j < 10 && !exit; ++j ) {
          // code
          if ( break_condition ) {
             throw new Exception()
          }
          // more code
       }
    }
catch ( Exception e ) {}

Requested registry access is not allowed

I was trying the verb = "runas", but I still was getting UnauthorizedAccessException when trying to update registry value. Turned out it was due to not opening the subkey with writeable set to true.

Registry.OpenSubKey("KeyName", true);

Cannot write to Registry Key, getting UnauthorizedAccessException

Easiest way to copy a table from one database to another?

If you are using PHPMyAdmin, it could be really simple. Suppose you have following databases:

DB1 & DB2

DB1 have a table users which you like to copy to DB2

Under PHPMyAdmin, open DB1, then go to users table.

On this page, click on the "Operations" tab on the top right. Under Operations, look for section Copy table to (database.table):

& you are done!

Character Limit in HTML

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

show more/Less text with just HTML and JavaScript

Try to toggle height.

function toggleTextArea()
{
  var limitedHeight = '40px';
  var targetEle = document.getElementById("textarea");
  targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
}

How to get a context in a recycler view adapter

First add a global variable

Context mContext;

Then change your constructor to this

public FeedAdapter(Context context, List<Post> myDataset) {
    mContext = context;
    mDataset = myDataset;
}

The pass your context when creating the adapter.

FeedAdapter myAdapter = new FeedAdapter(this,myDataset);

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

I just assigned a variable, but echo $variable shows something else

In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

echo "$var"

This gives the expected value in all the examples given. Always quote variable references!


Why?

When a variable is unquoted, it will:

  1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

    Before: /* Foobar is free software */

    After: /*, Foobar, is, free, software, */

  2. Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

    Before: /*

    After: /bin, /boot, /dev, /etc, /home, ...

  3. Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

    /bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
    

    instead of the variable's value.

When the variable is quoted it will:

  1. Be substituted for its value.
  2. There is no step 2.

This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

Using comma as list separator with AngularJS

You can use CSS to fix it too

<div class="some-container">
[ <span ng-repeat="something in somethings">{{something}}<span class="list-comma">, </span></span> ]
</div>

.some-container span:last-child .list-comma{
    display: none;
}

But Andy Joslin's answer is best

Edit: I changed my mind I had to do this recently and I ended up going with a join filter.

How do I lowercase a string in C?

Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.

'React' must be in scope when using JSX react/react-in-jsx-scope?

The error is very straight forward, you imported react instead of React.

TechView.jsx

import React , { Component} from 'react';

class TechView extends Component {

    constructor(props){
       super(props);
       this.state = {
           name:'Gopinath'
       }
    }

    render(){
        return(
            <span>hello Tech View</span>
        );
    }
}

export default TechView;

Also you don't need to import render in the above code unless it's the root level index.js.

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <TechView />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

Note: You could have imported render the way you did in your original post and used it directly:

import React from 'react';
import { render } from 'react-dom';
import './index.css';
import TechView from './TechView';
import * as serviceWorker from './serviceWorker';

render(
  <React.StrictMode>
    <TechView />
  </React.StrictMode>,
  document.getElementById('root')
);

serviceWorker.unregister();

Here, TechView becomes the main react component, which is conventionally also known as App. So, in this context instead of naming the file as TechView.jsx I'd name it App.jsx and instead of naming the class as TechView I'd name it App.

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

Using custom fonts using CSS?

Generically, you can use a custom font using @font-face in your CSS. Here's a very basic example:

@font-face {
    font-family: 'YourFontName'; /*a name to be used later*/
    src: url('http://domain.com/fonts/font.ttf'); /*URL to font*/
}

Then, trivially, to use the font on a specific element:

.classname {
    font-family: 'YourFontName';
}

(.classname is your selector).

Note that certain font-formats don't work on all browsers; you can use fontsquirrel.com's generator to avoid too much effort converting.

You can find a nice set of free web-fonts provided by Google Fonts (also has auto-generated CSS @font-face rules, so you don't have to write your own).

while also preventing people from having free access to download the font, if possible

Nope, it isn't possible to style your text with a custom font embedded via CSS, while preventing people from downloading it. You need to use images, Flash, or the HTML5 Canvas, all of which aren't very practical.

I hope that helped!

Adding n hours to a date in Java?

Something like:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() + 
                        (2L * hoursInMillis)); // Adds 2 hours

Invalid default value for 'dateAdded'

mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP

numbers not allowed (0-9) - Regex Expression in javascript

Something as simple as [a-z]+, or perhaps [\S]+, or even [a-zA-Z]+?

How to print Unicode character in C++?

Ultimately, this is completely platform-dependent. Unicode-support is, unfortunately, very poor in Standard C++. For GCC, you will have to make it a narrow string, as they use UTF-8, and Windows wants a wide string, and you must output to wcout.

// GCC
std::cout << "?";
// Windoze
wcout << L"?";

Convert Variable Name to String?

What are you trying to achieve? There is absolutely no reason to ever do what you describe, and there is likely a much better solution to the problem you're trying to solve..

The most obvious alternative to what you request is a dictionary. For example:

>>> my_data = {'var': 'something'}
>>> my_data['something_else'] = 'something'
>>> print my_data.keys()
['var', 'something_else']
>>> print my_data['var']
something

Mostly as a.. challenge, I implemented your desired output. Do not use this code, please!

#!/usr/bin/env python2.6
class NewLocals:
    """Please don't ever use this code.."""
    def __init__(self, initial_locals):
        self.prev_locals = list(initial_locals.keys())

    def show_new(self, new_locals):
        output = ", ".join(list(set(new_locals) - set(self.prev_locals)))
        self.prev_locals = list(new_locals.keys())
        return output
# Set up
eww = None
eww = NewLocals(locals())

# "Working" requested code

var = {}

print eww.show_new(locals())  # Outputs: var

something_else = 3
print eww.show_new(locals()) # Outputs: something_else

# Further testing

another_variable = 4
and_a_final_one = 5

print eww.show_new(locals()) # Outputs: another_variable, and_a_final_one

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Favicon dimensions?

No, you can't use a non-standard size or dimension, as it'd wreak havoc on peoples' browsers wherever the icons are displayed. You could make it 12x16 (with four pixels of white/transparent padding on the 12 pixel side) to preserve your aspect ratio, but you can't go bigger (well, you can, but the browser'll shrink it).

How to import spring-config.xml of one project into spring-config.xml of another project?

Here is the annotation based example:

@SpringBootApplication
@ImportResource({"classpath*:spring-config.xml"})
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

IPhone/IPad: How to get screen width programmatically?

This can be done in in 3 lines of code:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];

Java division by zero doesnt throw an ArithmeticException - why?

That's because you are dealing with floating point numbers. Division by zero returns Infinity, which is similar to NaN (not a number).

If you want to prevent this, you have to test tab[i] before using it. Then you can throw your own exception, if you really need it.

Reverse ip, find domain names on ip address

This worked for me to get domain in intranet

https://gist.github.com/jrothmanshore/2656003

It's a powershell script. Run it in PowerShell

.\ip_lookup.ps1 <ip>

Maven Modules + Building a Single Specific Module

Say Parent pom.xml contains 6 modules and you want to run A, B and F.

<modules>
        <module>A</module>
        <module>B</module>
        <module>C</module>
        <module>D</module>
        <module>E</module>
        <module>F</module>
  </modules>

1- cd into parent project

 mvn --projects A,B,F --also-make clean install

OR

mvn -pl A,B,F -am clean install

OR

mvn -pl A,B,F -amd clean install

Note: When you specify a project with the -am option, Maven will build all of the projects that the specified project depends upon (either directly or indirectly). Maven will examine the list of projects and walk down the dependency tree, finding all of the projects that it needs to build.

While the -am command makes all of the projects required by a particular project in a multi-module build, the -amd or --also-make-dependents option configures Maven to build a project and any project that depends on that project. When using --also-make-dependents, Maven will examine all of the projects in our reactor to find projects that depend on a particular project. It will automatically build those projects and nothing else.

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

How to add target="_blank" to JavaScript window.location?

I have created a function that allows me to obtain this feature:

function redirect_blank(url) {
  var a = document.createElement('a');
  a.target="_blank";
  a.href=url;
  a.click();
}

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

Can vue-router open a link in a new tab?

This worked for me-

let routeData = this.$router.resolve(
{
  path: '/resources/c-m-communities', 
  query: {'dataParameter': 'parameterValue'}
});
window.open(routeData.href, '_blank');

I modified @Rafael_Andrs_Cspedes_Basterio answer

Why does NULL = NULL evaluate to false in SQL server

The equality test, for example, in a case statement when clause, can be changed from

XYZ = NULL 

to

XYZ IS NULL

If I want to treat blanks and empty string as equal to NULL I often also use an equality test like:

(NULLIF(ltrim( XYZ ),'') IS NULL)

Dropdownlist validation in Asp.net Using Required field validator

I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:

<asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
<asp:ListItem>--Select--</asp:ListItem>                                                                                                
<asp:ListItem>Expired</asp:ListItem>                                                                                                
<asp:ListItem>Lost/Stolen</asp:ListItem>                                                                                                
<asp:ListItem>Location Change</asp:ListItem>                                                                                            
</asp:DropDownList>

However adding the InitialValue like this worked instantly for a compare Validator.

<asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>

How to permanently remove few commits from remote branch

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

Get skin path in Magento?

First note that

Mage::getBaseDir('skin')

returns only path to skin directory of your Magento install (/your/magento/dir/skin).

You can access absolute path to currently used skin directory using:

Mage::getDesign()->getSkinBaseDir()

This method accepts an associative array as optional parameter to modify result.

Following keys are recognized:

  • _area frontend (default) or adminhtml
  • _package your package
  • _theme your theme
  • _relative when this is set (as an key) path relative to Mage::getBaseDir('skin') is returned.

So in your case correct answer would be:

require(Mage::getDesign()->getSkinBaseDir().DS.'myfunc.php');

How to write URLs in Latex?

You can use \url

\usepackage{hyperref}
\url{http://stackoverflow.com/}

How to get URI from an asset File?

The correct url is:

file:///android_asset/RELATIVEPATH

where RELATIVEPATH is the path to your resource relative to the assets folder.

Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.

This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.

EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.

Span inside anchor or anchor inside span or doesn't matter?

It will work both, but personally I'd prefer option 2 so the span is "around" the link.

Random record from MongoDB

The following aggregation operation randomly selects 3 documents from the collection:

db.users.aggregate( [ { $sample: { size: 3 } } ] )

https://docs.mongodb.com/manual/reference/operator/aggregation/sample/

change image opacity using javascript

You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached

subsetting a Python DataFrame

I've found that you can use any subset condition for a given column by wrapping it in []. For instance, you have a df with columns ['Product','Time', 'Year', 'Color']

And let's say you want to include products made before 2014. You could write,

df[df['Year'] < 2014]

To return all the rows where this is the case. You can add different conditions.

df[df['Year'] < 2014][df['Color' == 'Red']

Then just choose the columns you want as directed above. For instance, the product color and key for the df above,

df[df['Year'] < 2014][df['Color'] == 'Red'][['Product','Color']]

Remove a prefix from a string

I think you can use methods of the str type to do this. There's no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text

python pandas remove duplicate columns

Transposing is inefficient for large DataFrames. Here is an alternative:

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []
    for t, v in groups.items():
        dcols = frame[v].to_dict(orient="list")

        vs = dcols.values()
        ks = dcols.keys()
        lvs = len(vs)

        for i in range(lvs):
            for j in range(i+1,lvs):
                if vs[i] == vs[j]: 
                    dups.append(ks[i])
                    break

    return dups       

Use it like this:

dups = duplicate_columns(frame)
frame = frame.drop(dups, axis=1)

Edit

A memory efficient version that treats nans like any other value:

from pandas.core.common import array_equivalent

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []

    for t, v in groups.items():

        cs = frame[v].columns
        vs = frame[v]
        lcs = len(cs)

        for i in range(lcs):
            ia = vs.iloc[:,i].values
            for j in range(i+1, lcs):
                ja = vs.iloc[:,j].values
                if array_equivalent(ia, ja):
                    dups.append(cs[i])
                    break

    return dups

IPC performance: Named Pipe vs Socket

For two way communication with named pipes:

  • If you have few processes, you can open two pipes for two directions (processA2ProcessB and processB2ProcessA)
  • If you have many processes, you can open in and out pipes for every process (processAin, processAout, processBin, processBout, processCin, processCout etc)
  • Or you can go hybrid as always :)

Named pipes are quite easy to implement.

E.g. I implemented a project in C with named pipes, thanks to standart file input-output based communication (fopen, fprintf, fscanf ...) it was so easy and clean (if that is also a consideration).

I even coded them with java (I was serializing and sending objects over them!)

Named pipes has one disadvantage:

  • they do not scale on multiple computers like sockets since they rely on filesystem (assuming shared filesystem is not an option)

"Cloning" row or column vectors

Use numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

or for repeating columns:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

Open URL in new window with JavaScript

Use window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>

This will create a link titled Share Page which opens the current url in a new window with a height of 570 and width of 520.

How to iterate over a JSONObject?

Iterator<JSONObject> iterator = jsonObject.values().iterator();

while (iterator.hasNext()) {
 jsonChildObject = iterator.next();

 // Do whatever you want with jsonChildObject 

  String id = (String) jsonChildObject.get("id");
}

How to make canvas responsive

try using max-width: 100%; on your canvas.

canvas {
  max-width: 100%;
}

SPA best practices for authentication and session management

You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.

The Basic Auth / Session ID can be stolen via:

  • MITM attack (Man-In-The-Middle) - without SSL/HTTPS
  • An intruder gaining access to a user's computer
  • XSS

By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.

The new (more secure) flow would be:

Login

  • User logs in and sends login credentials to API (over SSL/HTTPS)
  • API receives login credentials
  • If valid:
    • Register a new session in the database Read update
    • Encrypt User ID, Session ID, IP address, timestamp, etc. in a JWT with a private key.
  • API sends the JWT token back to the client (over SSL/HTTPS)
  • Client receives the JWT token and stores in localStorage/cookie

Every request to API

  • User sends a HTTP request to API (over SSL/HTTPS) with the stored JWT token in the HTTP header
  • API reads HTTP header and decrypts JWT token with its private key
  • API validates the JWT token, matches the IP address from the HTTP request with the one in the JWT token and checks if session has expired
  • If valid:
    • Return response with requested content
  • If invalid:
    • Throw exception (403 / 401)
    • Flag intrusion in the system
    • Send a warning email to the user.

Updated 30.07.15:

JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).

I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).

Updated 17.07.16:

JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.

How can I control the width of a label tag?

Inline elements (like SPAN, LABEL, etc.) are displayed so that their height and width are calculated by the browser based on their content. If you want to control height and width you have to change those elements' blocks.

display: block; makes the element displayed as a solid block (like DIV tags) which means that there is a line break after the element (it's not inline). Although you can use display: inline-block to fix the issue of line break, this solution does not work in IE6 because IE6 doesn't recognize inline-block. If you want it to be cross-browser compatible then look at this article: http://webjazz.blogspot.com/2008/01/getting-inline-block-working-across.html

Concatenating multiple text files into a single file in Bash

Just remember, for all the solutions given so far, the shell decides the order in which the files are concatenated. For Bash, IIRC, that's alphabetical order. If the order is important, you should either name the files appropriately (01file.txt, 02file.txt, etc...) or specify each file in the order you want it concatenated.

$ cat file1 file2 file3 file4 file5 file6 > out.txt

Difference between wait and sleep

One key difference not yet mentioned is that while sleeping a Thread does not release the locks it holds, while waiting releases the lock on the object that wait() is called on.

synchronized(LOCK) {
    Thread.sleep(1000); // LOCK is held
}


synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
}

What's the proper value for a checked attribute of an HTML checkbox?

  1. checked
  2. checked=""
  3. checked="checked"

    are equivalent;


according to spec checkbox '----? checked = "checked" or "" (empty string) or empty Specifies that the element represents a selected control.---'

How to get evaluated attributes inside a custom directive

For the same solution I was looking for Angularjs directive with ng-Model.
Here is the code that resolve the problem.

    myApp.directive('zipcodeformatter', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {

            scope.$watch(attrs.ngModel, function (v) {
                if (v) {
                    console.log('value changed, new value is: ' + v + ' ' + v.length);
                    if (v.length > 5) {
                        var newzip = v.replace("-", '');
                        var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
                        element.val(str);

                    } else {
                        element.val(v);
                    }

                }

            });

        }
    };
});


HTML DOM

<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">


My Result is:

92108-2223

How to return dictionary keys as a list in Python?

A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

Why do abstract classes in Java have constructors?

All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated

How does DHT in torrents work?

What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.

The original information bootstraps the later use of the DHT.

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Hope it helps someone on earth. In my case jQuery and $ were available but not when the plugin bootstrapped so I wrapped everything inside a setTimeout. Wrapping inside setTimeout helped me fix the error:

setTimeout(() => {
    /** Your code goes here */

    !function(t, e) {

    }(window);

})

How to resize JLabel ImageIcon?

And what about it?:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

From: Resize a picture to fit a JLabel

Pandas: Setting no. of max rows

pd.set_option('display.max_rows', 500)
df

Does not work in Jupyter!
Instead use:

pd.set_option('display.max_rows', 500)
df.head(500)

Running a single test from unittest.TestCase via the command line

It can work well as you guess

python testMyCase.py MyCase.testItIsHot

And there is another way to just test testItIsHot:

    suite = unittest.TestSuite()
    suite.addTest(MyCase("testItIsHot"))
    runner = unittest.TextTestRunner()
    runner.run(suite)

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

How do I create a right click context menu in Java Swing?

You are probably manually calling setVisible(true) on the menu. That can cause some nasty buggy behavior in the menu.

The show(Component, int x, int x) method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true) just shows the menu without adding any additional behavior.

To make a right click popup menu simply create a JPopupMenu.

class PopUpDemo extends JPopupMenu {
    JMenuItem anItem;
    public PopUpDemo() {
        anItem = new JMenuItem("Click Me!");
        add(anItem);
    }
}

Then, all you need to do is add a custom MouseListener to the components you would like the menu to popup for.

class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger())
            doPop(e);
    }

    private void doPop(MouseEvent e) {
        PopUpDemo menu = new PopUpDemo();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }
}

// Then on your component(s)
component.addMouseListener(new PopClickListener());

Of course, the tutorials have a slightly more in-depth explanation.

Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen() and e.getYOnScreen() methods for the x and y coordinates.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Excel doesn't update value unless I hit Enter

Found the problem and couldn't find the solution until tried this.

  1. Open Visual Basic from Developer tab (OR right-click at any sheet and click 'View code')
  2. At upper left panel, select 'ThisWorkbook'
  3. At lower left panel, find 'ForceFullCalculation' attribute
  4. Change it from 'False' to 'True' and save it

I'm not sure if this has any side-effect, but it is work for me now.

How much data can a List can hold at the maximum?

see the code below of arraylist default it is 10 when u create List l = new ArrayList();

   public class ArrayList<E> extends AbstractList<E> implements List<E>,
           Cloneable, Serializable, RandomAccess {

          private static final long serialVersionUID = 8683452581122892189L;

          private transient int firstIndex;

          private transient int lastIndex;

          private transient E[] array;

          /**
           * Constructs a new instance of {@code ArrayList} with ten capacity.
           */
          public ArrayList() {
              this(10);
          }

How to implement a Map with multiple keys?

I recommend something like this:

    public class MyMap {

      Map<Object, V> map = new HashMap<Object, V>();


      public V put(K1 key,V value){
        return map.put(key, value);
      }

      public V put(K2 key,V value){
        return map.put(key, value);
      }

      public V get(K1 key){    
        return map.get(key);
      }

      public V get(K2 key){    
        return map.get(key);
      }

      //Same for conatains

    }

Then you can use it like:
myMap.put(k1,value) or myMap.put(k2,value)

Advantages: It is simple, enforces type safety, and doesn't store repeated data (as the two maps solutions do, though still store duplicate values).
Drawbacks: Not generic.

How do I remove all non alphanumeric characters from a string except dash?

You can try:

string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");

Where s is your string.

Install a .NET windows service without InstallUtil.exe

You can always fall back to the good old WinAPI calls, although the amount of work involved is non-trivial. There is no requirement that .NET services be installed via a .NET-aware mechanism.

To install:

  • Open the service manager via OpenSCManager.
  • Call CreateService to register the service.
  • Optionally call ChangeServiceConfig2 to set a description.
  • Close the service and service manager handles with CloseServiceHandle.

To uninstall:

  • Open the service manager via OpenSCManager.
  • Open the service using OpenService.
  • Delete the service by calling DeleteService on the handle returned by OpenService.
  • Close the service and service manager handles with CloseServiceHandle.

The main reason I prefer this over using the ServiceInstaller/ServiceProcessInstaller is that you can register the service with your own custom command line arguments. For example, you might register it as "MyApp.exe -service", then if the user runs your app without any arguments you could offer them a UI to install/remove the service.

Running Reflector on ServiceInstaller can fill in the details missing from this brief explanation.

P.S. Clearly this won't have "the same effect as calling: InstallUtil MyService.exe" - in particular, you won't be able to uninstall using InstallUtil. But it seems that perhaps this wasn't an actual stringent requirement for you.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I faced this kind of issue once in my case here's what i did

  1. Delete the app from simulator.
  2. Delete the derived data folder.
  3. Perform a clean action in the project by selecting the product menu - clean
  4. Reset the simulator.
  5. Quit Xcode.
  6. Try running the project now if its working fine else go to step 7
  7. Repeat all steps from 1 to 5 and then restart your machine.

In most of the cases i got it running at step 6 extreme cases i had to restart my machine.

Make 2 functions run at the same time

The thread module does work simultaneously unlike multiprocess, but the timing is a bit off. The code below prints a "1" and a "2". These are called by different functions respectively. I did notice that when printed to the console, they would have slightly different timings.

from threading import Thread

def one():
    while(1 == num):
        print("1")
        time.sleep(2)
    
def two():
    while(1 == num):
        print("2")
        time.sleep(2)


p1 = Thread(target = one)
p2 = Thread(target = two)

p1.start()
p2.start()

Output: (Note the space is for the wait in between printing)

1
2

2
1

12
   
21

12
   
1
2

Not sure if there is a way to correct this, or if it matters at all. Just something I noticed.

Load RSA public key from file

Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.

Create a PemFile class that encapsulates file handling:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public class PemFile {

    private PemObject pemObject;

    public PemFile(String filename) throws FileNotFoundException, IOException {
        PemReader pemReader = new PemReader(new InputStreamReader(
                new FileInputStream(filename)));
        try {
            this.pemObject = pemReader.readPemObject();
        } finally {
            pemReader.close();
        }
    }

    public PemObject getPemObject() {
        return pemObject;
    }
}

Then instantiate private and public keys as usual:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main {

    protected final static Logger LOGGER = Logger.getLogger(Main.class);

    public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";

    public static void main(String[] args) throws FileNotFoundException,
            IOException, NoSuchAlgorithmException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        LOGGER.info("BouncyCastle provider added.");

        KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
        try {
            PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
                    + "id_rsa");
            LOGGER.info(String.format("Instantiated private key: %s", priv));

            PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
                    + "id_rsa.pub");
            LOGGER.info(String.format("Instantiated public key: %s", pub));
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    private static PrivateKey generatePrivateKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
        return factory.generatePrivate(privKeySpec);
    }

    private static PublicKey generatePublicKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
        return factory.generatePublic(pubKeySpec);
    }
}

Hope this helps.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Allow Apache Through the Firewall

Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp

And reload the firewall:

sudo firewall-cmd --reload

SQL - Create view from multiple tables

Thanks for the help. This is what I ended up doing in order to make it work.

CREATE VIEW V AS
    SELECT *
    FROM ((POP NATURAL FULL OUTER JOIN FOOD)
    NATURAL FULL OUTER JOIN INCOME);

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I have found that python-dotenv helps solve this issue pretty effectively. Your project structure ends up changing slightly, but the code in your notebook is a bit simpler and consistent across notebooks.

For your project, do a little install.

pipenv install python-dotenv

Then, project changes to:

+-- .env (this can be empty)
+-- ipynb
¦   +-- 20170609-Examine_Database_Requirements.ipynb
¦   +-- 20170609-Initial_Database_Connection.ipynb
+-- lib
    +-- __init__.py
    +-- postgres.py

And finally, your import changes to:

import os
import sys

from dotenv import find_dotenv


sys.path.append(os.path.dirname(find_dotenv()))

A +1 for this package is that your notebooks can be several directories deep. python-dotenv will find the closest one in a parent directory and use it. A +2 for this approach is that jupyter will load environment variables from the .env file on startup. Double whammy.

do-while loop in R

Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).

  df <- data.frame(X=c(), R=c())  
  x <- x0
  continue <- TRUE

  while(continue)
  {
    xi <- (11 * x) %% 16
    df <- rbind(df, data.frame(X=x, R=xi))
    x <- xi

    if(xi == x0)
    {
      continue <- FALSE
    }
  }

Uncaught (in promise) TypeError: Failed to fetch and Cors error

you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port

2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem

3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions

the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment

Refreshing data in RecyclerView and keeping its scroll position

That's working for me in Kotlin.

  1. Create the Adapter and hand over your data in the constructor
class LEDRecyclerAdapter (var currentPole: Pole): RecyclerView.Adapter<RecyclerView.ViewHolder>()  { ... }
  1. change this property and call notifyDataSetChanged()
adapter.currentPole = pole
adapter.notifyDataSetChanged()

The scroll offset doesn't change.

Determine path of the executing script

Here there is a simple solution for the problem. This command:

script.dir <- dirname(sys.frame(1)$ofile)

returns the path of the current script file. It works after the script was saved.

EC2 instance types's exact network performance?

FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.

Sql Server return the value of identity column after insert statement

send an output parameter like

@newId int output

at the end use

    select @newId = Scope_Identity() 

     return @newId 

When should I use a struct rather than a class in C#?

The source referenced by the OP has some credibility ...but what about Microsoft - what is the stance on struct usage? I sought some extra learning from Microsoft, and here is what I found:

Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

Do not define a structure unless the type has all of the following characteristics:

  1. It logically represents a single value, similar to primitive types (integer, double, and so on).
  2. It has an instance size smaller than 16 bytes.
  3. It is immutable.
  4. It will not have to be boxed frequently.

Microsoft consistently violates those rules

Okay, #2 and #3 anyway. Our beloved dictionary has 2 internal structs:

[StructLayout(LayoutKind.Sequential)]  // default for structs
private struct Entry  //<Tkey, TValue>
{
    //  View code at *Reference Source
}

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator : 
    IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, 
    IDictionaryEnumerator, IEnumerator
{
    //  View code at *Reference Source
}

*Reference Source

The 'JonnyCantCode.com' source got 3 out of 4 - quite forgivable since #4 probably wouldn't be an issue. If you find yourself boxing a struct, rethink your architecture.

Let's look at why Microsoft would use these structs:

  1. Each struct, Entry and Enumerator, represent single values.
  2. Speed
  3. Entry is never passed as a parameter outside of the Dictionary class. Further investigation shows that in order to satisfy implementation of IEnumerable, Dictionary uses the Enumerator struct which it copies every time an enumerator is requested ...makes sense.
  4. Internal to the Dictionary class. Enumerator is public because Dictionary is enumerable and must have equal accessibility to the IEnumerator interface implementation - e.g. IEnumerator getter.

Update - In addition, realize that when a struct implements an interface - as Enumerator does - and is cast to that implemented type, the struct becomes a reference type and is moved to the heap. Internal to the Dictionary class, Enumerator is still a value type. However, as soon as a method calls GetEnumerator(), a reference-type IEnumerator is returned.

What we don't see here is any attempt or proof of requirement to keep structs immutable or maintaining an instance size of only 16 bytes or less:

  1. Nothing in the structs above is declared readonly - not immutable
  2. Size of these struct could be well over 16 bytes
  3. Entry has an undetermined lifetime (from Add(), to Remove(), Clear(), or garbage collection);

And ... 4. Both structs store TKey and TValue, which we all know are quite capable of being reference types (added bonus info)

Hashed keys notwithstanding, dictionaries are fast in part because instancing a struct is quicker than a reference type. Here, I have a Dictionary<int, int> that stores 300,000 random integers with sequentially incremented keys.

Capacity: 312874
MemSize: 2660827 bytes
Completed Resize: 5ms
Total time to fill: 889ms

Capacity: number of elements available before the internal array must be resized.

MemSize: determined by serializing the dictionary into a MemoryStream and getting a byte length (accurate enough for our purposes).

Completed Resize: the time it takes to resize the internal array from 150862 elements to 312874 elements. When you figure that each element is sequentially copied via Array.CopyTo(), that ain't too shabby.

Total time to fill: admittedly skewed due to logging and an OnResize event I added to the source; however, still impressive to fill 300k integers while resizing 15 times during the operation. Just out of curiosity, what would the total time to fill be if I already knew the capacity? 13ms

So, now, what if Entry were a class? Would these times or metrics really differ that much?

Capacity: 312874
MemSize: 2660827 bytes
Completed Resize: 26ms
Total time to fill: 964ms

Obviously, the big difference is in resizing. Any difference if Dictionary is initialized with the Capacity? Not enough to be concerned with ... 12ms.

What happens is, because Entry is a struct, it does not require initialization like a reference type. This is both the beauty and the bane of the value type. In order to use Entry as a reference type, I had to insert the following code:

/*
 *  Added to satisfy initialization of entry elements --
 *  this is where the extra time is spent resizing the Entry array
 * **/
for (int i = 0 ; i < prime ; i++)
{
    destinationArray[i] = new Entry( );
}
/*  *********************************************** */  

The reason I had to initialize each array element of Entry as a reference type can be found at MSDN: Structure Design. In short:

Do not provide a default constructor for a structure.

If a structure defines a default constructor, when arrays of the structure are created, the common language runtime automatically executes the default constructor on each array element.

Some compilers, such as the C# compiler, do not allow structures to have default constructors.

It is actually quite simple and we will borrow from Asimov's Three Laws of Robotics:

  1. The struct must be safe to use
  2. The struct must perform its function efficiently, unless this would violate rule #1
  3. The struct must remain intact during its use unless its destruction is required to satisfy rule #1

...what do we take away from this: in short, be responsible with the use of value types. They are quick and efficient, but have the ability to cause many unexpected behaviors if not properly maintained (i.e. unintentional copies).

Array of PHP Objects

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

align textbox and text/labels in html?

you can do a multi div layout like this

<div class="fieldcontainer">
    <div class="label"></div>
    <div class="field"></div>
</div>

where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }

Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

How is a CRC32 checksum calculated?

In order to reduce crc32 to taking the reminder you need to:

  1. Invert bits on each byte
  2. xor first four bytes with 0xFF (this is to avoid errors on the leading 0s)
  3. Add padding at the end (this is to make the last 4 bytes take part in the hash)
  4. Compute the reminder
  5. Reverse the bits again
  6. xor the result again.

In code this is:


func CRC32 (file []byte) uint32 {
    for i , v := range(file) {
        file[i] = bits.Reverse8(v)
    }
    for i := 0; i < 4; i++ {
        file[i] ^= 0xFF
    }

    // Add padding
    file = append(file, []byte{0, 0, 0, 0}...)
    newReminder := bits.Reverse32(reminderIEEE(file))

    return newReminder ^ 0xFFFFFFFF
}

where reminderIEEE is the pure reminder on GF(2)[x]

Best C/C++ Network Library

Aggregated List of Libraries

Equivalent of LIMIT and OFFSET for SQL Server?

The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).

Note: the @Offset parameter should use one-based indexing for this rather than the normal zero-based indexing.

How to perform a for loop on each character in a string in Bash?

With sed on dash shell of LANG=en_US.UTF-8, I got the followings working right:

$ echo "??? ????????" | sed -e 's/\(.\)/\1\n/g'
?
?
?

?
?
?
?
?
?
?
?

and

$ echo "Hello world" | sed -e 's/\(.\)/\1\n/g'
H
e
l
l
o

w
o
r
l
d

Thus, output can be looped with while read ... ; do ... ; done

edited for sample text translate into English:

"??? ????????" is zh_TW.UTF-8 encoding for:
"???"     = How are you[ doing]
" "         = a normal space character
"???"     = Happy new year
"?????" = a double-byte-sized full-stop followed by text description

MySQL select one column DISTINCT, with corresponding other columns

As pointed out by fyrye, the accepted answer pertains to older versions of MySQL in which ONLY_FULL_GROUP_BY had not yet been introduced. With MySQL 8.0.17 (used in this example), unless you disable ONLY_FULL_GROUP_BY you would get the following error message:

mysql> SELECT id, firstName, lastName FROM table_name GROUP BY firstName;

ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mydatabase.table_name.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

One way to work around this not mentioned by fyrye, but described in https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html, is to apply the ANY_VALUE() function to the columns which are not in the GROUP BY clause (id and lastName in this example):

mysql> SELECT ANY_VALUE(id) as id, firstName, ANY_VALUE(lastName) as lastName FROM table_name GROUP BY firstName;
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | John      | Doe      |
|  2 | Bugs      | Bunny    |
+----+-----------+----------+
2 rows in set (0.01 sec)

As written in the aforementioned docs,

In this case, MySQL ignores the nondeterminism of address values within each name group and accepts the query. This may be useful if you simply do not care which value of a nonaggregated column is chosen for each group. ANY_VALUE() is not an aggregate function, unlike functions such as SUM() or COUNT(). It simply acts to suppress the test for nondeterminism.

Parsing query strings on Android

I don't think there is one in JRE. You can find similar functions in other packages like Apache HttpClient. If you don't use any other packages, you just have to write your own. It's not that hard. Here is what I use,

public class QueryString {

 private Map<String, List<String>> parameters;

 public QueryString(String qs) {
  parameters = new TreeMap<String, List<String>>();

  // Parse query string
     String pairs[] = qs.split("&");
     for (String pair : pairs) {
            String name;
            String value;
            int pos = pair.indexOf('=');
            // for "n=", the value is "", for "n", the value is null
         if (pos == -1) {
          name = pair;
          value = null;
         } else {
       try {
        name = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
              value = URLDecoder.decode(pair.substring(pos+1, pair.length()), "UTF-8");            
       } catch (UnsupportedEncodingException e) {
        // Not really possible, throw unchecked
           throw new IllegalStateException("No UTF-8");
       }
         }
         List<String> list = parameters.get(name);
         if (list == null) {
          list = new ArrayList<String>();
          parameters.put(name, list);
         }
         list.add(value);
     }
 }

 public String getParameter(String name) {        
  List<String> values = parameters.get(name);
  if (values == null)
   return null;

  if (values.size() == 0)
   return "";

  return values.get(0);
 }

 public String[] getParameterValues(String name) {        
  List<String> values = parameters.get(name);
  if (values == null)
   return null;

  return (String[])values.toArray(new String[values.size()]);
 }

 public Enumeration<String> getParameterNames() {  
  return Collections.enumeration(parameters.keySet()); 
 }

 public Map<String, String[]> getParameterMap() {
  Map<String, String[]> map = new TreeMap<String, String[]>();
  for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
   List<String> list = entry.getValue();
   String[] values;
   if (list == null)
    values = null;
   else
    values = (String[]) list.toArray(new String[list.size()]);
   map.put(entry.getKey(), values);
  }
  return map;
 } 
}

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

How to hide 'Back' button on navigation bar on iPhone?

hide back button with bellow code...

[self.navigationItem setHidesBackButton:YES animated:YES];

or

[self.navigationItem setHidesBackButton:YES];

Also if you have custom UINavigationBar then try bellow code

self.navigationItem.leftBarButtonItem = nil;

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I had the exact same problem and since I read somewhere that the error was caused by a cached file, I fixed it by deleting all the files under the .m2 repository folder. The next time I built the project I had to download all the dependencies again but it was worth it - 0 errors!!

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

What does 'super' do in Python?

Consider the following code:

class X():
    def __init__(self):
        print("X")

class Y(X):
    def __init__(self):
        # X.__init__(self)
        super(Y, self).__init__()
        print("Y")

class P(X):
    def __init__(self):
        super(P, self).__init__()
        print("P")

class Q(Y, P):
    def __init__(self):
        super(Q, self).__init__()
        print("Q")

Q()

If change constructor of Y to X.__init__, you will get:

X
Y
Q

But using super(Y, self).__init__(), you will get:

X
P
Y
Q

And P or Q may even be involved from another file which you don't know when you writing X and Y. So, basically, you won't know what super(Child, self) will reference to when you are writing class Y(X), even the signature of Y is as simple as Y(X). That's why super could be a better choice.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Create a date from day month and year with T-SQL

Try this query:

    SELECT SUBSTRING(CONVERT(VARCHAR,JOINGDATE,103),7,4)AS
    YEAR,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),1,2)AS
MONTH,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),4,3)AS DATE FROM EMPLOYEE1

Result:

2014    Ja    1
2015    Ja    1
2014    Ja    1
2015    Ja    1
2012    Ja    1
2010    Ja    1
2015    Ja    1

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

How can I get the URL of the current tab from a Google Chrome extension?

For those using the context menu api, the docs are not immediately clear on how to obtain tab information.

  chrome.contextMenus.onClicked.addListener(function(info, tab) {
    console.log(info);
    return console.log(tab);
  });

https://developer.chrome.com/extensions/contextMenus

MySQL INNER JOIN select only one row from second table

You need to have a subquery to get their latest date per user ID.

SELECT  a.*, c.*
FROM users a 
    INNER JOIN payments c
        ON a.id = c.user_ID
    INNER JOIN
    (
        SELECT user_ID, MAX(date) maxDate
        FROM payments
        GROUP BY user_ID
    ) b ON c.user_ID = b.user_ID AND
            c.date = b.maxDate
WHERE a.package = 1

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

Checking the header file solve's the problem. One can check for there system compiler.

For my system , AF_INET == PF_INET

AF == Address Family And PF == Protocol Family

Protocol families, same as address families.

enter image description here

Reading specific columns from a text file in python

I know this is an old question, but nobody mentioned that when your data looks like an array, numpy's loadtxt comes in handy:

>>> import numpy as np
>>> np.loadtxt("myfile.txt")[:, 1]
array([10., 20., 30., 40., 23., 13.])

inverting image in Python with OpenCV

You can use "tilde" operator to do it:

import cv2
image = cv2.imread("img.png")
image = ~image
cv2.imwrite("img_inv.png",image)

This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object

for example for integers, its formula is:

x + (~x) = -1

but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255

so if we apply this operator to an "uint8 numpy array object" like this:

import numpy as np
x1 = np.array([25,255,10], np.uint8) #for example
x2 = ~x1
print (x2)

we will have as a result:

[230 0 245]

because its formula is:

x2 = 255 - x1

and that is exactly what we want to do to solve the problem.

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

Set default syntax to different filetype in Sublime Text 2

Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:

{
    "extensions":["cfg"]
}

And then restart Sublime Text

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Convert HTML string to image

       <!--ForExport data in iamge -->
        <script type="text/javascript">
            function ConvertToImage(btnExport) {
                html2canvas($("#dvTable")[0]).then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=hfImageData]").val(base64);
                    __doPostBack(btnExport.name, "");
                });
                return false;
            }
        </script>

        <!--ForExport data in iamge -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="../js/html2canvas.min.js"></script> 





<table>
                <tr>
                    <td valign="top">
                        <asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
                            OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                        <div id="dvTable" class="divsection2" style="width: 350px">
                            <asp:HiddenField ID="hfImageData" runat="server" />
                            <table width="100%">
                                <tr>
                                    <td>
                                        <br />

                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
                                    </td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>


         protected void ExportToImage(object sender, EventArgs e)
                {
                    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(base64);
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();

                }

Using bootstrap with bower

I finally ended using the following : bower install --save http://twitter.github.com/bootstrap/assets/bootstrap.zip

Seems cleaner to me since it doesn't clone the whole repo, it only unzip the required assests.

The downside of that is that it breaks the bower philosophy since a bower update will not update bootstrap.

But I think it's still cleaner than using bower install bootstrap and then building bootstrap in your workflow.

It's a matter of choice I guess.

Update : seems they now version a dist folder (see: https://github.com/twbs/bootstrap/pull/6342), so just use bower install bootstrap and point to the assets in the dist folder

List of foreign keys and the tables they reference in Oracle DB

If you need all the foreign keys of the user then use the following script

SELECT a.constraint_name, a.table_name, a.column_name,  c.owner, 
       c_pk.table_name r_table_name,  b.column_name r_column_name
  FROM user_cons_columns a
  JOIN user_constraints c ON a.owner = c.owner
       AND a.constraint_name = c.constraint_name
  JOIN user_constraints c_pk ON c.r_owner = c_pk.owner
       AND c.r_constraint_name = c_pk.constraint_name
  JOIN user_cons_columns b ON C_PK.owner = b.owner
       AND  C_PK.CONSTRAINT_NAME = b.constraint_name AND b.POSITION = a.POSITION     
 WHERE c.constraint_type = 'R'

based on Vincent Malgrat code

react hooks useEffect() cleanup for only componentWillUnmount?

To add to the accepted answer, I had a similar issue and solved it using a similar approach with the contrived example below. In this case I needed to log some parameters on componentWillUnmount and as described in the original question I didn't want it to log every time the params changed.

const componentWillUnmount = useRef(false)

// This is componentWillUnmount
useEffect(() => {
    return () => {
        componentWillUnmount.current = true
    }
}, [])

useEffect(() => {
    return () => {
        // This line only evaluates to true after the componentWillUnmount happens 
        if (componentWillUnmount.current) {
            console.log(params)
        }
    }

}, [params]) // This dependency guarantees that when the componentWillUnmount fires it will log the latest params

Do I need to explicitly call the base virtual destructor?

No you don't need to call the base destructor, a base destructor is always called for you by the derived destructor. Please see my related answer here for order of destruction.

To understand why you want a virtual destructor in the base class, please see the code below:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

Then if you did not have a virtual destructor in B, only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

How can I make an entire HTML form "readonly"?

I'd rather use jQuery:

$('#'+formID).find(':input').attr('disabled', 'disabled');

find() would go much deeper till nth nested child than children(), which looks for immediate children only.

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

What are good message queue options for nodejs?

You might want to have a look at

Redis Simple Message Queue for Node.js

Which uses Redis and offers most features of Amazons SQS.

SQL Server stored procedure parameters

I'm going on a bit of an assumption here, but I'm assuming the logic inside the procedure gets split up via task. And you cant have nullable parameters as @Yuck suggested because of the dynamics of the parameters?

So going by my assumption

If TaskName = "Path1" Then Something

If TaskName = "Path2" Then Something Else

My initial thought is, if you have separate functions with business-logic you need to create, and you can determine that you have say 5-10 different scenarios, rather write individual stored procedures as needed, instead of trying one huge one solution fits all approach. Might get a bit messy to maintain.

But if you must...

Why not try dynamic SQL, as suggested by @E.J Brennan (Forgive me, i haven't touched SQL in a while so my syntax might be rusty) That being said i don't know if its the best approach, but could this could possibly meet your needs?

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50)
    @Values varchar(200)
AS
BEGIN
  DECLARE @SQL VARCHAR(MAX)

  IF @TaskName = 'Something'
  BEGIN
    @SQL = 'INSERT INTO.....' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  IF @TaskName = 'Something Else'
  BEGIN
    @SQL = 'DELETE SOMETHING WHERE' + CHAR(13)
    @SQL += @Values + CHAR(13) 
  END

  PRINT(@SQL)
  EXEC(@SQL)    
END

(The CHAR(13) adds a new line.. an old habbit i picked up somewhere, used to help debugging/reading dynamic procedures when running SQL profiler.)

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

By default, the classes in the csv module use Windows-style line terminators (\r\n) rather than Unix-style (\n). Could this be what’s causing the apparent double line breaks?

If so, you can override it in the DictWriter constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

Can jQuery check whether input content has changed?

function checkChange($this){
    var value = $this.val();      
    var sv=$this.data("stored");            
        if(value!=sv)
            $this.trigger("simpleChange");    
}

$(document).ready(function(){
    $(this).data("stored",$(this).val());   
        $("input").bind("keyup",function(e){  
        checkChange($(this));
    });        
    $("input").bind("simpleChange",function(e){
        alert("the value is chaneged");
    });        
});

here is the fiddle http://jsfiddle.net/Q9PqT/1/

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

What is aria-label and how should I use it?

Prerequisite:

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type="edit" aria-label="search" placeholder="search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id="sd">Search</span>

<input type="text" aria-labelledby="sd">

Approach 2:

aria-labelledby can also be used to combine two labels for screen reader users

<span id="de">Billing Address</span>

<span id="sd">First Name</span>

<input type="text" aria-labelledby="de sd">

GCC dump preprocessor defines

I usually do it this way:

$ gcc -dM -E - < /dev/null

Note that some preprocessor defines are dependent on command line options - you can test these by adding the relevant options to the above command line. For example, to see which SSE3/SSE4 options are enabled by default:

$ gcc -dM -E - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSSE3__ 1

and then compare this when -msse4 is specified:

$ gcc -dM -E -msse4 - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSE4_1__ 1
#define __SSE4_2__ 1
#define __SSSE3__ 1

Similarly you can see which options differ between two different sets of command line options, e.g. compare preprocessor defines for optimisation levels -O0 (none) and -O3 (full):

$ gcc -dM -E -O0 - < /dev/null > /tmp/O0.txt
$ gcc -dM -E -O3 - < /dev/null > /tmp/O3.txt
$ sdiff -s /tmp/O0.txt /tmp/O3.txt 
#define __NO_INLINE__ 1        <
                               > #define __OPTIMIZE__ 1

Difference between request.getSession() and request.getSession(true)

request.getSession() will return a current session. if current session does not exist, then it will create a new one.

request.getSession(true) will return current session. If current session does not exist, then it will create a new session.

So basically there is not difference between both method.

request.getSession(false) will return current session if current session exists. If not, it will not create a new session.

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

python: urllib2 how to send cookie with urlopen request

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookies section of quickstart guide:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Encode String to UTF-8

A Java String is internally always encoded in UTF-16 - but you really should think about it like this: an encoding is a way to translate between Strings and bytes.

So if you have an encoding problem, by the time you have String, it's too late to fix. You need to fix the place where you create that String from a file, DB or network connection.

Install Android App Bundle on device

For MAC:

brew install bundletool
bundletool build-apks --bundle=./app.aab --output=./app.apks
bundletool install-apks --apks=app.apks

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

TypeError: a bytes-like object is required, not 'str' in python and CSV

You are using Python 2 methodology instead of Python 3.

Change:

outfile=open('./immates.csv','wb')

To:

outfile=open('./immates.csv','w')

and you will get a file with the following output:

SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....

In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.

Edited to Add

Here is the code I ran:

url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
    list_of_cells=[]
    for cell in row.findAll('td'):
        list_of_cells.append(cell.text)
    list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)

Ruby: What is the easiest way to remove the first element from an array?

[0, 132, 432, 342, 234][1..-1]
=> [132, 432, 342, 234]

So unlike shift or slice this returns the modified array (useful for one liners).

Passing just a type as a parameter in C#

There are two common approaches. First, you can pass System.Type

object GetColumnValue(string columnName, Type type)
{
    // Here, you can check specific types, as needed:

    if (type == typeof(int)) { // ...

This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));

The other option would be to use generics:

T GetColumnValue<T>(string columnName)
{
    // If you need the type, you can use typeof(T)...

This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I had the same issue - it sorted itself out in ~3 hours after I uploaded the app to the Play console. According to Google:

Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.

While the message is not the same, I suspect the root cause to be the same.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Its possible at application level. Click on the EJB under the deployment(like Home > >Summary of Deployments >). Click on the Configuration tab and there is "Transaction Timeout:"

Java Class that implements Map and keeps insertion order?

You can use LinkedHashMap to main insertion order in Map

The important points about Java LinkedHashMap class are:

  1. It contains onlyunique elements.
  2. A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order

    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
    

But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link

NavigationBar bar, tint, and title text color in iOS 8

Updated with swift 4

override func viewDidLoad() {
    super.viewDidLoad()
        self.navigationController?.navigationBar.tintColor = UIColor.blue
        self.navigationController?.navigationBar.barStyle = UIBarStyle.black
}

How to fix "unable to write 'random state' " in openssl

Or this in windows powershell

$env:RANDFILE=".rnd"

Is JavaScript a pass-by-reference or pass-by-value language?

I've read through these answers multiple times, but didn't REALLY get it until I learned about the technical definition of "Call by sharing" as termed by Barbara Liskov

The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller (unlike by reference semantics)[citation needed], so e.g. if a variable was passed, it is not possible to simulate an assignment on that variable in the caller's scope. However, since the function has access to the same object as the caller (no copy is made), mutations to those objects, if the objects are mutable, within the function are visible to the caller, which may appear to differ from call by value semantics. Mutations of a mutable object within the function are visible to the caller because the object is not copied or cloned — it is shared.

That is, parameter references are alterable if you go and access the parameter value itself. On the other hand, assignment to a parameter will disappear after evaluation, and is non-accessible to the function caller.

Prevent div from moving while resizing the page

I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.

Or, you can set a min-width on elements like header, navigation, content etc.

Get UTC time in seconds

I bet this is what was intended as a result.

$ date -u --date=@1404372514
Thu Jul  3 07:28:34 UTC 2014

Android: Test Push Notification online (Google Cloud Messaging)

Pushwatch is a free to use online GCM and APNS push notification tester developed by myself in Django/Python as I have found myself in a similar situation while working on multiple projects. It can send both GCM and APNS notifications and also support JSON messages for extra arguments. Following are the links to the testers.

Please let me know if you have any questions or face issues using it.

How to wait till the response comes from the $http request, in angularjs?

You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {

    var getData = function() {

        // Angular $http() and then() both return promises themselves 
        return $http({method:"GET", url:"/my/url"}).then(function(result){

            // What we return here is the data that will be accessible 
            // to us after the promise resolves
            return result.data;
        });
    };


    return { getData: getData };
});


function myFunction($scope, myService) {
    var myDataPromise = myService.getData();
    myDataPromise.then(function(result) {  

       // this is only run after getData() resolves
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });
}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) { 
    var myDataPromise = myService.getData(); 
    myDataPromise.then(function(result) { 
         $scope.data = result; 
         console.log("data.name"+$scope.data.name); 
    }); 
    console.log("This will get printed before data.name inside then. And I don't want that."); 
 }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

Reactjs convert html string to jsx

You can also use Parser() from html-react-parser. I have used the same. Link shared.

How to prevent scrollbar from repositioning web page?

I use to have that problem, but the simples way to fix it is this (this works for me):

on the CSS file type:

body{overflow-y:scroll;}

as that simple! :)

Add new row to excel Table (VBA)

I had the same problem before and i fixed it by creating the same table in a new sheet and deleting all the name ranges associated to the table, i believe whene you're using listobjects you're not alowed to have name ranges contained within your table hope that helps thanks

webpack is not recognized as a internal or external command,operable program or batch file

If you create a boilerplate folder for your JS projects so that you can use JS Modules, webpack and Babel are great tools.

Don't install webpack globally and after installing the most recent versions of both, your package.json file will be loaded up and ready to copy for future projects.

Make sure to delete the node_modules folder to decrease file size in your boilerplate folder and then to reinstall node_modules use npm install.

I forgot to run npm install and kept getting this error when trying to run my webpack dev-server until I realized I needed to run npm install to install node_modules and then it worked.

How do I resolve ClassNotFoundException?

  1. It could happen if your classpath is not correct

  2. Let us posit a serializable class and deserializable class under same projectname. You run the serializable class, creating a serializable object in specific folder. Now you need the desearialized data. In the meantime, if you change the name of the project it will not work. You have to run the serializable class first and then deserialize the file.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

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

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {
    background: #ccc
}

<div id="a">Div A</div>
<div id="b">Div B</div>

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {
    background: #ccc
}

<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

how to display employee names starting with a and then b in sql

select columns
  from table
 where (
         column like 'a%' 
      or column like 'b%' )
 order by column asc

How to fire an event when v-model changes?

This happens because your click handler fires before the value of the radio button changes. You need to listen to the change event instead:

<input 
  type="radio" 
  name="optionsRadios" 
  id="optionsRadios2" 
  value=""
  v-model="srStatus" 
  v-on:change="foo"> //here

Also, make sure you really want to call foo() on ready... seems like maybe you don't actually want to do that.

ready:function(){
    foo();
},

How to add a string to a string[] array? There's no .Add function

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

Array.push() if does not exist?

http://api.jquery.com/jQuery.unique/

var cleanArray = $.unique(clutteredArray);

you might be interested in makeArray too

The previous example is best in saying that check if it exists before pushing. I see in hindsight it also states you can declare it as part of the prototype (I guess that's aka Class Extension), so no big enhancement below.

Except I'm not sure if indexOf is a faster route then inArray? probably.

Array.prototype.pushUnique = function (item){
    if(this.indexOf(item) == -1) {
    //if(jQuery.inArray(item, this) == -1) {
        this.push(item);
        return true;
    }
    return false;
}

Load jQuery with Javascript and use jQuery

From the DevTools console, you can run:

document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';

Check the available jQuery version at https://code.jquery.com/jquery/.

To check whether it's loaded, see: Checking if jquery is loaded using Javascript.

Is multiplication and division using shift operators in C actually faster?

Python test performing same multiplication 100 million times against the same random numbers.

>>> from timeit import timeit
>>> setup_str = 'import scipy; from scipy import random; scipy.random.seed(0)'
>>> N = 10*1000*1000
>>> timeit('x=random.randint(65536);', setup=setup_str, number=N)
1.894096851348877 # Time from generating the random #s and no opperati

>>> timeit('x=random.randint(65536); x*2', setup=setup_str, number=N)
2.2799630165100098
>>> timeit('x=random.randint(65536); x << 1', setup=setup_str, number=N)
2.2616429328918457

>>> timeit('x=random.randint(65536); x*10', setup=setup_str, number=N)
2.2799630165100098
>>> timeit('x=random.randint(65536); (x << 3) + (x<<1)', setup=setup_str, number=N)
2.9485139846801758

>>> timeit('x=random.randint(65536); x // 2', setup=setup_str, number=N)
2.490908145904541
>>> timeit('x=random.randint(65536); x / 2', setup=setup_str, number=N)
2.4757170677185059
>>> timeit('x=random.randint(65536); x >> 1', setup=setup_str, number=N)
2.2316000461578369

So in doing a shift rather than multiplication/division by a power of two in python, there's a slight improvement (~10% for division; ~1% for multiplication). If its a non-power of two, there's likely a considerable slowdown.

Again these #s will change depending on your processor, your compiler (or interpreter -- did in python for simplicity).

As with everyone else, don't prematurely optimize. Write very readable code, profile if its not fast enough, and then try to optimize the slow parts. Remember, your compiler is much better at optimization than you are.

Appending a byte[] to the end of another byte[]

Perhaps the easiest way:

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write(ciphertext);
output.write(mac);

byte[] out = output.toByteArray();

How to iterate over rows in a DataFrame in Pandas

There are so many ways to iterate over the rows in Pandas dataframe. One very simple and intuitive way is:

df = pd.DataFrame({'A':[1, 2, 3], 'B':[4, 5, 6], 'C':[7, 8, 9]})
print(df)
for i in range(df.shape[0]):
    # For printing the second column
    print(df.iloc[i, 1])

    # For printing more than one columns
    print(df.iloc[i, [0, 2]])

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

I like Keith Hill's answer except it has a bug that prevents it from recursing past two levels. These commands manifest the bug:

New-Item level1/level2/level3/level4/foobar.txt -Force -ItemType file
cd level1
GetFiles . xyz | % { $_.fullname }

With Hill's original code you get this:

...\level1\level2
...\level1\level2\level3

Here is a corrected, and slightly refactored, version:

function GetFiles($path = $pwd, [string[]]$exclude)
{
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        $item
        if (Test-Path $item.FullName -PathType Container)
        {
            GetFiles $item.FullName $exclude
        }
    }
} 

With that bug fix in place you get this corrected output:

...\level1\level2
...\level1\level2\level3
...\level1\level2\level3\level4
...\level1\level2\level3\level4\foobar.txt

I also like ajk's answer for conciseness though, as he points out, it is less efficient. The reason it is less efficient, by the way, is because Hill's algorithm stops traversing a subtree when it finds a prune target while ajk's continues. But ajk's answer also suffers from a flaw, one I call the ancestor trap. Consider a path such as this that includes the same path component (i.e. subdir2) twice:

\usr\testdir\subdir2\child\grandchild\subdir2\doc

Set your location somewhere in between, e.g. cd \usr\testdir\subdir2\child, then run ajk's algorithm to filter out the lower subdir2 and you will get no output at all, i.e. it filters out everything because of the presence of subdir2 higher in the path. This is a corner case, though, and not likely to be hit often, so I would not rule out ajk's solution due to this one issue.

Nonetheless, I offer here a third alternative, one that does not have either of the above two bugs. Here is the basic algorithm, complete with a convenience definition for the path or paths to prune--you need only modify $excludeList to your own set of targets to use it:

$excludeList = @("stuff","bin","obj*")
Get-ChildItem -Recurse | % {
    $pathParts = $_.FullName.substring($pwd.path.Length + 1).split("\");
    if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $_ }
}

My algorithm is reasonably concise but, like ajk's, it is less efficient than Hill's (for the same reason: it does not stop traversing subtrees at prune targets). However, my code has an important advantage over Hill's--it can pipeline! It is therefore amenable to fit into a filter chain to make a custom version of Get-ChildItem while Hill's recursive algorithm, through no fault of its own, cannot. ajk's algorithm can be adapted to pipeline use as well, but specifying the item or items to exclude is not as clean, being embedded in a regular expression rather than a simple list of items that I have used.

I have packaged my tree pruning code into an enhanced version of Get-ChildItem. Aside from my rather unimaginative name--Get-EnhancedChildItem--I am excited about it and have included it in my open source Powershell library. It includes several other new capabilities besides tree pruning. Furthermore, the code is designed to be extensible: if you want to add a new filtering capability, it is straightforward to do. Essentially, Get-ChildItem is called first, and pipelined into each successive filter that you activate via command parameters. Thus something like this...

Get-EnhancedChildItem –Recurse –Force –Svn
    –Exclude *.txt –ExcludeTree doc*,man -FullName -Verbose 

... is converted internally into this:

Get-ChildItem | FilterExcludeTree | FilterSvn | FilterFullName

Each filter must conform to certain rules: accepting FileInfo and DirectoryInfo objects as inputs, generating the same as outputs, and using stdin and stdout so it may be inserted in a pipeline. Here is the same code refactored to fit these rules:

filter FilterExcludeTree()
{
  $target = $_
  Coalesce-Args $Path "." | % {
    $canonicalPath = (Get-Item $_).FullName
    if ($target.FullName.StartsWith($canonicalPath)) {
      $pathParts = $target.FullName.substring($canonicalPath.Length + 1).split("\");
      if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $target }
    }
  }
} 

The only additional piece here is the Coalesce-Args function (found in this post by Keith Dahlby), which merely sends the current directory down the pipe in the event that the invocation did not specify any paths.

Because this answer is getting somewhat lengthy, rather than go into further detail about this filter, I refer the interested reader to my recently published article on Simple-Talk.com entitled Practical PowerShell: Pruning File Trees and Extending Cmdlets where I discuss Get-EnhancedChildItem at even greater length. One last thing I will mention, though, is another function in my open source library, New-FileTree, that lets you generate a dummy file tree for testing purposes so you can exercise any of the above algorithms. And when you are experimenting with any of these, I recommend piping to % { $_.fullname } as I did in the very first code fragment for more useful output to examine.

Is it possible to get only the first character of a String?

Use ld.charAt(0). It will return the first char of the String.

With ld.substring(0, 1), you can get the first character as String.

Get a DataTable Columns DataType

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt : DataTable object.

0 : DataTable column index.

Hope It Helps

Ty :)

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

How to increase font size in the Xcode editor?

I found that in the Preferences, there is no fonts and colors selection. Guess the version is different, following is the one that works for the latest version.

Method 1

enter image description here

  • Go to Xcode -> Preferences
  • Click Themes
  • Click the T symbol in the middle of the font
  • Adjust the size at the bottom right corner

Method 2

Simply adjust with cmd + or cmd -

EditText, inputType values (xml)

android:inputMethod

is deprecated, instead use inputType :

 android:inputType="numberPassword"

How do you install an APK file in the Android emulator?

keep your emulator up and running. In the command line, go inside the platform-tools folder, in your sdk folder which come with adt bundle and execute following command :

>adb install <yourFilename.apk>

This command detect your running emulator/emulators and show you the list of devices where you can install this app(show if any physical device/devices connected to your computer.). Then you can select any one, if only one emulator is running then app will directly installed on it by default.

Note: For above command your .apk file needs to be in same directory.

for more detailed tutorial follo : This link

Constants in Objective-C

If you want something like global constants; a quick an dirty way is to put the constant declarations into the pch file.

Hibernate error: ids for this class must be manually assigned before calling save():

Here is what I did to solve just by 2 ways:

  1. make ID column as int type

  2. if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)

  3. try using @GeneratedValue(strategy=GenerationType.SEQUENCE) if possible

What is the best java image processing library/approach?

Try to use Catalano Framework.

Keypoints:

  • Architecture like AForge.NET/Accord.NET.
  • Run in the both environments with the same code, desktop and Android.
  • Contains several filters in parallel.
  • Development is on full steam.

The Catalano Framework is a framework for scientific computing for Java and Android. The project started as an initial port of the many features of the AForge.NET and Accord.NET frameworks for .NET, but is steadily growing with more advanced features which are now being shared between those projects.

Example:

FastBitmap fb = new FastBitmap(bitmap);

Grayscale g = new Grayscale();
g.applyInPlace(fb);

Threshold t = new Threshold(120);
t.applyInPlace(fb);

bitmap = fb.toBitmap();

//Show the result

How can I resize an image dynamically with CSS as the browser width/height changes?

You can use CSS3 scale property to resize image with css:

.image:hover {
  -webkit-transform:scale(1.2); 
          transform:scale(1.2);
}
.image {
  -webkit-transition: all 0.7s ease; 
          transition: all 0.7s ease;
}

Further Reading:

Sum a list of numbers in Python

All answers did show a programmatic and general approach. I suggest a mathematical approach specific for your case. It can be faster in particular for long lists. It works because your list is a list of natural numbers up to n:

Let's assume we have the natural numbers 1, 2, 3, ..., 10:

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You can use the sum function on a list:

>>> print sum(nat_seq)
55

You can also use the formula n*(n+1)/2 where n is the value of the last element in the list (here: nat_seq[-1]), so you avoid iterating over elements:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

To generate the sequence (1+2)/2, (2+3)/2, ..., (9+10)/2 you can use a generator and the formula (2*k-1)/2. (note the dot to make the values floating points). You have to skip the first element when generating the new list:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

Here too, you can use the sum function on that list:

>>> print sum(new_seq)
49.5

But you can also use the formula (((n*2+1)/2)**2-1)/2, so you can avoid iterating over elements:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5