std
namespace (where features of the C++ Standard Library, such as string
or vector
, are declared).After you write this instruction, if the compiler sees string
it will know that you may be referring to std::string
, and if it sees vector
, it will know that you may be referring to std::vector
. (Provided that you have included in your compilation unit the header files where they are defined, of course.)
If you don't write it, when the compiler sees string
or vector
it will not know what you are refering to. You will need to explicitly tell it std::string
or std::vector
, and if you don't, you will get a compile error.
If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, List<String>> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
I know this is old but I've used a function similar to this...
deleteRow: function (ctrl) {
//remove the row from the table
$(ctrl).closest('tr').remove();
}
... with markup like this ...
<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>
...and it works fine
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.
Building on RobertoNovelo's answer:
import * as fs from 'fs';
is currently the simplest way to do it.
It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import
.
After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:
10
but you want it to return a String and not a Fixnum, write '10'
or "10"
.:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, \
).'\n'
would be returned as the string \n
."\n"
would be returned as a line feed character.!ruby/sym
to return a Ruby symbol.Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.
Update
"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:
en:
yesno:
'yes': 'Yes'
'no': 'No'
If you haven't push the deletion yet, you can simply do :
$ git checkout deletedBranchName
simple load xml file ..
$xml = @simplexml_load_string($retValuet);
$status = (string)$xml->Status;
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;
?>
For What its worth, this is what I did and maybe it can help others even though the article is old.
PHP:
session_start();
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['userID'])){
if(!strpos($_SESSION['activeID'], '-')){
$_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID'];
}
}elseif(!isset($_SESSION['activeID'])){
$_SESSION['activeID'] = time();
}
JS
window.setInterval(function(){
var userid = '<?php echo $_SESSION['activeID']; ?>';
var ipaddress = '<?php echo $_SESSION['ipaddress']; ?>';
var action = 'data';
$.ajax({
url:'activeUser.php',
method:'POST',
data:{action:action,userid:userid,ipaddress:ipaddress},
success:function(response){
//alert(response);
}
});
}, 5000);
Ajax call to activeUser.php
if(isset($_POST['action'])){
if(isset($_POST['userid'])){
$stamp = time();
$activeid = $_POST['userid'];
$ip = $_POST['ipaddress'];
$query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1";
$results = RUNSIMPLEDB($query);
if($results->num_rows > 0){
$query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1";
RUNSIMPLEDB($query);
}else{
$query = "INSERT INTO activeusers (activeid,stamp,ip)
VALUES ('".$activeid."','$stamp','$ip')";
RUNSIMPLEDB($query);
}
}
}
Database:
CREATE TABLE `activeusers` (
`id` int(11) NOT NULL,
`activeid` varchar(20) NOT NULL,
`stamp` int(11) NOT NULL,
`ip` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.
Probably not the most efficient solution but it does the job.
Auto reload with target of your choice. In this case target is _self
set to every 5 minutes.
300000 milliseconds = 300 seconds = 5 minutes
as 60000 milliseconds = 60 seconds = 1 minute.
This is how you do it:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">
The following assumes command-line access via iTerm / Terminal to bitbucket.
For MacOS Sierra 10.12.5, my system manifested an equivalent problem - asking for my SSH passphrase on each connection to bitbucket.
The issue has to do with OpenSSH updates in macOS 10.12.2, which are described here in Technical Note TN2449.
You very well might want to tailor your solution, but the following will work when added to your ~/.ssh/config file:
Host *
UseKeychain yes
For more information on ssh configs, take a look at the man pages for ssh_config:
% man ssh_config
One other thing: there is a good write-up on superuser here that discusses this problem and various solutions depending on your needs and setup.
For example, if you want an array of int
pointers it will be int* a[10]
. It means that variable a
is a collection of 10 int*
s.
EDIT
I guess this is what you want to do:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
This solution is no more supported since jQuery 1.8 as we can read on the blog here:
$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.
So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).
If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.
But as a developer, I will not recommend this type of practices. WHY?
answer to why is already given by Pascal Thivent in the comment of the question
I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.
I will recommend this type of practice:
<properties>
<spring.version>3.1.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
it is easy to maintain and easy to debug. You can update your POM in no time.
If you're using SonarLint, try above the method or class the whole squid string: @SuppressWarnings("squid:S1172")
Browser technology currently doesn't support downloading a file directly from an Ajax request. The work around is to add a hidden form and submit it behind the scenes to get the browser to trigger the Save dialog.
I'm running a standard Flux implementation so I'm not sure what the exact Redux (Reducer) code should be, but the workflow I just created for a file download goes like this...
FileDownload
. All this component does is render a hidden form and then, inside componentDidMount
, immediately submit the form and call it's onDownloadComplete
prop.Widget
, with a download button/icon (many actually... one for each item in a table). Widget
has corresponding action and store files. Widget
imports FileDownload
.Widget
has two methods related to the download: handleDownload
and handleDownloadComplete
.Widget
store has a property called downloadPath
. It's set to null
by default. When it's value is set to null
, there is no file download in progress and the Widget
component does not render the FileDownload
component.Widget
calls the handleDownload
method which triggers a downloadFile
action. The downloadFile
action does NOT make an Ajax request. It dispatches a DOWNLOAD_FILE
event to the store sending along with it the downloadPath
for the file to download. The store saves the downloadPath
and emits a change event.downloadPath
, Widget
will render FileDownload
passing in the necessary props including downloadPath
as well as the handleDownloadComplete
method as the value for onDownloadComplete
.FileDownload
is rendered and the form is submitted with method="GET"
(POST should work too) and action={downloadPath}
, the server response will now trigger the browser's Save dialog for the target download file (tested in IE 9/10, latest Firefox and Chrome).onDownloadComplete
/handleDownloadComplete
is called. This triggers another action that dispatches a DOWNLOAD_FILE
event. However, this time downloadPath
is set to null
. The store saves the downloadPath
as null
and emits a change event.downloadPath
the FileDownload
component is not rendered in Widget
and the world is a happy place.Widget.js - partial code only
import FileDownload from './FileDownload';
export default class Widget extends Component {
constructor(props) {
super(props);
this.state = widgetStore.getState().toJS();
}
handleDownload(data) {
widgetActions.downloadFile(data);
}
handleDownloadComplete() {
widgetActions.downloadFile();
}
render() {
const downloadPath = this.state.downloadPath;
return (
// button/icon with click bound to this.handleDownload goes here
{downloadPath &&
<FileDownload
actionPath={downloadPath}
onDownloadComplete={this.handleDownloadComplete}
/>
}
);
}
widgetActions.js - partial code only
export function downloadFile(data) {
let downloadPath = null;
if (data) {
downloadPath = `${apiResource}/${data.fileName}`;
}
appDispatcher.dispatch({
actionType: actionTypes.DOWNLOAD_FILE,
downloadPath
});
}
widgetStore.js - partial code only
let store = Map({
downloadPath: null,
isLoading: false,
// other store properties
});
class WidgetStore extends Store {
constructor() {
super();
this.dispatchToken = appDispatcher.register(action => {
switch (action.actionType) {
case actionTypes.DOWNLOAD_FILE:
store = store.merge({
downloadPath: action.downloadPath,
isLoading: !!action.downloadPath
});
this.emitChange();
break;
FileDownload.js
- complete, fully functional code ready for copy and paste
- React 0.14.7 with Babel 6.x ["es2015", "react", "stage-0"]
- form needs to be display: none
which is what the "hidden" className
is for
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';
function getFormInputs() {
const {queryParams} = this.props;
if (queryParams === undefined) {
return null;
}
return Object.keys(queryParams).map((name, index) => {
return (
<input
key={index}
name={name}
type="hidden"
value={queryParams[name]}
/>
);
});
}
export default class FileDownload extends Component {
static propTypes = {
actionPath: PropTypes.string.isRequired,
method: PropTypes.string,
onDownloadComplete: PropTypes.func.isRequired,
queryParams: PropTypes.object
};
static defaultProps = {
method: 'GET'
};
componentDidMount() {
ReactDOM.findDOMNode(this).submit();
this.props.onDownloadComplete();
}
render() {
const {actionPath, method} = this.props;
return (
<form
action={actionPath}
className="hidden"
method={method}
>
{getFormInputs.call(this)}
</form>
);
}
}
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.
In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.
- Florina Muntenescu (source)
build.gradle
android {
// [...]
defaultConfig {
// [...]
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
// add the schema location to the source sets
// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
// [...]
}
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...
I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.
For example:
$("#id_form").on("submit", function(){
//Code: Action (like ajax...)
return false;
})
You can simply do this with a bool:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
Try to look at KEYS
command. KEYS *
will list all keys stored in redis.
EDIT: please note the warning at the top of KEYS
documentation page:
Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.
UPDATE (V2.8 or greater): SCAN
is a superior alternative to KEYS
, in the sense that it does not block the server nor does it consume significant resources. Prefer using it.
// 1. remove duplicate item
// 2. flat array
let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
let result = Array.from(new Set(arr.flat(Infinity)));
console.log(`flat array with unique filter`, result);
//
// 1. remove duplicate item_x000D_
// 2. sort by Asc order (munber only)_x000D_
// 3. flat array_x000D_
_x000D_
// let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];_x000D_
_x000D_
let arr= [["6", ["18"]], ["6"], ["12"], ["25"], ["25"], ["18"], ["22"], ["10"]];_x000D_
_x000D_
let result = Array.from(new Set(arr.flat(Infinity))).map(Number).sort((a,b)=> a > b ? 1: -1);_x000D_
_x000D_
console.log(`flat array with unique filter & Asc sort`, result);_x000D_
//
_x000D_
// 1. remove duplicate item
// 2. flat array
let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
let result = [...new Set(arr.flat(Infinity))];
console.log(`flat array with unique filter`, result);
//
// 1. remove duplicate item_x000D_
// 2. sort by Asc order(number only)_x000D_
// 3. flat array_x000D_
_x000D_
//let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];_x000D_
_x000D_
let arr= [["6", ["18"]], ["6"], ["12"], ["25"], ["25"], ["18"], ["22"], ["10"]];_x000D_
_x000D_
let result = [...new Set(arr.flat(Infinity))].map(Number).sort((a,b)=> a > b ? 1: -1);_x000D_
_x000D_
console.log(`flat array with unique filter & Asc sort`, result);_x000D_
//
_x000D_
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
In the event you have to solve the problem with simple SQL you might use an inline view.
select count(*) from (select * from foo) as x;
You can try to do what you're doing by manually loading the images, but I would very very strongly recommend taking a look at Universal Image Loader.
I recently integrated it into my project and I have to say its fantastic. Does all the worrying about making things asynchronous, resizing, caching images for you. It's really easy to integrate and set up. Within 5 minutes you can probably get it doing what you want.
Example code:
//ImageLoader config
DisplayImageOptions displayimageOptions = new DisplayImageOptions.Builder().showStubImage(R.drawable.downloadplaceholder).cacheInMemory().cacheOnDisc().showImageOnFail(R.drawable.loading).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).
defaultDisplayImageOptions(displayimageOptions).memoryCache(new WeakMemoryCache()).discCache(new UnlimitedDiscCache(cacheDir)).build();
if (ImageLoader.getInstance().isInited()) {
ImageLoader.getInstance().destroy();
}
ImageLoader.getInstance().init(config);
imageLoadingListener = new ImageLoadingListener() {
@Override
public void onLoadingStarted(String s, View view) {
}
@Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
ImageView imageView = (ImageView) view;
imageView.setImageResource(R.drawable.android);
Log.i("Failed to Load " + s, failReason.toString());
}
@Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
}
@Override
public void onLoadingCancelled(String s, View view) {
}
};
//Imageloader usage
ImageView imageView = new ImageView(getApplicationContext());
if (orientation == 1) {
imageView.setLayoutParams(new LinearLayout.LayoutParams(width / 6, width / 6));
} else {
imageView.setLayoutParams(new LinearLayout.LayoutParams(height / 6, height / 6));
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageLoader.displayImage(SERVER_HOSTNAME + "demos" + demo.getPathRoot() + demo.getRootName() + ".png", imageView, imageLoadingListener);
This can lazy load the images, fit them correctly to the size of the imageView showing a placeholder image while it loads, and showing a default icon if loading fails and caching the resources.
-- I should also add that this current config keeps the image aspect ratio, hence applicable to your original question
Another date format
select datediff(day,'20110101','20110301')
This works fine. just insert your jquery code in document.ready function.
$(document).ready(function(e) {
// your code here
});
example:
$(document).ready(function(e) {
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
});
});
<div>
<select id='canselect_code' name='canselect_code' multiple class='fl'>
<option value='1'>toto</option>
<option value='2'>titi</option>
</select>
<input type='button' id='btnRight_code' value=' > ' />
<br>
<input type='button' id='btnLeft_code' value=' < ' />
<select id='isselect_code' name='isselect_code' multiple class='fr'>
<option value='3'>tata</option>
<option value='4'>tutu</option>
</select>
</div>
Try this
$(function() {
$('#clickMe').click(function(event) {
var mytext = $('#myText').val();
$('<div id="dialog">'+mytext+'</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#dialog").remove();
}
});
}); //close click
});
And in HTML
<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>
You can certainly do something like
SQL> ed
Wrote file afiedt.buf
1 begin
2 for d in (select * from dept)
3 loop
4 for e in (select * from emp where deptno=d.deptno)
5 loop
6 dbms_output.put_line( 'Employee ' || e.ename ||
7 ' in department ' || d.dname );
8 end loop;
9 end loop;
10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
Or something equivalent using explicit cursors.
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor dept_cur
3 is select *
4 from dept;
5 d dept_cur%rowtype;
6 cursor emp_cur( p_deptno IN dept.deptno%type )
7 is select *
8 from emp
9 where deptno = p_deptno;
10 e emp_cur%rowtype;
11 begin
12 open dept_cur;
13 loop
14 fetch dept_cur into d;
15 exit when dept_cur%notfound;
16 open emp_cur( d.deptno );
17 loop
18 fetch emp_cur into e;
19 exit when emp_cur%notfound;
20 dbms_output.put_line( 'Employee ' || e.ename ||
21 ' in department ' || d.dname );
22 end loop;
23 close emp_cur;
24 end loop;
25 close dept_cur;
26* end;
27 /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of
FOR x IN (SELECT *
FROM all_users,
org
WHERE length(all_users.username) = 3
AND all_users.username = org.username )
LOOP
<<do something>>
END LOOP;
You may be able to use an approximate string matching library to do this, e.g. SecondString, but that is almost certainly overkill - just use one of the for-loop answers provided instead.
Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.
package com.zenimax.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Matthew H. Wagner
*/
public class TripleDesBouncyCastle {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private static void init()
{
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] encode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
return encrypter.doFinal(input);
}
public static byte[] decode(byte[] input, byte[] key)
throws IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, InvalidKeyException {
init();
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
return decrypter.doFinal(input);
}
}
Also note that a result code in the second column refers to the properties of the file. For example:
U filename.1
U filename.2
UU filename.3
filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated
-- Microsoft SQL Server 2008 Standard Edition:
IF EXISTS(SELECT 1
FROM msdb.dbo.sysjobs J
JOIN msdb.dbo.sysjobactivity A
ON A.job_id=J.job_id
WHERE J.name=N'Your Job Name'
AND A.run_requested_date IS NOT NULL
AND A.stop_execution_date IS NULL
)
PRINT 'The job is running!'
ELSE
PRINT 'The job is not running.'
you can even create a function to return different time stamps depending on your necessity:
func dataatual(_ tipo:Int) -> String {
let date = Date()
let formatter = DateFormatter()
if tipo == 1{
formatter.dateFormat = "dd/MM/yyyy"
} else if tipo == 2{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
} else {
formatter.dateFormat = "dd-MM-yyyy"
}
return formatter.string(from: date)
}
Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule
.
You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
View getView(int position, View convertView, ViewGroup parent);
Try this:
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;
First of all: The UIBezierPath
used as shadowPath
is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.
Regarding your issue specifically: The important line is view.layer.masksToBounds = NO
. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.
For those wondering what the difference between masksToBounds
(on the layer) and the view's own clipToBounds
property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.
Swift 2.2:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSizeMake(0.0, 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.CGPath
}
Swift 3:
override func layoutSubviews()
{
super.layoutSubviews()
let shadowPath = UIBezierPath(rect: bounds)
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
layer.shadowOpacity = 0.5
layer.shadowPath = shadowPath.cgPath
}
If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:
Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.
This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm
<style type="text/css">
.input input {
float: left;
}
.input label {
margin: 5px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
You can use both .content and .container to overflow:auto. Means if it's text is exceed automatically scroll will come x-axis and y-axis. (no need to give separete x-axis and y-axis commonly give overflow:auto)
.content {overflow:auto;}
I made the same error using sudo for my installation. (oops)
brew install python
brew linkapps python
brew link --overwrite python
This brought everything back to normal.
To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});
In C, you can use the built in qsort
command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
if ( int_a == int_b ) return 0;
else if ( int_a < int_b ) return -1;
else return 1;
}
qsort( a, 6, sizeof(int), compare )
see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.
As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort
There is another solution for this.
Consider the quotes as part of the fields delimiter, by editing the fmt file.
You can check this out for more information:
An extract of the link above:
The only way to remove the quotation marks would be to modify the column delimiters specified during the import operation. The only drawback here is that if you inspect the data to be inserted, you will very quickly realize that the column delimiters are different for each column (Delimiters highlighted above).
So to specify different column delimiters for each column, you would need to use a format file if you plan to use Bulk Insert or BCP. If you generate a format file for the above table structure, it would be as follows:
9.0
3
1 SQLCHAR 0 5 "\t" 1 FName SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 5 "\t" 2 LName SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 50 "\r\n" 3 Company SQL_Latin1_General_CP1_CI_AS
Modify the format file to represent the correct column delimiters for each column. The new format file to be used will look like this:
9.0
4
1 SQLCHAR 0 0 "\"" 0 FIRST_QUOTE SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 5 "\",\"" 1 FNAME SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 5 "\",\"" 2 LNAME SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 50 "\"\r\n" 3 COMPANY SQL_Latin1_General_CP1_CI_AS
Try this.. credits to https://stackoverflow.com/users/1169519/teemu
for answering my question here: https://stackoverflow.com/questions/24651811/jquery-keyup-doesnt-work-with-keycode-filtering?noredirect=1#comment38213480_24651811
This solution helped me to progress on my project.
$("#your_textbox").on("input propertychange",function(){
// Do your thing here.
});
Note: propertychange for lower versions of IE.
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
You can set the value property using client script after the element is created:
<input type="text" id="fee" />
<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>
Running Visual Studio as administrator could fix the issue, but if you use Visual Studio with for example TortoiseSVN, you cannot commit any changes. Another possible solution would be to run the service as administrator and the rest Visual Studio as local user.
Replace:
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
with:
System.out.println("Enter EmployeeName:");
ename=(scanner.nextLine());
This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
It depends on what format you put on the datepicker So first we gave it the format.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd;
}
if(mm<10){
mm='0'+mm;
}
var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want
Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )
//Datetimepicker
$(function () {
$('#datetimepicker1').datetimepicker({
minDate: today, //pass today's date
daysOfWeekDisabled: [0],
locale: 'es',
inline: true,
format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)
sideBySide: true
});
});
Just put "?" in your shell script. In the correct locale and on a Unicode-enabled console it'll print just fine:
$ echo ?
?
$
An ugly "workaround" would be to output the UTF-8 sequence, but that also depends on the encoding used:
$ echo -e '\xE2\x98\xA0'
?
$
There are two issues here:
To overcome this, disable the button after the JavaScript onclick
event. An easy way to do this is to use setTimeout
as suggested by this answer.
Also, the OnClientClick
code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid
. This ensures that the button will not be disabled if validation fails.
OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"
It's neater to put all of this JavaScript code in its own function as the question shows:
OnClientClick="disable(this);"
function disable(button) {
setTimeout(function () {
if (Page_IsValid)
button.disabled = true;
}, 0);
}
To overcome this, disable the button on the server side. For example, in the OnClick
event handler:
OnClick="Button1_Click"
protected void Button1_Click(object sender, EventArgs e)
{
((Button)sender).Enabled = false;
}
Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.
Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.
I followed almost the same instructions by @Mason G. Zhwiti , but had to instead navigate to this folder to find the SDK:
/Users/{my-username}/Library/Android/sdk
I'm using Android Studio v1.2.2 on Mac OS
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson
function and add contentType: 'application/json;charset=UTF-8'
to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
sometimes, you can use regex
>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
This issue occurred for me after installing a pod via Podfile and pod install
. After trying a bunch of different fixes I finally just imported the Pod manually (dragging the necessary files into my project) and that solved the problem.
My preference is to keep the formatting details with the view and not the viewmodel. So in MVC4/Razor:
@Html.TextBoxFor(model => model.DateTime, "{0:d}");
datetime format reference: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx
Then I have a JQuery datepicker bound to it, and that put's the date in as a different format...doh!
Looks like I need to set the datepicker's format to the same formatting.
So I'm storing the System.Globalization
formatting in a data-* attribute and collecting it when setting up the
@Html.TextBoxFor(
model => model.DateTime.Date,
"{0:d}",
new
{
@class = "datePicker",
@data_date_format=System.Globalization.CultureInfo
.CurrentUICulture.DateTimeFormat.ShortDatePattern
}));
And here's the sucky part: the formats of .net and datepicker do not match, so hackery is needed:
$('.datePicker').each(function(){
$(this).datepicker({
dateFormat:$(this).data("dateFormat").toLowerCase().replace("yyyy","yy")
});
});
that's kind of weak, but should cover a lot of cases.
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
Use datetime.replace
:
from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)
To use aliases on eloquent models modify your code like this:
Item
::from( 'items as items_alias' )
->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
->select( DB::raw( 'items_alias.*' ) )
->get();
This will automatically add table prefix to table names and returns an instance of Items
model. not a bare query result.
Adding DB::raw
prevents laravel from adding table prefixes to aliases.
try this formula in column E:
=IF( AND( ISNUMBER(D2), D2=G2), H2, "")
your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )
you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.
I hope you understand my explanation.
you can do this using __ import __ and chdir
def import_file(full_path_to_module):
try:
import os
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
save_cwd = os.getcwd()
os.chdir(module_dir)
module_obj = __import__(module_name)
module_obj.__file__ = full_path_to_module
globals()[module_name] = module_obj
os.chdir(save_cwd)
except Exception as e:
raise ImportError(e)
return module_obj
import_file('/home/somebody/somemodule.py')
Try this (subquery):
SELECT * FROM terms WHERE id IN
(SELECT term_id FROM terms_relation WHERE taxonomy = "categ")
Or you can try this (JOIN):
SELECT t.* FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you want to receive all fields from two tables:
SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at
FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
Here's what I did to get small grey blocks to be on the left side and in the center of the text with an increased lineheight:
line-height:200%;
padding-left:13px;
background-image:url('images/greyblock.gif');
background-repeat:no-repeat;
background-position:left center;
Hope this helps someone :D
the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.
next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.
in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.
i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (
Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:
module.directive('myDirectiveContainer', function () {
return {
controller: function ($scope) {
this.scope = $scope;
}
};
});
module.directive('myDirective', function () {
return {
require: '^myDirectiveContainer',
link: function (scope, element, attrs, containerController) {
// use containerController.scope here...
}
};
});
and then
<div my-directive-container="">
<div my-directive="">
</div>
</div>
Maybe not the most graceful solution, but it got the job done.
There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.
to wit:
ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);
GO
UPDATE MyTable
SET NewColumnName = OldColumnName;
GO
ALTER TABLE CONTRACTS DROP COLUMN OldColumnName;
GO
EXEC sp_rename
@objname = 'MyTable.NewColumnName',
@newname = 'OldColumnName',
@objtype = 'COLUMN'
GO
This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.
We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.
Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.
This will help if you are connecting to some or all servers via a jump host server.
Earlier in my ~/.ssh/config file, my setting to connect were:
Host * !ssh.somejumphost.my.company.com
ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com
What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.
To FIX the issue, all I did was, change the config to ignore git server as well:
Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com
So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.
This seems quick for me :
comm -1 -3 <(sort file1.txt) <(sort file2.txt) > output.txt
On Centos 5 I was getting all sorts of errors trying to make changes to some variable values from the MySQL shell, after having logged in with the proper uid and pw (with root access). The error that I was getting was something like this:
mysql> -- Set some variable value, for example
mysql> SET GLOBAL general_log='ON';
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation
In a moment of extreme serendipity I did the following:
OS-Shell> sudo mysql # no DB uid, no DB pw
Kindly note that I did not provide the DB uid and password
mysql> show variables;
mysql> -- edit the variable of interest to the desired value, for example
mysql> SET GLOBAL general_log='ON';
It worked like a charm
To replace all spaces
:
UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')
To remove all tabs
characters :
UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )
To remove all new line
characters :
UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
To remove first and last space(s)
of column :
UPDATE `table` SET `col_name` = TRIM(`col_name`)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.
You can disable it later for development purposes and still get email field.
For static text:
For long text that needs to be updated once in a while:
For a number (formatted 00.0):
In your onDraw event only update the value variable sent to the shader.
precision highp float;
precision highp sampler2D;
uniform float uTime;
uniform float uValue;
uniform vec3 iResolution;
varying vec4 v_Color;
varying vec2 vTextureCoord;
uniform sampler2D s_texture;
void main() {
vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
vec2 uv = vTextureCoord;
float devisor = 10.75;
float digit;
float i;
float uCol;
float uRow;
if (uv.y < 0.45) {
if (uv.x > 0.75) {
digit = floor(uValue*10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
} else if (uv.x > 0.5) {
uCol = 4.0;
uRow = 1.0;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
} else if (uv.x > 0.25) {
digit = floor(uValue);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
} else if (uValue >= 10.0) {
digit = floor(uValue/10.0);
digit = digit - floor(digit/10.0)*10.0;
i = 48.0 - 32.0 + digit;
uRow = floor(i / 10.0);
uCol = i - 10.0 * uRow;
fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
} else {
fragColor = vec4(0.0, 0.0, 0.0, 0.0);
}
gl_FragColor = fragColor;
}
Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).
Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)
names(x)[names(x) %in% c("q","e")]<-c("A","B")
You need to remove the scanner closing lines: scan.close();
It happened to me before and that was the reason.
I tried some of the other answers here, but originalEvent was also undefined. Upon inspection, found a TouchList classed property (as suggested by another poster) and managed to get to pageX/Y this way:
var x = e.changedTouches[0].pageX;
Here's a nice trick to read JSON from s3:
import json, boto3
s3 = boto3.resource("s3").Bucket("bucket")
json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))
Now you can use json.load_s3
and json.dump_s3
with the same API as load
and dump
data = {"test":0}
json.dump_s3(data, "key") # saves json to s3://bucket/key
data = json.load_s3("key") # read json from s3://bucket/key
ALTER table table_name Drop column column1, Drop column column2,Drop column column3;
for MySQL DB.
Or you can add some column while altering in the same line:
ALTER table table_name Drop column column1, ADD column column2 AFTER column7;
When the page loads totally (dom, images, ...)
$(window).load(function(){
// full load
});
When DOM elements load (not necessary all images will be loaded)
$(function(){
// DOM Ready
});
Then you can trigger any event
$("element").trigger("event");
Actually, the Robustness Diagrams (or Analysis Diagrams, as they are sometimes called) are just specialized Class Diagrams. They are a part of UML, and have been from the beginning (see Jacobson's book, The Unified Software Development Process - part of the "Three Amigos" series of books). The aforementioned book has a good definition of these three classes on pp 183-185.
When you try to switch between two branches, this situation occurs.
Try to add the files using "git add filepath
".
Later execute this line
git stash --keep-index
Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.
The .ascx:
<script type="text/javascript">
function checkAgreement(source, args)
{
var elem = document.getElementById('<%= chkAgree.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
function checkAge(source, args)
{
var elem = document.getElementById('<%= chkAge.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />
<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAgreement">
You must agree to the terms and conditions.
</asp:CustomValidator>
<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAge">
You must be 18 years or older to continue.
</asp:CustomValidator>
And the codebehind:
Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
e.IsValid = chkAgree.Checked
End Sub
Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
e.IsValid = chkAge.Checked
End Sub
You can convert it to datetime
, and then use DATEADD(DAY, -30, date)
.
See here.
edit
I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:
DATEADD(DAY, -30, GETDATE())
Improve to @inno answer
delimiter //
DROP PROCEDURE IF EXISTS get_product;
CREATE PROCEDURE get_product()
BEGIN
DECLARE i VARCHAR(100);
DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO i;
SELECT i; -- printing table name
SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END LOOP read_loop;
CLOSE cur1;
END//
delimiter ;
call get_product();
Your class's constructor method should be called __construct()
, not __constructor()
:
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
Here it is in C# (lat and long in radians):
double CalculateGreatCircleDistance(double lat1, double long1, double lat2, double long2, double radius)
{
return radius * Math.Acos(
Math.Sin(lat1) * Math.Sin(lat2)
+ Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(long2 - long1));
}
If your lat and long are in degrees then divide by 180/PI to convert to radians.
It seems that it doesn't turn it into a string. Try
row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
Besides just using include()
or include_once()
to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:
In the site pages:
<?php
$PageTitle="New Page Title";
function customPageHeader(){?>
<!--Arbitrary HTML Tags-->
<?php }
include_once('header.php');
//body contents go here
include_once('footer.php');
?>
And, in the header.php file:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
<!-- Additional tags here -->
<?php if (function_exists('customPageHeader')){
customPageHeader();
}?>
</head>
<body>
Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.
Just do select date(timestamp_column)
and you would get the only the date part.
Sometimes doing select timestamp_column::date
may return date 00:00:00
where it doesn't remove the 00:00:00
part. But I have seen date(timestamp_column)
to work perfectly in all the cases. Hope this helps.
First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:
//Declaring
public EditText etPesquisa;
public ContasPagarAdapter adapterNormal;
public List<ContasPagar> lstBkp;
public List<ContasPagar> lstCp;
//Within the onCreate method, type the following:
etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);
etPesquisa.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
filter(String.valueOf(cs));
}
@Override
public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable e){
}
});
//Before moving objects to lists first initializes them as below:
lstCp = new ArrayList<ContasPagar>();
lstBkp = new ArrayList<ContasPagar>();
//When you add objects to the main list, repeat the procedure also for bkp list, as follows:
lstCp.add(cp);
lstBkp.add(cp);
//Now initializes the adapter and let the listener, as follows:
adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);
lvContasPagar.setAdapter(adapterNormal);
lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));
//Now create the methods inside actito filter the text entered by the user, as follows:
public void filter(String charText){
charText = charText.toLowerCase();
lstCp.clear();
if (charText.length() == 0){
lstCp.addAll(lstBkp);
appendAddItem(lstBkp);
}
else {
for (int i = 0; i < lstBkp.size(); i++){
if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){
lstCp.add(lstBkp.get(i));
}
}
appendAddItem(lstCp);
}
}
private void appendAddItem(final List<ContasPagar> novaLista){
runOnUiThread(new Runnable(){
@Override
public void run(){
adapterNormal.notifyDataSetChanged();
}
});
}
One way is to use the Extended State. This asks the underlying OS to maximize the JFrame.
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
Other approach would be to manually maximize the screen for you requirement.
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);
But this has pitfalls in Ubuntu OS. The work around I found was this.
if (SystemHelper.isUnix()) {
getContentPane().setPreferredSize(
Toolkit.getDefaultToolkit().getScreenSize());
pack();
setResizable(false);
show();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, getContentPane());
Point l = getLocation();
l.x -= p.x;
l.y -= p.y;
setLocation(p);
}
});
}
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);
In Fedora the above problem is not present. But there are complications involved with Gnome or KDE. So better be careful. Hope this helps.
If you want to work over APIs you have to do inside your DialogFragemnt->onStart and not inside onCreateDialog
@Override
public void onStart()
{
if (getDialog() == null)
{
return;
}
getDialog().getWindow().setWindowAnimations(
R.style.DlgAnimation);
super.onStart();
}
It sounds like jQuery isn't loading properly. Which source/version are you using?
Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $
. If that works, you may like to use noConflict
to ensure the other code that's using $
doesn't break.
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Like this... I used it to read Chinese characters...
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String
Do
a = reader.ReadLine
'
' Code here
'
Loop Until a Is Nothing
reader.Close()
No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.
Here are some similar questions with similar results:
"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
This regex will check for scientific floating point numbers:
^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$
However, I believe that your best bet is to use the parser in a try.
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
An evolved version of ossek solution
Custom filter is more appropriate, then you can use it anywhere in the project
js file
var myApp = angular.module('myApp',[]);
myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){
return function (input, format) {
if (!angular.isDefined(format)) {
format = $locale['DATETIME_FORMATS']['medium'];
}
var date = new Date(input);
var d = new Date()
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return $filter('date')(_utc, format)
};
}]);
in template
<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
We can use following code to get the current logged in User in ASP.Net MVC:
var user= System.Web.HttpContext.Current.User.Identity.GetUserName();
Also
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'
Environment.UserName - Will Display format : 'Username'
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
The easiest way is something like this and it will return only the date:
var date = DateTime.Now.ToShortDateString();
Migrations change the state of the database using the command
$ bundle exec rake db:migrate
We can undo a single migration step using
$ bundle exec rake db:rollback
To go all the way back to the beginning, we can use
$ bundle exec rake db:migrate VERSION=0
As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially
Below code will retrieve all fields other than password within each document:
const users = await UserModel.find({}, {
password: 0
});
console.log(users);
Output
[
{
"_id": "5dd3fb12b40da214026e0658",
"email": "[email protected]"
}
]
Below code will only retrieve email field within each document:
const users = await UserModel.find({}, {
email: 1
});
console.log(users);
Output
[
{
"email": "[email protected]"
}
]
myInt.ToString("D4");
Both do one thing in common - that is serializing an Object. Serialization is used to transfer objects or to store them. But:
So Serialization is part of Marshalling.
CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.
Try this:
ul li a:after {
display: block;
content: "";
width: 3px;
height: 5px;
background: transparent url('../images/small_triangle.png') no-repeat;
}
You need the content: "";
declaration to give your generated element content, even if that content is "nothing".
Also, I fixed the syntax/ordering of your background
declaration.
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
The script you downloaded lists the content of a specified folder. You probably put the unlink - call in one of the while
-loops that list the files.
EDIT - Now that you posted your code:
echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';
Doing this calls the unlink
-function each time the line is written, deleting your file.
You have to write a link to a script that contains a delete function and pass some parameter that tells your script what to delete.
Example:
<a href="/path/to/script.php?delete='. $FileLink .'">delete</a>
You should not pass the path to a file this script and just delete it though, because malevolent being might use it to just delete everything or do other evil things.
jquery will provide you with this and more ...
if($("#something").val()){ //do stuff}
It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.
jQuery(document).ready(function() {
/* finds closest element with class divright/left and
makes all checkboxs inside that div class the same as selectAll...
*/
$("#selectAll").click(function() {
$(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
});
});
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html()
call will not serialize the event.
It permanently comments out that code so the compiler will never compile it.
The coder can later change the #ifdef to have that code compile in the program if he wants to.
It's exactly like the code doesn't exist.
Wrap your columns in a .row and add to that div a class called "no-gutter"
<div class="container">
<div class="row no-gutter">
<h2>OntoExplorer<span style="color:#b92429">.</span></h2>
<div class="col-md-4">
<div class="widget">
<div class="widget-header">
<h3>Dimensions</h3>
</div>
<div class="widget-content">
</div>
</div>
</div>
<div class="col-md-8">
<div class="widget">
<div class="widget-header">
<h3>Results</h3>
</div>
<div class="widget-content">
</div>
</div>
</div>
</div>
Then paste below contents to your CSS file
.row.no-gutter {
margin-left: 0;
margin-right: 0;
}
.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
padding-right: 0;
padding-left: 0;
}
I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.
The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.
This assumes that your objective is to stream output to the console, rather than having output go to message boxes.
The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:
Option Explicit
'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE
'// Now we can use the Consol object to write to and read from the console
With CONS
'// Simply write a line
.print "CSCRIPT Console demo script"
'// Arguments are passed through correctly, if present
.Print "Arg count=" & wscript.arguments.count
'// List all the arguments on the console log
dim ix
for ix = 0 to wscript.arguments.count -1
.print "Arg(" & ix & ")=" & wscript.arguments(ix)
next
'// Prompt for some text from the user
dim sMsg : sMsg = .prompt( "Enter any text:" )
'// Write out the text in a box
.Box sMsg
'// Pause with the message "Hit enter to continue"
.Pause
End With
'= =========== End of script - the cCONSOLE class code follows here
Here is the code for the cCONSOLE class
CLASS cCONSOLE
'= =================================================================
'=
'= This class provides automatic switch to CScript and has methods
'= to write to and read from the CSCript console. It transparently
'= switches to CScript if the script has been started in WScript.
'=
'= =================================================================
Private oOUT
Private oIN
Private Sub Class_Initialize()
'= Run on creation of the cCONSOLE object, checks for cScript operation
'= Check to make sure we are running under CScript, if not restart
'= then run using CScript and terminate this instance.
dim oShell
set oShell = CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
'= Not running under CSCRIPT
'= Get the arguments on the command line and build an argument list
dim ArgList, IX
ArgList = ""
For IX = 0 to wscript.arguments.count - 1
'= Add the argument to the list, enclosing it in quotes
argList = argList & " """ & wscript.arguments.item(IX) & """"
next
'= Now restart with CScript and terminate this instance
oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
WScript.Quit
End If
'= Running under CScript so OK to continue
set oShell = Nothing
'= Save references to stdout and stdin for use with Print, Read and Prompt
set oOUT = WScript.StdOut
set oIN = WScript.StdIn
'= Print out the startup box
StartBox
BoxLine Wscript.ScriptName
BoxLine "Started at " & Now()
EndBox
End Sub
'= Utility methods for writing a box to the console with text in it
Public Sub StartBox()
Print " " & String(73, "_")
Print " |" & Space(73) & "|"
End Sub
Public Sub BoxLine(sText)
Print Left(" |" & Centre( sText, 74) , 75) & "|"
End Sub
Public Sub EndBox()
Print " |" & String(73, "_") & "|"
Print ""
End Sub
Public Sub Box(sMsg)
StartBox
BoxLine sMsg
EndBox
End Sub
'= END OF Box utility methods
'= Utility to center given text padded out to a certain width of text
'= assuming font is monospaced
Public Function Centre(sText, nWidth)
dim iLen
iLen = len(sText)
'= Check for overflow
if ilen > nwidth then Centre = sText : exit Function
'= Calculate padding either side
iLen = ( nWidth - iLen ) / 2
'= Generate text with padding
Centre = left( space(iLen) & sText & space(ilen), nWidth )
End Function
'= Method to write a line of text to the console
Public Sub Print( sText )
oOUT.WriteLine sText
End Sub
'= Method to prompt user input from the console with a message
Public Function Prompt( sText )
oOUT.Write sText
Prompt = Read()
End Function
'= Method to read input from the console with no prompting
Public Function Read()
Read = oIN.ReadLine
End Function
'= Method to provide wait for n seconds
Public Sub Wait(nSeconds)
WScript.Sleep nSeconds * 1000
End Sub
'= Method to pause for user to continue
Public Sub Pause
Prompt "Hit enter to continue..."
End Sub
END CLASS
The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
But also you should make sure that, the data which is coming coalesce nodes should have highly configured, if you are dealing with huge data. Because all the data will be loaded to those nodes, may lead memory exception. Though reparation is costly, i prefer to use it. Since it shuffles and distribute the data equally.
Be wise to select between coalesce and repartition.
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.
Good luck.
set the target
attribute of your <a>
element to "_tab"
EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp
EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):
_blank Opens the linked document in a new window or tab
_self Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top Opens the linked document in the full body of the window
framename Opens the linked document in a named frame
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:
import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'
df['string_col'].str.replace(regular_expression, '', regex=True)
I did find any of these solutions met my requirements, so made my own version of node called node2exe that does this. It's available from https://github.com/areve/node2exe
With gnuplot using gplot.py
from gplot import *
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
gplot.log('y')
gplot(*zip(*l))
DataTable
's Select
method only supports simple filtering expressions like {field} = {value}
. It does not support complex expressions, let alone SQL/Linq statements.
You can, however, use Linq extension methods to extract a collection of DataRow
s then create a new DataTable
.
dt = dt.AsEnumerable()
.GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
.Select(g => g.OrderBy(r => r["PK"]).First())
.CopyToDataTable();
Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/
Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.
EDIT: Youtube renders the object
and embed
with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:
a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements
b) Find a way for youtube to specify those.
Try this
@Entity
@Table(name="tblperson")
public class Person {
public int id;
public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
this.otherInfo= otherInfo;
}
rest of attributes ...
}
@Entity
@Table(name="tblotherInfo")
public class OtherInfo {
private int id;
private Person person;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)
public College getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
rest of attributes ...
}
You can use ILDASM...
ildasm.exe C:\foo.dll /metadata[=MDHEADER] /text /noil
and check for the 'Metadata section' in the output. It would be something like this:
Metadata section: 0x424a5342, version: 1.1, extra: 0, version len: 12, version: v4.0.30319
The 'version' tag will tell you the .NET Framework version. In the above example it is 4.0.30319
You can also use the RestSharp library for example
var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The easiest way to do this is using ios :: noreplace
.
The main difference is ::
npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json
npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).
Ponits to note::
One more thing, npm build
and npm run build
are two different things, npm run build
will do custom work written inside package.json
and npm build
is a pre-defined script (not available to use directly)
You cannot specify some thing inside custom build script (npm run build
) script and expect npm build
to do the same. Try following thing to verify in your package.json
:
{ "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }
and run npm run build
and npm build
one by one and you will see the difference. For more about commands kindly follow npm documentation.
Cheers!!
The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.
The syntax for this is as follows:
class Container {
...
struct Inner; // Declare, but not define, the struct.
...
};
struct Container::Inner {
/* Define the struct here. */
};
You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.
In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):
Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.
Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.
It should work like this
Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.
Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.
The most beginner-friendly solution is:
Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:
private void wait_Tick(object sender, EventArgs e)
{
refreshText(); // Add the method you want to call here.
}
No need to worry about pasting it into the wrong code block or something like that.
I have:
Copy-paste the configuration from existing configuration which works with specific name and targeting platform (I had Release | x64):
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
There is no need to invoke PHP for this. Just put it directly into the HTML:
<a href="http://www.example.com/">...
If you cannot use TRUNCATE
(e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:
ALTER TABLE mytable AUTO_INCREMENT = 1
If you are dealing with a previously bound date picker then setting
$("#datepicker").datepicker({ minDate: 0 });
will not work. That syntax is applicable only when you are creating the widget.
To set min date for a bound date picker use the following:
$("#datePicker").datepicker("option", "minDate", 0);
The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.
import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")
If it's working in the debug, then wait
must be the proper solution.
I will suggest to use the explicit wait
, as given below:
WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));
In the upcoming Python 3.10
release schedule
, with the new pairwise
function it's possible to slide through pairs of elements and thus map on rolling pairs:
from itertools import pairwise
[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]
The intermediate result being:
pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
int number = 534;
int firstDigit = number/100;
( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .
but if you want to get the last number , you can use (%) operator
int lastDigit = number%10;
which gives us the reminder of the division , so 534%10 , will yield the number 4 .
Alternatively, can use for particular table
<table style="width:1000px; height:100px;">
<tr>
<td align="center" valign="top">Text</td> //Remove it
<td class="tableFormatter">Text></td>
</tr>
</table>
Add this css in external file
.tableFormatter
{
width:100%;
vertical-align:top;
text-align:center;
}
define margin and padding for the element is facing the problem:
#element_id {margin: 0; padding: 0}
and see if problem exists. IE renders the page with to more unwanted inheritance. you should stop it from doing so.
First
ps -ef
to list all processes. Note the the process number of the one you want to kill. Then
kill 1234
were you replace 1234 with the process number that you want.
Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name
killall processname
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
for key in data.keys():
print key
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
External
option in Unity ? Preferences ? Packages ? Repository
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuNote that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json")
fixed the problem
also mimetype is important.
There is no foreach in C.
You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).
char* nullTerm;
nullTerm = "Loop through my characters";
for(;nullTerm != NULL;nullTerm++)
{
//nullTerm will now point to the next character.
}
The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.
If you don't like the version with the anonymous type for some specific reason, you should explain that reason.
If you want to do something other than what you originally asked for, please give an example of what you really want to do.
EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.
Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where
clause (after a second from
clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.
Depending on how the proxy login works stream_context_set_default might help you.
$context = stream_context_set_default(
array(
'http'=>array(
'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
)
)
);
$result = file_get_contents('http://..../...');
You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().
Example:
try {
int i = Integer.parseint(stringToParse);
//parseInt succeded
} catch(Exception e)
{
//parseInt failed
}
I know this question is old but I ran across it and I know other people might have the same problem. All these answers are okay but do not give proper detail or actual TRUE advice.
When wanting to style a specific section of a paragraph use the span tag.
<p><span style="font-weight:900">Andy Warhol</span> (August 6, 1928 - February 22, 1987)
was an American artist who was a leading figure in the visual art movement known as pop
art.</p>
Andy Warhol (August 6, 1928 - February 22, 1987) was an American artist who was a leading figure in the visual art movement known as pop art.
As the code shows, the span tag styles on the specified words: "Andy Warhol". You can further style a word using any CSS font styling codes.
{font-weight; font-size; text-decoration; font-family; margin; color}, etc.
Any of these and more can be used to style a word, group of words, or even specified paragraphs without having to add a class to the CSS Style Sheet Doc. I hope this helps someone!
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
I think Compiling Python Code would be a good place to start:
Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.
To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.
To “compile” a Python program into an executable, use a bundling tool, such as Gordon McMillan’s installer (alternative download) (cross-platform), Thomas Heller’s py2exe (Windows), Anthony Tuininga’s cx_Freeze (cross-platform), or Bob Ippolito’s py2app (Mac). These tools puts your modules and data files in some kind of archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g,'_');
Here is another solution that works good.
(function() {
'use strict';
angular.module('cms').config(route);
route.$inject = ['$routeProvider'];
function route($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: buildPath
})
.when('/:section/:page', {
templateUrl: buildPath
})
.when('/:section/:page/:task', {
templateUrl: buildPath
});
}
function buildPath(path) {
var layout = 'layout';
angular.forEach(path, function(value) {
value = value.charAt(0).toUpperCase() + value.substring(1);
layout += value;
});
layout += '.tpl';
return 'client/app/layouts/' + layout;
}
})();
On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.
As someone else suggested, the solution seems to be to install locally by not using the -g
hint.
string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";
string jsonData = jsonData1.Replace("\"", "");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
JArray array= JArray.Parse(jsonData);
couldnot parse , if the vaule is a string..
look at name : meals , if name : 1 then it will parse
This one has always been a gotcha for me and many others. In short, the opening and closing tags for the <textarea>
element must be on the same line, otherwise a newline character occupies it. The placeholder will therefore not be displayed since the input area contains content (a newline character is, technically, valid content).
Good:
<textarea></textarea>
Bad:
<textarea>
</textarea>
This is not true anymore, according to the HTML5 parsing spec:
If the next token is a U+000A LINE FEED (LF) character token,
then ignore that token and move on to the next one. (Newlines
at the start of textarea elements are ignored as an authoring
convenience.)
You might still have trouble if you editor insists on ending lines with CRLF, though.
Your code can work well with some adaptations :
div {
background-position: 50% 100%;
background-repeat: no-repeat;
background-size: contain;
animation: animateSectionBackground infinite 240s;
}
@keyframes animateSectionBackground {
00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}
Here is the explanation of the percentage to suit your situation:
First you need to calculate the "chunks". If you had 8 differents background, you need to do : 100% / 8 = 12.5% (to simplify you can let fall the decimals) => 12%
After that you obtain that :
@keyframes animateSectionBackground {
00% { background-image: url(/assets/images/bg-1.jpg); }
12% { background-image: url(/assets/images/bg-2.jpg); }
25% { background-image: url(/assets/images/bg-3.jpg); }
37% { background-image: url(/assets/images/bg-4.jpg); }
50% { background-image: url(/assets/images/bg-5.jpg); }
62% { background-image: url(/assets/images/bg-6.jpg); }
75% { background-image: url(/assets/images/bg-7.jpg); }
87% { background-image: url(/assets/images/bg-8.jpg); }
}
If you execute this code, you will see the transition will be permanantly. If you want the backgrounds stay fixed while a moment, you can do like this :
@keyframes animateSectionBackground {
00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}
That mean you want :
By putting 11%, the transtion duration will be 1% (12% - 11% = 1%). 1% of 240s (total duration) => 2.4 seconds.
You can adapt according to your needs.
PHP 5.6 introduced a third parameter to array_filter()
, flag
, that you can set to ARRAY_FILTER_USE_KEY
to filter by key instead of value:
$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed = ['foo', 'bar'];
$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
Clearly this isn't as elegant as array_intersect_key($my_array, array_flip($allowed))
, but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed
could contain regex patterns instead of plain strings.
You can also use ARRAY_FILTER_USE_BOTH
to have both the value and the key passed to your filter function. Here's a contrived example based upon the first, but note that I'd not recommend encoding filtering rules using $allowed
this way:
$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
$my_array,
function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
return isset($allowed[$key]) && (
$allowed[$key] === true || $allowed[$key] === $val
);
},
ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']
You could use the ones on CodePlex or http://www.enterprisedt.com/general/press/20060818.html
You can find them in /var/log
within your root Magento installation
There will usually be two files by default, exception.log
and system.log
.
If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes
A good power function would be
public long Power(int number, int power) {
if (number == 0) return 0;
long t = number;
int e = power;
int result = 1;
for(i=0; i<sizeof(int); i++) {
if (e & 1 == 1) result *= t;
e >>= 1;
if (e==0) break;
t = t * t;
}
}
The Math.Pow
function uses the processor power function and is more efficient.
urllib2.urlopen
handles ftp links.
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
If you want to have a solid color for your navigation bar in iOS 6 similar to iOS 7 use this:
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor greenColor]];
in iOS 7 use the barTintColor
like this:
navigationController.navigationBar.barTintColor = [UIColor greenColor];
or
[[UINavigationBar appearance] setBarTintColor:[UIColor greenColor]];
I hope this code can help:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
NOTES:
If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.
If you just cannot tolerate a global variable, define it in main() and pass it around where needed...
Another option is:
when:
def response = mockMvc.perform(
get('/path/to/api')
.header("Content-Type", "application/json"))
then:
response.andExpect(status().isOk())
response.andReturn().getResponse().getContentAsString() == "what you expect"
This answer is more meant to explain why, not how. The '=='
operator in R is vectorized in a same way as the '+'
operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:
> 1:3 == 1:3
[1] TRUE TRUE TRUE
Here the first test is 1==1
which is TRUE, the second 2==2
and the third 3==3
. Notice that this returns a FALSE in the first and second element because the order is wrong:
> 3:1 == 1:3
[1] FALSE TRUE FALSE
Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:
> 1:2 == 1:3
[1] TRUE TRUE FALSE
Warning message:
In 1:2 == 1:3 :
longer object length is not a multiple of shorter object length
Here the first match is 1==1
, then 2==2
, and finally 1==3
(FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:
> 1:3 == 1
[1] TRUE FALSE FALSE
The correct operator to test if an element is in a vector is indeed '%in%'
which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).
Alternatively, you can use '&'
to combine two logical statements. '&'
takes two elements and checks elementwise if both are TRUE:
> 1:3 == 1 & 1:3 != 2
[1] TRUE FALSE FALSE
You can do a custom namespace of events.
$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});
Then, when you need to trigger them you can choose the order.
$('span').trigger('click.doStuff1').trigger('click.doStuff2');
or
$('span').trigger('click.doStuff2').trigger('click.doStuff1');
Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do
$('span').trigger('click');
I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.
show timezone;
But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone;
will return that value instead of "localtime".
So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".
It is possible. With vanilla Javascript, you can use the function below for reference.
function updateIframeBackground(iframeId) {
var x = document.getElementById(iframeId);
var y = (x.contentWindow || x.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor = "#2D2D2D";
}
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_iframe_contentdocument
This answer is based on Pedro's answer but adjusted so it also works if text attribute is already set:
package nl.raakict.android.spc.widget;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ScaleXSpan;
import android.util.AttributeSet;
import android.widget.TextView;
public class LetterSpacingTextView extends TextView {
private float letterSpacing = LetterSpacing.BIGGEST;
private CharSequence originalText = "";
public LetterSpacingTextView(Context context) {
super(context);
}
public LetterSpacingTextView(Context context, AttributeSet attrs){
super(context, attrs);
originalText = super.getText();
applyLetterSpacing();
this.invalidate();
}
public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public float getLetterSpacing() {
return letterSpacing;
}
public void setLetterSpacing(float letterSpacing) {
this.letterSpacing = letterSpacing;
applyLetterSpacing();
}
@Override
public void setText(CharSequence text, BufferType type) {
originalText = text;
applyLetterSpacing();
}
@Override
public CharSequence getText() {
return originalText;
}
private void applyLetterSpacing() {
if (this == null || this.originalText == null) return;
StringBuilder builder = new StringBuilder();
for(int i = 0; i < originalText.length(); i++) {
String c = ""+ originalText.charAt(i);
builder.append(c.toLowerCase());
if(i+1 < originalText.length()) {
builder.append("\u00A0");
}
}
SpannableString finalText = new SpannableString(builder.toString());
if(builder.toString().length() > 1) {
for(int i = 1; i < builder.toString().length(); i+=2) {
finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
super.setText(finalText, BufferType.SPANNABLE);
}
public class LetterSpacing {
public final static float NORMAL = 0;
public final static float NORMALBIG = (float)0.025;
public final static float BIG = (float)0.05;
public final static float BIGGEST = (float)0.2;
}
}
If you want to use it programatically:
LetterSpacingTextView textView = new LetterSpacingTextView(context);
textView.setSpacing(10); //Or any float. To reset to normal, use 0 or LetterSpacingTextView.Spacing.NORMAL
textView.setText("My text");
//Add the textView in a layout, for instance:
((LinearLayout) findViewById(R.id.myLinearLayout)).addView(textView);
Either of the following SQL will return all schema in Oracle DB.
select owner FROM all_tables group by owner;
select distinct owner FROM all_tables;
As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule
on your ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
For custom serialization/de-serialization of DateTime
, you need to implement your own StdScalarSerializer
and StdScalarDeserializer
; it's pretty convoluted, but anyway.
For example, here's a DateTime
serializer that uses the ISODateFormat
with the UTC time zone:
public class DateTimeSerializer extends StdScalarSerializer<DateTime> {
public DateTimeSerializer() {
super(DateTime.class);
}
@Override
public void serialize(DateTime dateTime,
JsonGenerator jsonGenerator,
SerializerProvider provider) throws IOException, JsonGenerationException {
String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
jsonGenerator.writeString(dateTimeAsString);
}
}
And the corresponding de-serializer:
public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {
public DateTimeDesrializer() {
super(DateTime.class);
}
@Override
public DateTime deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
JsonToken currentToken = jsonParser.getCurrentToken();
if (currentToken == JsonToken.VALUE_STRING) {
String dateTimeAsString = jsonParser.getText().trim();
return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
}
} finally {
throw deserializationContext.mappingException(getValueClass());
}
}
Then tie these together with a module:
public class DateTimeModule extends SimpleModule {
public DateTimeModule() {
super();
addSerializer(DateTime.class, new DateTimeSerializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
Then register the module on your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
The round funtion stated does not works for definate integers like :
a=8
round(a,3)
8.0
a=8.00
round(a,3)
8.0
a=8.000000000000000000000000
round(a,3)
8.0
but , works for :
r=400/3.0
r
133.33333333333334
round(r,3)
133.333
Morever the decimals like 2.675 are rounded as 2.67 not 2.68.
Better use the other method provided above.
in python .....intendation matters, e.g.:
if a==1:
print("hey")
if a==2:
print("bye")
print("all the best")
In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this
if a==2:
print("bye")
print("all the best")
then "all the best" will be printed only if a==2
I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put
#include <Windows.h>
instead.
void clearArray (char *input[]){
*input = ' ';
}
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time
with the ability to do arithmetic. If you go past midnight, it just wraps around:
>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'
It's available from PyPi as nptime
("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime
The documentation is at http://tgs.github.io/nptime/
Because that's not what strip()
does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.
You could do:
name= name.replace('(', '').replace(')', '').replace ...
or:
name= ''.join(c for c in name if c not in '(){}<>')
or maybe use a regex:
import re
name= re.sub('[(){}<>]', '', name)
I've found a more reliable method (at least on Excel 2016 for Mac) is:
Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:
= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")
Then just sort the list by column C to find what you have to delete.