Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
Use this..
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
div {
text-align: center;
}
div ul {
display: inline-table;
}
ul as inline-table fixes the with issue. I used the parent div to align the text to center. this way it looks good even in other languages (translation, different width)
The directions state:
- Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
- Unzip the packages into a single directory such as "instantclient".
- Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
- Start your application and enjoy.
Suggest extracting/unzipping into a new directory. They've suggested instantclient
, but you can name the directory anything you like. Name it C:\OracleInstantClient\
if you choose.
Then in Step 3, open a Windows Command Prompt. Type:
PATH C:\OracleInstantClient; %PATH%`
That's all there is to it!
Well I would do it this way as I am no good with Regs..
CODE
t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()
print [i+j for i,j in zip(t[::2],t[1::2])]
output:
['1. eat, food 7am', '2. brush, teeth 8am', '3. crack, eggs 1pm']
Hope this helps :)
Apart from having a Path
variable, the directory C:\data\db
is mandatory.
Create this and the error shall be solved.
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
You can do this using PHP:
$txt1 = "the color is";
$txt2 = " red!";
echo $txt1.$txt2;
This will combine two strings and the putput will be: "the color is red!".
this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.
@echo off
mkdir C:\Users\cmdfolder
if echo=="Access is denied." (goto :1A) else (goto :A4)
:A1
cls
color 0d
echo restart this program as administator
:A4
pause
you are get the view in string using this way
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
if (model != null)
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
We are call this method in two way
string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", null)
OR
var model = new Person()
string strView = RenderPartialViewToString("~/Views/Shared/_Header.cshtml", model)
Here is a working version using v3
of docker-compose.yml
. The key is the volumes directive:
mysql:
image: mysql:5.6
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: theusername
MYSQL_PASSWORD: thepw
MYSQL_DATABASE: mydb
volumes:
- ./data:/docker-entrypoint-initdb.d
In the directory that I have my docker-compose.yml
I have a data
dir that contains .sql
dump files. This is nice because you can have a .sql
dump file per table.
I simply run docker-compose up
and I'm good to go. Data automatically persists between stops. If you want remove the data and "suck in" new .sql
files run docker-compose down
then docker-compose up
.
If anyone knows how to get the mysql
docker to re-process files in /docker-entrypoint-initdb.d
without removing the volume, please leave a comment and I will update this answer.
I had this same problem. I had set Project A's "Platform Target" ("Project A"(Right Click)->Properties->Build->"Platform Target") to x86 but kept Project B's at "Any CPU". Setting Project B's to "x86" fixed this.
If you have cloned using HTTPS (recommended) then:-
git config --global credential.helper cache
and then
git config --global credential.helper 'cache --timeout=2592000'
timeout=2592000 (30 Days in seconds) to enable caching for 30 days (or whatever suites you).
Now run a simple git command that requires your username and password.
Enter your credentials once and now caching is enabled for 30 Days.
Try again with any git command and now you don't need any credentials.
For more info :- Caching your GitHub password in Git
Note : You need Git 1.7.10 or newer to use the credential helper. On system restart, we might have to enter the password again.
Update #1:
If you are receiving this error git: 'credential-cache' is not a git command. See 'get --help'
then replace git config --global credential.helper 'cache --timeout=2592000'
with git config --global credential.helper 'store --file ~/.my-credentials'
Update #2:
If you keep getting the prompt of username and password and getting this issue:
Logon failed, use ctrl+c to cancel basic credential prompt.
Reinstalling the latest version of git worked for me.
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
You can declare SqlConnection
and SqlCommand
instances at global level so that you can use it through out the class. Connection string is in Web.Config
.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet
.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
"location" : null // this is not really an array it's a null object
"location" : [] // this is an empty array
It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.
Thanks to TheSharpieOne for pointing out the ng-selected option. If that had been posted as an answer rather than as a comment, I would have made that the correct answer.
Here's a working JSFiddle: http://jsfiddle.net/coverbeck/FxM3B/5/.
I also updated the fiddle to use the title attribute, which I had left out in my original post, since it wasn't the cause of the problem (but it is the reason I want to use ng-repeat instead of ng-options).
HTML:
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator">
<option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
</body>
JS:
function AppCtrl($scope) {
$scope.filterCondition={
operator: 'eq'
}
$scope.operators = [
{value: 'eq', displayName: 'equals', title: 'The equals operator does blah, blah'},
{value: 'neq', displayName: 'not equal', title: 'The not equals operator does yada yada'}
]
}
Swift version:
if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
let docURL = NSURL(fileURLWithPath: docPath)
webView.loadRequest(NSURLRequest(URL: docURL))
}
So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo
What you have to do once install command is done: Open Packages menu -> Load package...
You will see your package on the list. You can automate this: How to load packages in R automatically?
I recently created this Pagination component that implements paging logic like Google's search results:
import React, { PropTypes } from 'react';
const propTypes = {
items: PropTypes.array.isRequired,
onChangePage: PropTypes.func.isRequired,
initialPage: PropTypes.number
}
const defaultProps = {
initialPage: 1
}
class Pagination extends React.Component {
constructor(props) {
super(props);
this.state = { pager: {} };
}
componentWillMount() {
this.setPage(this.props.initialPage);
}
setPage(page) {
var items = this.props.items;
var pager = this.state.pager;
if (page < 1 || page > pager.totalPages) {
return;
}
// get new pager object for specified page
pager = this.getPager(items.length, page);
// get new page of items from items array
var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
// update state
this.setState({ pager: pager });
// call change page function in parent component
this.props.onChangePage(pageOfItems);
}
getPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 10
pageSize = pageSize || 10;
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
var pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
render() {
var pager = this.state.pager;
return (
<ul className="pagination">
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(1)}>First</a>
</li>
<li className={pager.currentPage === 1 ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
</li>
{pager.pages.map((page, index) =>
<li key={index} className={pager.currentPage === page ? 'active' : ''}>
<a onClick={() => this.setPage(page)}>{page}</a>
</li>
)}
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
</li>
<li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
<a onClick={() => this.setPage(pager.totalPages)}>Last</a>
</li>
</ul>
);
}
}
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;
And here's an example App component that uses the Pagination component to paginate a list of 150 example items:
import React from 'react';
import Pagination from './Pagination';
class App extends React.Component {
constructor() {
super();
// an example array of items to be paged
var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
this.state = {
exampleItems: exampleItems,
pageOfItems: []
};
// bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
this.onChangePage = this.onChangePage.bind(this);
}
onChangePage(pageOfItems) {
// update state with new page of items
this.setState({ pageOfItems: pageOfItems });
}
render() {
return (
<div>
<div className="container">
<div className="text-center">
<h1>React - Pagination Example with logic like Google</h1>
{this.state.pageOfItems.map(item =>
<div key={item.id}>{item.name}</div>
)}
<Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
</div>
</div>
<hr />
<div className="credits text-center">
<p>
<a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
</p>
</div>
</div>
);
}
}
export default App;
For more details and a live demo you can check out this post
You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.
do this
while read -r line
do
set -- $line
echo "$1 $2"
done <"file"
$1, $2 etc will be your 1st and 2nd splitted "fields". use $@ to get all values..use $# to get length of the "fields".
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
The best way to put is that hg forget
is identical to hg remove
except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore
.
In other words, I cannot tell if you used hg forget
or hg remove
when I pull from you. A file that you ran hg forget
on will be deleted when I update to that changeset — just as if you had used hg remove
instead.
Here is a Xamarin.Android version of Tom McFarlin's answer
//Determine screen size
if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) {
Toast.MakeText (this, "Large screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) {
Toast.MakeText (this, "Normal screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) {
Toast.MakeText (this, "Small screen", ToastLength.Short).Show ();
} else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) {
Toast.MakeText (this, "XLarge screen", ToastLength.Short).Show ();
} else {
Toast.MakeText (this, "Screen size is neither large, normal or small", ToastLength.Short).Show ();
}
//Determine density
DisplayMetrics metrics = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics (metrics);
var density = metrics.DensityDpi;
if (density == DisplayMetricsDensity.High) {
Toast.MakeText (this, "DENSITY_HIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Medium) {
Toast.MakeText (this, "DENSITY_MEDIUM... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Low) {
Toast.MakeText (this, "DENSITY_LOW... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xhigh) {
Toast.MakeText (this, "DENSITY_XHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxhigh) {
Toast.MakeText (this, "DENSITY_XXHIGH... Density is " + density, ToastLength.Long).Show ();
} else if (density == DisplayMetricsDensity.Xxxhigh) {
Toast.MakeText (this, "DENSITY_XXXHIGH... Density is " + density, ToastLength.Long).Show ();
} else {
Toast.MakeText (this, "Density is neither HIGH, MEDIUM OR LOW. Density is " + density, ToastLength.Long).Show ();
}
Somewhat a little prettified solution by @Vin-G.
import datetime
def monthrange(start, finish):
months = (finish.year - start.year) * 12 + finish.month + 1
for i in xrange(start.month, months):
year = (i - 1) / 12 + start.year
month = (i - 1) % 12 + 1
yield datetime.date(year, month, 1)
One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator
.
The assert
statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails.
When you do...
assert condition
... you're telling the program to test that condition, and immediately trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
if not condition:
raise AssertionError()
Try it in the Python shell:
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
Assertions can include an optional message, and you can disable them when running the interpreter.
To print a message if the assertion fails:
assert False, "Oh no! This assertion failed!"
Do not use parenthesis to call assert
like a function. It is a statement. If you do assert(condition, message)
you'll be running the assert
with a (condition, message)
tuple as first parameter.
As for disabling them, when running python
in optimized mode, where __debug__
is False
, assert statements will be ignored. Just pass the -O
flag:
python -O script.py
See here for the relevant documentation.
In dashboard you can see running word press version at "At a Glance"
I got around the proxy using https... some proxies don't even check https.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
c:\git\meantest>git clone http://github.com/linnovate/mean.git
Cloning into 'mean'...
fatal: unable to access 'http://github.com/linnovate/mean.git/': Failed connect
to github.com:80; No error
c:\git\meantest>git clone https://github.com/linnovate/mean.git
Cloning into 'mean'...
remote: Reusing existing pack: 2587, done.
remote: Counting objects: 27, done.
remote: Compressing objects: 100% (24/24), done.
rRemote: Total 2614 (delta 3), reused 4 (delta 0)eceiving objects: 98% (2562/26
Receiving objects: 100% (2614/2614), 1.76 MiB | 305.00 KiB/s, done.
Resolving deltas: 100% (1166/1166), done.
Checking connectivity... done
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...)
of the ActionListener
registered with the Start button, not for the Start button itself.
You can add a simple ActionListener
like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final
in the above example if you want to create the anonymous listener in local scope.
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
You can do it using xml.
Create an xml layout and name it like my_edit_text_border.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:radius="5dp" />
<stroke
android:width="2dp"
android:color="#949494"
/>
</shape>
</item>
</selector>
Add background to your Edittext
<EditText
android:id="@+id/editText1"
..
android:background="@layout/my_edit_text_border">
A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try cat .git/refs/heads/<branch>
in your repository.
That written, if you're really into tracking this information in your repository, check out branch descriptions. They allow you to attach arbitrary metadata to branches, locally at least.
Also DarVar's answer below is a very clever way to get at this information.
public static void main(String[] args) {
String str = "Honey dfd tEch Solution";
String[] arr = str.split(" ");
System.out.println(arr.length);
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (!arr[i].trim().isEmpty()) {
System.out.println(arr[i]);
count++;
}
}
System.out.println(count);
}
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
import numpy as np
import scipy.stats
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, m-h, m+h
you can calculate like this way.
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
Boost multindex can be used for proper solution. Following solution is not a very best option but might be useful in few cases where user is assigning default value like 0 or NULL at initialization and want to check if value has been modified.
Ex.
< int , string >
< string , int >
< string , string >
consider < string , string >
mymap["1st"]="first";
mymap["second"]="";
for (std::map<string,string>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
{
if ( it->second =="" )
continue;
}
You can use within <td>
tag css : display:inline-block
Like: <td style="display:inline-block">
In MS-SQL Server 7+:
SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mytable'
@echo off
setlocal enableextensions enabledelayedexpansion
if %1=="" (
rem Set default path
set PWA_PATH="C:\Program Files\PWA"
rem
echo You have not specified your PWA url.
echo Default will be assumed: C:\Program Files\PWA.
choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
IF ERRORLEVEL ==2 GOTO CANCEL
IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
GOTO END
) else (
set PWA_PATH=%1
@echo !PWA_PATH! vs. %1
goto end
)
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1
As VardhanDotNet mentions, %1
is enough.
"%1%"
would add quotes around quotes: ""c:\Program Files\xxx""
which means:
""
), ""
)Note however that if you need to use PWA_PATH
within your IF
clause, you need to refer if as !PWA_PATH!
(hence the enabledelayedexpansion
as the beginning of the script)
Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:
Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):
=$A1<>$B1
Then press OK and that should do it.
Here's pure javascript example of handling classes during scrolling.
You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle
from lodash
lib comes in handy.
And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener
once they're not needed (eg during onDestroy
lifecycle hook of your component, like destroyed()
for Vue, or maybe return function of useEffect
hook for React).
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
// Get scroll value_x000D_
const scroll = document.documentElement.scrollTop_x000D_
_x000D_
// If scroll value is more than 0 - add class_x000D_
if (scroll > 0) {_x000D_
navbar.classList.add("scrolled");_x000D_
} else {_x000D_
navbar.classList.remove("scrolled")_x000D_
}_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: 100%;_x000D_
height: 60px;_x000D_
background-color: #89d0f7;_x000D_
box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
height: 3000px;_x000D_
margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
If you have an html form containing one or more fields with "required" attributes, Chrome (on last versions) will validate these fields before submitting the form and, if they are not filled, some tooltips will be shown to the users to help them getting the form submitted (I.e. "please fill out this field").
To avoid this browser built-in validation in forms you can use "novalidate" attribute on your form tag. This form won't be validated by browser:
<form id="form-id" novalidate>
<input id="input-id" type="text" required>
<input id="submit-button" type="submit">
</form>
What about:
WHERE table.field = "0" or CAST(table.field as SIGNED) != 0
to test for numeric and the corrolary:
WHERE table.field != "0" and CAST(table.field as SIGNED) = 0
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Since You Have used the float
property we don't have many options except to adjust it manually.
Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
Just another way, and it works very well.
The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.
This worked:
validateSelectizeDropdown('#PartCondition')
This did not:
validateSelectizeDropdown("#PartCondition")
And the function:
function validateSelectizeDropdown(name) {
if ($(name).val() === "") {
//do something
}
}
I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.
It's a simple ActionResult
that will allow you to download a file from a controller call that returns an IHttpActionResult
.
The file is stored in the byte[] Content
. You can turn it into a stream if needs be.
I used this to return files stored in a database's varbinary column.
public class FileHttpActionResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string FileName { get; set; }
public string MediaType { get; set; }
public HttpStatusCode StatusCode { get; set; }
public byte[] Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage(StatusCode);
response.StatusCode = StatusCode;
response.Content = new StreamContent(new MemoryStream(Content));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
return Task.FromResult(response);
}
}
moment(d).isAfter(ahead30now); // true
http://momentjs.com/docs/#/query/is-after/
if (moment(d).isAfter(ahead30now)) {
// allow input time
console.log('UTC TIME DB', d.format());
} else {
}
If you wrote the console application you can make it hidden by default.
Create a new console app then then change the "Output Type" type to "Windows Application" (done in the project properties)
As stated, use TextView.setText(Html.fromHtml(String))
And use these tags in your Html formatted string:
<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html
The Esentutl /y option allows copyng (single) file files with progress bar like this :
the command should look like :
esentutl /y "FILE.EXT" /d "DEST.EXT" /o
The command is available on every windows machine but the y
option is presented in windows vista.
As it works only with single files does not look very useful for a small ones.
Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h
).
My simple fix it turned out to be calling the form's Activate()
method, so there's no need to use TopMost
(which is what I was aiming at).
Do you need to fake an anchor click? From the thickbox site:
ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).
If that is acceptable it should be as easy as putting the thickbox class on the input itself:
<input id="thickboxButton" type="button" class="thickbox" value="Click me">
If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.
Edit:
Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:
<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>
The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.
Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
You would first remove the table, then add the new replacement to the table's parent object.
Look up removeChild
and appendChild
http://javascript.about.com/library/bldom09.htm
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
Edit: jQuery .append allows sting-html without removing tags: http://api.jquery.com/append/
For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).
This can be caused in many ways:
#include
the header that defines it.#ifndef BLAH_H
) are defective (your #ifndef BLAH_H
doesn't match your #define BALH_H
due to a typo or copy+paste mistake).#define MYHEADER_H
, even if they are in separate directories)new Vector()
should be new Vector<int>()
)NamespaceA::NamespaceB
, AND a <global scope>::NamespaceB
, if you are already within NamespaceA
, it'll look in NamespaceA::NamespaceB
and not bother checking <global scope>::NamespaceB
) unless you explicitly access it.To explicitly access something in the global namespace, prefix it with ::
, as if the global namespace is a namespace with no name (e.g. ::MyType
or ::MyNamespace::MyType
).
I know this may be a bit old, but try using PDO::lastInsertId
. I think it does what you want it to, but you would have to rewrite your application to use PDO (Which is a lot safer against attacks)
THIS IS THE VB VERSION (Works with GREEK) :
Imports System.Text
Imports System.Globalization
Public Function RemoveDiacritics(ByVal s As String)
Dim normalizedString As String
Dim stringBuilder As New StringBuilder
normalizedString = s.Normalize(NormalizationForm.FormD)
Dim i As Integer
Dim c As Char
For i = 0 To normalizedString.Length - 1
c = normalizedString(i)
If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
stringBuilder.Append(c)
End If
Next
Return stringBuilder.ToString()
End Function
In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
ids vals
0 aball 1
1 bball 2
3 fball 4
To end this discussion: the c++ preprocessor is turing complete. It is a semantic property, whether an include is superfluous. Hence, it follows from Rice's theorem that it is undecidable whether an include is superfluous or not. There CAN'T be a program, that (always correctly) detects whether an include is superfluous.
In my case, I needed to retrieve the username to enable the script to change the path, ie. c:\users\%username%\
. I needed to start the script by changing the path to the users desktop. I was able to do this, with help from above and elsewhere, by using the get-location applet.
You may have another, or even better way to do it, but this worked for me:
$Path = Get-Location
Set-Location $Path\Desktop
Split creates an array . You can access the individual values by using a index.
var result=$(row).val().split('|')[2]
alert(result);
OR
var result=$(row).val().split('|');
alert(result[2]);
If it's input element then you need to use $(row).val()
to get the value..
Otherwise you would need to use $(row).text()
or $(row).html()
This answer is to give a better understanding of this warning
Deprecation warning is caused when you use moment to create time object, var today = moment();
.
If this warning is okay with you then I have a simpler method.
Don't use date
object from js
use moment
instead. For example use moment()
to get the current date.
Or convert the js
date object to moment
date. You can simply do that specifying the format of your js
date object.
ie, moment("js date", "js date format");
eg:
moment("2014 04 25", "YYYY MM DD");
(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment
in the future)
Have you given a try to Webkit Filters?
You can manipulate not only opacity, but colour, brightness, luminosity and other properties:
The opposite of read
is show
.
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
sorted((minval, value, maxval))[1]
for example:
>>> minval=3
>>> maxval=7
>>> for value in range(10):
... print sorted((minval, value, maxval))[1]
...
3
3
3
3
4
5
6
7
7
7
Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable
For radio button:
<md-radio-button disabled>Select color</md-radio-button>
For dropdown:
<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>
I have tried the awnsers before but this did not work. Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :)
view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor
openWindowOnButtonClick();
public void openWindowOnButtonClick()
{
view.setAlpha((float)0.5);
FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton);
final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE);
fb.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// check if the Overlay should be visible. If this value is false, it is not shown -> show it.
if(view.getVisibility() == View.INVISIBLE)
{
view.setVisibility(View.VISIBLE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
Log.d("Overlay", "Klick");
}
else if(view.getVisibility() == View.VISIBLE)
{
view.setVisibility(View.INVISIBLE);
keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
This is an error of type database trigger policies. A trigger is code and can add some intelligences or conditions to a Cascade relation like Cascade Deletion. You may need to specialize the related tables options around this like Turning off CascadeOnDelete:
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
modelBuilder.Entity<TableName>().HasMany(i => i.Member).WithRequired().WillCascadeOnDelete(false);
}
Or Turn off this feature completely:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
to print all (or arbitrarily many) lines of the grouped df:
import pandas as pd
pd.set_option('display.max_rows', 500)
grouped_df = df.group(['var1', 'var2'])
print(grouped_df)
Just pick the columns you want directly....
df[['A','E','I','C']]
The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same
No, it is not.
The one that is new to the N Developer Preview has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
The one that is supported by all Android versions, including N, has this method signature:
public boolean shouldOverrideUrlLoading(WebView view, String url)
So why should I do to make it work on all versions?
Override the deprecated one, the one that takes a String
as the second parameter.
I have recently done this on my website using jQuery. The code calculates the height of the tallest div and sets the other divs to the same height. Here's the technique:
http://www.broken-links.com/2009/01/20/very-quick-equal-height-columns-in-jquery/
I don't believe height:100%
will work, so if you don't explicitly know the div heights I don't think there is a pure CSS solution.
THIRD VERSION OF MY ANSWER:
Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -
. This is a flash message example that I use in a partial. Hope this helps!
-if(typeof(info) !== 'undefined')
-if (info)
- if(info.length){
ul
-info.forEach(function(info){
li= info
-})
-}
Is the code you're trying to get to compile the code in your question?
If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -
; second, after you type -if
you don't need to type the {
or }
either. That's what makes Jade pretty sweet.
--------------ORIGINAL ANSWER BELOW ---------------
Try prepending if
with -
:
-if(10 == 10)
//do whatever you want here as long as it's indented two spaces from
the `-` above
There are also tons of Jade examples at:
You can use .reset()
on your form.
$(".myform")[0].reset();
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
It can't be done, either manually or progamatically. This is because the color behind every slide master is white. If you set your background to 100% transparent, it will print as white.
The best you could do is design your slide with all the stuff you want, group everything you want to appear in the transparent image and then right-click/save as picture/.PNG (or you could do that with a macro as well). In this way you would retain transparency.
Here's an example of how to export all slides' shapes to seperate PNG files. Note:
This uses a depreciated function,
namely Shape.Export
. This means
that while the function is still
available up to PowerPoint 2010, it
may be removed from PowerPoint VBA later.
Sub PrintShapesToPng()
Dim ap As Presentation: Set ap = ActivePresentation
Dim sl As slide
Dim shGroup As ShapeRange
For Each sl In ap.Slides
ActiveWindow.View.GotoSlide (sl.SlideIndex)
sl.Shapes.SelectAll
Set shGroup = ActiveWindow.Selection.ShapeRange
shGroup.Export ap.Path & "\Slide" & sl.SlideIndex & ".png", _
ppShapeFormatPNG, , , ppRelativeToSlide
Next
End Sub
Check out the Maven Properties Guide...
As Seshagiri pointed out in the comments, ${env.VARIABLE_NAME}
will do what you want.
I will add a word of warning and say that a pom.xml
should completely describe your project so please use environment variables judiciously. If you make your builds dependent on your environment, they are harder to reproduce
I have routine in VB ..
but you should have 2 pictureboxes .. 1 for frame .. 1 for the image .. and it make keep the picture's size ratio
Assumed picFrame is the image frame and picImg is the image
Sub InsertPicture(ByVal oImg As Image)
Dim oFoto As Image
Dim x, y As Integer
oFoto = oImg
picImg.Visible = False
picImg.Width = picFrame.Width - 2
picImg.Height = picFrame.Height - 2
picImg.Location = New Point(1, 1)
SetPicture(picPreview, oFoto)
x = (picImg.Width - picFrame.Width) / 2
y = (picImg.Height - picFrame.Height) / 2
picImg.Location = New Point(x, y)
picImg.Visible = True
End Sub
I'm sure you can make it as C# ....
The method join()
blocks the calling thread until the thread whose join() method is called is terminated.
I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue)
as a parameter, but the Queue
class is abstract. I solved that by using a QueuePtr(myQueue)
constructor like so:
using QueuePtr = std::unique_ptr<Queue>;
and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue
when you make a std::unique_ptr
of its type, which can't happen.
use a temporary scan.nextLine();
this will consume the \n character
try below code
Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)
The "0x" counts towards the eight character count. You need "%#010x"
.
Note that #
does not append the 0x to 0 - the result will be 0000000000
- so you probably actually should just use "0x%08x"
anyway.
Java does not provide very full-featured splitting utilities, so the Guava libraries do:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
Check out the Javadoc for Splitter; it's very powerful.
This was the best solution for me, just follow this path C:\Users\yourusername.gradle\wrapper\dists then delete all the files inside this folder. Close your android studio and restart it and it will automatically download the updated gradle files.
I noticed some of the answers were not triggering the HTML5 required
attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):
<form id='xform'></form>
with some inputs with the required attribute and place a <input type='submit'>
at the end.<input type='text' name='xconf' value='' required>
modal_1_accept
to the accept button.modal_2_accept
to the accept button.m2_Txt
to the displayed text holder.The JS to intercept before the form is sent:
$("#xform").submit(function(e){
var msg, conf, preventSend;
if($("#xform").attr("data-send")!=="ready"){
msg="Error."; //default error msg
preventSend=false;
conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
if(conf===""){
msg="The field is empty.";
preventSend=true;
}else if(conf!=="ok"){
msg="You didn't write \"ok\" correctly.";
preventSend=true;
}
if(preventSend){ //validation failed, show the error
$("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
$("#modal_2_errMsg").modal("show");
}else{ //validation passed, now let's confirm the action
$("#modal_1_confirm").modal("show");
}
e.preventDefault();
return false;
}
});
`9. Also some stuff when clicking the Buttons from the modals:
$("#modal_1_accept").click(function(){
$("#modal_1_confirm").modal("hide");
$("#xform").attr("data-send", "ready").submit();
});
$("#modal_2_accept").click(function(){
$("#modal_2_errMsg").modal("hide");
});
Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept")
will assume the validation passed and it will add the "ready"
attribute:
$("#modal_1_confirm").modal("show");
is shown only when it passed
the validation, so clicking $("#modal_1_accept")
should be
unreachable without first getting the form validated.If anyone experiences the error for the same reason why I experience it, here's my solution:
if you had Html.AntiForgeryToken();
change it to @Html.AntiForgeryToken()
I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.
If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:
** UPDATED inline with jQuery changes (thanks Toskan) **
(function($) {
$.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
var indexOfDot = eventType.indexOf(".");
var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";
eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
handler = handler == undefined ? eventData : handler;
eventData = typeof eventData == "function" ? {} : eventData;
return this.each(function() {
var $this = $(this);
var currentAttrListener = this["on" + eventType];
if (currentAttrListener) {
$this.bind(eventType, function(e) {
return currentAttrListener(e.originalEvent);
});
this["on" + eventType] = null;
}
$this.bind(eventType + eventNameSpace, eventData, handler);
var allEvents = $this.data("events") || $._data($this[0], "events");
var typeEvents = allEvents[eventType];
var newEvent = typeEvents.pop();
typeEvents.unshift(newEvent);
});
};
})(jQuery);
Things to note:
You could use a couple approaches. First would be to use the strong tag
Here is an <strong>example of that tag</strong>.
Another approach would be to use the font-weight property. You can achieve inline, or via a class or id. Let's say you're using a class.
.className {
font-weight: bold;
}
Alternatively, you can also use a hard value for font-weight and most fonts support a value between 300 and 700, incremented by 100. For example, the following would be bold:
.className {
font-weight: 700;
}
on my pc I had the same problem and it was because in properties -> security I didn't have the ownership of the file...
$("#singlechatpanel-1").is(':visible');
$("#singlechatpanel-1").is(':hidden');
There is no space allocated for the strings. use array (or) pointers with malloc()
and free()
Other than that
#import <stdio.h>
#import <string.h>
should be
#include <stdio.h>
#include <string.h>
NOTE:
malloc()
ed must be free()
'edn + 1
bytes for a string which is of length n
(the last byte is for \0
)Please you the following code as a reference
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//char *str1 = "First string";
char *str1 = "First string is a big string";
char *str2 = NULL;
if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
strcpy(str2, str1);
printf("str1 : %s \n", str1);
printf("str2 : %s \n", str2);
free(str2);
return 0;
}
import React, {Component} from 'react';
import imagename from './imagename.png'; //image is in the current folder where the App.js exits
class App extends React. Component{
constructor(props){
super(props)
this.state={
imagesrc=imagename // as it is imported
}
}
render(){
return (
<ImageClass
src={this.state.imagesrc}
/>
);
}
}
class ImageClass extends React.Component{
render(){
return (
<img src={this.props.src} height='200px' width='100px' />
);
}
}
export default App;
For anyone interested to implement a DropDown
of custom class
you can follow the bellow steps.
Suppose you have a class called Language
with the following code and a static
method which returns a List<Language>
class Language {
final int id;
final String name;
final String languageCode;
const Language(this.id, this.name, this.languageCode);
}
const List<Language> getLanguages = <Language>[
Language(1, 'English', 'en'),
Language(2, '?????', 'fa'),
Language(3, '????', 'ps'),
];
Anywhere you want to implement a DropDown
you can import
the Language
class first use it as follow
DropdownButton(
underline: SizedBox(),
icon: Icon(
Icons.language,
color: Colors.white,
),
items: getLanguages.map((Language lang) {
return new DropdownMenuItem<String>(
value: lang.languageCode,
child: new Text(lang.name),
);
}).toList(),
onChanged: (val) {
print(val);
},
)
You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"
DISCLAIMER: I wrote this extension
Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.
I've done this to extend Python 2's str()
class, for instance. str()
is a particularly interesting target because of the implicit linkage to quoted data such as 'this'
and 'that'
.
Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad
bit:
extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
After which I can write in the code fed to the preprocessor:
if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.
Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
Tip of the hat to @gniourf_gniourf for clearing up a fundamental misconception.
This answer attempts to provide an overview of the existing answers and to discuss their subtleties and relative merits as well as to provide background information, especially with respect to portability.
Finding files that are executable can refer to two distinct use cases:
Note that in either scenario it may make sense to use find -L ...
instead of just find ...
in order to also find symlinks to executables.
Note that the simplest file-centric case - looking for executables with the executable permissions bit set for ALL three security principals (user, group, other) - will typically, but not necessarily yield the same results as the user-centric scenario - and it's important to understand the difference.
-executable
)The accepted answer commendably recommends -executable
, IF GNU find
is available.
find
comes with most Linux distros
-executable
matches only files the current user can execute (there are edge cases.[1]).The BSD find
alternative offered by the accepted answer (-perm +111
) answers a different, file-centric question (as the answer itself states).
-perm
to answer the user-centric question is impossible, because what is needed is to relate the file's user and group identity to the current user's, whereas -perm
can only test the file's permissions.find
features, the question cannot be answered without involving external utilities.Thus, the best -perm
can do (by itself) is an approximation of -executable
. Perhaps a closer approximation than -perm +111
is -perm -111
, so as to find files that have the executable bit set for ALL security principals (user, group, other) - this strikes me as the typical real-world scenario. As a bonus, it also happens to be POSIX-compliant (use find -L
to include symlinks, see farther below for an explanation):
find . -type f -perm -111 # or: find . -type f -perm -a=x
gniourf_gniourf's answer provides a true, portable equivalent of -executable
, using -exec test -x {} \;
, albeit at the expense of performance.
Combining -exec test -x {} \;
with -perm +111
(i.e., files with at least one executable bit set) may help performance in that exec
needn't be invoked for every file (the following uses the POSIX-compliant equivalent of BSD find -perm +111
/ GNU find -perm /111
; see farther below for an explanation):
find . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) -exec test -x {} \; -print
-perm
)-perm
primary (known as a test in GNU find terminology).
-perm
allows you to test for any file permissions, not just executability.111
), whereas symbolic modes are strings (e.g., a=x
).u
(user), g
(group) and o
(other), or a
to refer to all three. Permissions are expressed as x
for executable, for instance, and assigned to principals using operators =
, +
and -
; for a full discussion, including of octal modes, see the POSIX spec for the chmod
utility.find
:
-
(e.g., -ug=x
) means: match files that have all the permissions specified (but matching files may have additional permissions).755
) means: match files that have this full, exact set of permissions.+
/
[2]File-centric command examples
Note:
+
or /
.!
for NOT (GNU find and BSD find also allow -not
); note that \!
is used in the examples so as to protect !
from shell history expansions-a
for AND (GNU find and BSD find also allow -and
)-o
for OR (GNU find and BSD find also allow -or
)-
, the =
and +
operators can be used interchangeably
(e.g., -u=x
is equivalent to -u+x
- unless you apply -x
later, but there's no point in doing that).,
to join partial modes; AND logic is implied; e.g., -u=x,g=x
means that both the user and the group executable bit must be set.-perm
expression with the NOT primary, !
.-print
, or -perm
; also known as actions and tests in GNU find) are implicitly joined with -a
(logical AND), and that -o
and possibly parentheses (escaped as \(
and \)
for the shell) are needed to implement OR logic.find -L ...
instead of just find ...
is used in order to also match symlinks to executables
-L
instructs find to evaluate the targets of symlinks instead of the symlinks themselves; therefore, without -L
, -type f
would ignore symlinks altogether.# Match files that have ALL executable bits set - for ALL 3 security
# principals (u (user), g (group), o (others)) and are therefore executable
# by *anyone*.
# This is the typical case, and applies to executables in _system_ locations
# (e.g., /bin) and user-installed executables in _shared_ locations
# (e.g., /usr/local/bin), for instance.
find -L . -type f -perm -a=x # -a=x is the same as -ugo=x
# The POSIX-compliant equivalent of `-perm +111` from the accepted answer:
# Match files that have ANY executable bit set.
# Note the need to group the permission tests using parentheses.
find -L . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \)
# A somewhat contrived example to demonstrate the use of a multi-principial
# mode (comma-separated clauses) and negation:
# Match files that have _both_ the user and group executable bit set, while
# also _not_ having the other executable bit set.
find -L . -type f -perm -u=x,g=x \! -perm -o=x
[1] Description of -executable
from man find
as of GNU find 4.4.2:
Matches files which are executable and directories which are searchable (in a file name resolution sense). This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.
[2] GNU find versions older than 4.5.12 also allowed prefix +
, but this was first deprecated and eventually removed, because combining +
with symbolic modes yields likely yields unexpected results due to being interpreted as an exact permissions mask. If you (a) run on a version before 4.5.12 and (b) restrict yourself to octal modes only, you could get away with using +
with both GNU find and BSD find, but it's not a good idea.
The precise wording of the question makes me think it's impossible.
return
to me means you have a function, which you have passed a string as a parameter.
You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.
>>> def removeAndReturnLastCharacter(a):
c = a[-1]
a = a[:-1]
return c
>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!
>>> b # b has not been changed
Hello, Gaukler!
try {
// THIS for POST+JSON
options.contentType = 'application/json';
options.type = 'POST';
options.data = JSON.stringify(options.data);
// OR THIS for GET+URL-encoded
//options.data = $.param(_.clone(options.data));
console.log('.fetch options = ', options);
collection.fetch(options);
} catch (excp) {
alert(excp);
}
Here's a Boolean thing:
if (not suffix == "flac" ) or (not suffix == "cue" ): # WRONG! FAILS
print filename + ' is not a flac or cue file'
but
if not (suffix == "flac" or suffix == "cue" ): # CORRECT!
print filename + ' is not a flac or cue file'
(not a) or (not b) == not ( a and b )
,
is false only if a and b are both true
not (a or b)
is true only if a and be are both false.
I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2);
will return 600.23
First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast
or return NULL
pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:
DerivedType m_derivedType = m_baseType;
Here there is no casting. You are creating a new object of type DerivedType
and try to initialize it with value of m_baseType variable.
Next line is not much better:
DerivedType m_derivedType = (DerivedType)m_baseType;
Here you are creating a temporary of DerivedType
type initialized with m_baseType
value.
The last line
DerivedType * m_derivedType = (DerivedType*) & m_baseType;
should compile provided that BaseType
is a direct or indirect public base class of DerivedType
. It has two flaws anyway:
static_cast<DerivedType *>(&m_baseType)
BaseType m_baseType;
so any use of m_derivedType
pointer will result in undefined behaviour.For most multiline strings using an XML element with an inner CDATA block is easier to avoid having to escape anything for simple raw string data.
Dim s as string = <s><![CDATA[Line 1
line 2
line 3]]></s>.Value
Note that I've seen many people state the same format but without the wrapping "< s >" tag (just the CDATA block) but visual studio Automatic formatting seams to alter the leading whitespace of each line then. I think this is due to the object inheritance structure behind the Linq "X" objects. CDATA is not a "Container", the outer block is an XElement which inherits from XContainer.
abstraction is hiding non useful data from users and encapsulation is bind together data into a capsule (a class). I think encapsulation is way that we achieve abstraction.
Here's roughly how C# handles this problem (but expressed as Java code). Something like this could handle almost all your needs:
import static org.util.function.Functions.*;
public class Test {
public static void main(String[] args)
{
Test.invoke((a, b) -> a + b);
}
public static void invoke(Func2<Integer, Integer, Integer> func)
{
System.out.println(func.apply(5, 6));
}
}
package org.util.function;
public interface Functions {
//Actions:
public interface Action {
public void apply();
}
public interface Action1<T1> {
public void apply(T1 arg1);
}
public interface Action2<T1, T2> {
public void apply(T1 arg1, T2 arg2);
}
public interface Action3<T1, T2, T3> {
public void apply(T1 arg1, T2 arg2, T3 arg3);
}
public interface Action4<T1, T2, T3, T4> {
public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
}
public interface Action5<T1, T2, T3, T4, T5> {
public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public interface Action6<T1, T2, T3, T4, T5, T6> {
public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
}
public interface Action7<T1, T2, T3, T4, T5, T6, T7> {
public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
}
public interface Action8<T1, T2, T3, T4, T5, T6, T7, T8> {
public void apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
}
//Functions:
public interface Func<TResult> {
public TResult apply();
}
public interface Func1<T1, TResult> {
public TResult apply(T1 arg1);
}
public interface Func2<T1, T2, TResult> {
public TResult apply(T1 arg1, T2 arg2);
}
public interface Func3<T1, T2, T3, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3);
}
public interface Func4<T1, T2, T3, T4, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
}
public interface Func5<T1, T2, T3, T4, T5, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
}
public interface Func6<T1, T2, T3, T4, T5, T6, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
}
public interface Func7<T1, T2, T3, T4, T5, T6, T7, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
}
public interface Func8<T1, T2, T3, T4, T5, T6, T7, T8, TResult> {
public TResult apply(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
}
}
Just adding to this list. I was having trouble this morning with a new user just added to an AWS EC2 instance. To cut to the chase, the problem was selinux (which was in enforcing mode), together with the fact that my user home dir was on a new EBS attached volume. Somehow I guess selinux doesn't like that other volume. Took me a while to figure out, as I looked through all the other usual ssh issues (/etc/ssh/sshd_config was fine, of course no password allowed, permissions were right, etc.)
The fix?
For now (until I understand how to allow a user to ssh to a different volume, or somehow make that volume a bona fide home dir point):
sudo perl -pi -e 's/^SELINUX=enforcing/SELINUX=permissive/' /etc/selinux/config
sudo setenforce 0
That's it. Now my new user can log in, using his own id_rsa key.
Initially my repo said "Already up to date."
MINGW64 (feature/Issue_123)
$ git merge develop
Output:
Already up to date.
But the code is not up to date & it is showing some differences in some files.
MINGW64 (feature/Issue_123)
$ git diff develop
Output:
diff --git
a/src/main/database/sql/additional/pkg_etl.sql
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql
However, merging fixes it.
MINGW64 (feature/Issue_123)
$ git merge origin/develop
Output:
Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)
Again I have confirmed this by using diff
command.
MINGW64 (feature/Issue_123)
$ git diff develop
No differences in the code now!
Not sure if any of these help, but this might get you started: http://studiostyles.info
I know that the site owner has been gradually adding functionality to allow support for new color assignments, so perhaps there's something there.
Both perform shallow copies as @PatrickDesjardins said (despite the many misled souls who think that CopyTo
does a deep copy).
However, CopyTo
allows you to copy one array to a specified index in the destination array, giving it significantly more flexibility.
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
Even if the generics problems are fixed in 1.3
the great thing about this method is it works on any class that has an isEmpty()
method! Not just Collections
!
For example it will work on String
as well!
/* Matches any class that has an <code>isEmpty()</code> method
* that returns a <code>boolean</code> */
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
@Factory
public static <T> Matcher<T> empty()
{
return new IsEmpty<T>();
}
@Override
protected boolean matchesSafely(@Nonnull final T item)
{
try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
catch (final NoSuchMethodException e) { return false; }
catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
}
@Override
public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}
The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.
Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u@\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
OP's sample code is incorrect.
Endian conversion works at the bit and 8-bit byte level. Most endian issues deal with the byte level. OP code is doing a endian change at the 4-bit nibble level. Recommend instead:
// Swap endian (big to little) or (little to big)
uint32_t num = 9;
uint32_t b0,b1,b2,b3;
uint32_t res;
b0 = (num & 0x000000ff) << 24u;
b1 = (num & 0x0000ff00) << 8u;
b2 = (num & 0x00ff0000) >> 8u;
b3 = (num & 0xff000000) >> 24u;
res = b0 | b1 | b2 | b3;
printf("%" PRIX32 "\n", res);
If performance is truly important, the particular processor would need to be known. Otherwise, leave it to the compiler.
[Edit] OP added a comment that changes things.
"32bit numerical value represented by the hexadecimal representation (st uv wx yz) shall be recorded in a four-byte field as (st uv wx yz)."
It appears in this case, the endian of the 32-bit number is unknown and the result needs to be store in memory in little endian order.
uint32_t num = 9;
uint8_t b[4];
b[0] = (uint8_t) (num >> 0u);
b[1] = (uint8_t) (num >> 8u);
b[2] = (uint8_t) (num >> 16u);
b[3] = (uint8_t) (num >> 24u);
[2016 Edit] Simplification
... The type of the result is that of the promoted left operand.... Bitwise shift operators C11 §6.5.7 3
Using a u
after the shift constants (right operands) results in the same as without it.
b3 = (num & 0xff000000) >> 24u;
b[3] = (uint8_t) (num >> 24u);
// same as
b3 = (num & 0xff000000) >> 24;
b[3] = (uint8_t) (num >> 24);
Use reflection
System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
If you know the child element you're interested in is the first:
$('.second').children().first();
Or to find by index:
var index = 0
$('.second').children().eq(index);
There are several options. If performance is a concern, test them to see which works fastest in a large loop.
double Adjust(double input)
{
double whole = Math.Truncate(input);
double remainder = input - whole;
if (remainder < 0.3)
{
remainder = 0;
}
else if (remainder < 0.8)
{
remainder = 0.5;
}
else
{
remainder = 1;
}
return whole + remainder;
}
Here is a base R one liner that overlaps a number of previous solutions, but returns a data.frame with the proper names.
out <- setNames(data.frame(before$attr,
do.call(rbind, strsplit(as.character(before$type),
split="_and_"))),
c("attr", paste0("type_", 1:2)))
out
attr type_1 type_2
1 1 foo bar
2 30 foo bar_2
3 4 foo bar
4 6 foo bar_2
It uses strsplit
to break up the variable, and data.frame
with do.call
/rbind
to put the data back into a data.frame. The additional incremental improvement is the use of setNames
to add variable names to the data.frame.
You might want to consider using some algorithms instead:
// read in the data:
std::copy(std::istream_iterator<double>(input),
std::istream_iterator<double>(),
std::back_inserter(v));
sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();
You can modify the values with std::transform
, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:
class difference {
double base;
public:
difference(double b) : base(b) {}
double operator()(double v) { return v-base; }
};
std::transform(v.begin(), v.end(), v.begin(), difference(average));
A few more things in addition to the existing answers. Have a look at this:
var seatsValid = true;
// cache the selector
var seatsVal = $("#seats").val();
if(seatsVal!=''){
seatsValid = false;
alert("Not a valid character")
// convert seatsVal to an integer for comparison
}else if(parseInt(seatsVal) < 99999){
seatsValid = false;
alert("Not a valid Number");
}
The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid). I also initialized it to true which gets rid of the need for the final else in your original code. Next, I put the selector and call to .val() in a variable. It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to. Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.
It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:
For example, you might use the following code to increment a counter in XML in C#.
Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);
By using the DLR, you could use the following code instead for the same operation.
scriptobj.Count += 1;
MSDN lists these advantages:
- Simplifies Porting Dynamic Languages to the .NET Framework
- Enables Dynamic Features in Statically Typed Languages
- Provides Future Benefits of the DLR and .NET Framework
- Enables Sharing of Libraries and Objects
- Provides Fast Dynamic Dispatch and Invocation
See MSDN for more details.
Yes, just override the printMe()
method:
class Son extends Dad {
public static final String me = "son";
@Override
public void printMe() {
System.out.println(me);
}
}
Two options save vijay.sql
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
and then run as sqlplus -s username/password @vijay.sql '20100101'
Was facing a similar issue yesterday with our CI server. The app extension could not be signed with the error
Code Sign error: No matching provisioning profiles found: No provisioning profiles with a valid signing identity (i.e. certificate and private key pair) matching the bundle identifier XXX were found.
Note: I had created my provisioning profiles myself from Developer portal (not managed by Xcode).
The error was that I had created the provisioning profiles using the Distribution certificate, but the build settings were set to use the developer certificate. Changing it to use Distribution certificate solved the issue.
Summary: Match the certificate used for creating the provisioning profile in build settings too.
If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:
Kibana => DevTools => Console:
GET /_cluster/health
fieldset {
min-width: 0;
max-width: 100%;
width: 100%;
}
The withColumn function in pyspark enables you to make a new variable with conditions, add in the when and otherwise functions and you have a properly working if then else structure. For all of this you would need to import the sparksql functions, as you will see that the following bit of code will not work without the col() function. In the first bit, we declare a new column -'new column', and then give the condition enclosed in when function (i.e. fruit1==fruit2) then give 1 if the condition is true, if untrue the control goes to the otherwise which then takes care of the second condition (fruit1 or fruit2 is Null) with the isNull() function and if true 3 is returned and if false, the otherwise is checked again giving 0 as the answer.
from pyspark.sql import functions as F
df=df.withColumn('new_column',
F.when(F.col('fruit1')==F.col('fruit2'), 1)
.otherwise(F.when((F.col('fruit1').isNull()) | (F.col('fruit2').isNull()), 3))
.otherwise(0))
You need to install Node . Visiti this link
[1]: https://nodejs.org/en/ and follow the instructions.
Swift 2.0 you can initialize Integer using constructor
var stringNumber = "1234"
var numberFromString = Int(stringNumber)
imprime en linea los datos con un espaciado determinado, así tendrás columnas de datos de la misma variable y será más claro
Print all data in line, so you have rows with the data you need, i just solve the same problem like this, just make sur you had asignad a constant data size and spacement between, I made this
Serial.print("cuenta q2: ");
Serial.print( cuenta_pulsos_encoder_1,3);
Serial.print("\t");
Serial.print(q2_real,4);
Serial.print("\t");
Serial.print("cuenta q3: ");
Serial.print( cuenta_pulsos_encoder_2,3);
Serial.print("\t");
Serial.print(q3_real,4);
Serial.print("\t");
Serial.print("cuenta q4: ");
Serial.print( cuenta_pulsos_encoder_3,3);
Serial.print("\t");
Serial.println(q4_real,4);
Apache Commons collection classes is the solution.
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMap.get("fruit"));
// Mango Orange Blueberry
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --
>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
System.setProperty("webdriver.gecko.driver", "C:\\gecko\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = new FirefoxDriver();
The @
means that the file has extended file attributes associated with it. You can query them using the getxattr()
function.
There's no definite way to detect the encoding of a file. Read this answer, it explains why.
There's a command line tool, enca, that attempts to guess the encoding. You might want to check it out.
https://www.w3schools.com/tags/av_event_timeupdate.asp
// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");
// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};
function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
document.getElementById("demo").innerHTML = vid.currentTime;
}
I too had this problem, when I checked I image that I was pulling from a private registry was removed If we describe pod it will show pulling event and the image it's trying to pull
kubectl describe pod <POD_NAME>
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Pulling 18h (x35 over 20h) kubelet, gsk-kub Pulling image "registeryName:tag"
Normal BackOff 11m (x822 over 20h) kubelet, gsk-kub Back-off pulling image "registeryName:tag"
Warning Failed 91s (x858 over 20h) kubelet, gsk-kub Error: ImagePullBackOff
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
Tested the wink solution, and working fine:
@Test
public void testJSONObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("bbb", "xxx");
jsonObject.put("ccc", "xxx");
jsonObject.put("aaa", "xxx");
jsonObject.put("xxx", "xxx");
System.out.println(jsonObject.toString());
assertTrue(jsonObject.toString().startsWith("{\"xxx\":"));
}
@Test
public void testWinkJSONObject() throws JSONException {
org.apache.wink.json4j.JSONObject jsonObject = new OrderedJSONObject();
jsonObject.put("bbb", "xxx");
jsonObject.put("ccc", "xxx");
jsonObject.put("aaa", "xxx");
jsonObject.put("xxx", "xxx");
assertEquals("{\"bbb\":\"xxx\",\"ccc\":\"xxx\",\"aaa\":\"xxx\",\"xxx\":\"xxx\"}", jsonObject.toString());
}
I use the following Interactivity Behavior to provide an unloading event to WPF UserControls. You can include the behavior in the UserControls XAML. So you can have the functionality without placing the logic it in every single UserControl.
XAML declaration:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<i:Interaction.Behaviors>
<behaviors:UserControlSupportsUnloadingEventBehavior UserControlClosing="UserControlClosingHandler" />
</i:Interaction.Behaviors>
CodeBehind handler:
private void UserControlClosingHandler(object sender, EventArgs e)
{
// to unloading stuff here
}
Behavior Code:
/// <summary>
/// This behavior raises an event when the containing window of a <see cref="UserControl"/> is closing.
/// </summary>
public class UserControlSupportsUnloadingEventBehavior : System.Windows.Interactivity.Behavior<UserControl>
{
protected override void OnAttached()
{
AssociatedObject.Loaded += UserControlLoadedHandler;
}
protected override void OnDetaching()
{
AssociatedObject.Loaded -= UserControlLoadedHandler;
var window = Window.GetWindow(AssociatedObject);
if (window != null)
window.Closing -= WindowClosingHandler;
}
/// <summary>
/// Registers to the containing windows Closing event when the UserControl is loaded.
/// </summary>
private void UserControlLoadedHandler(object sender, RoutedEventArgs e)
{
var window = Window.GetWindow(AssociatedObject);
if (window == null)
throw new Exception(
"The UserControl {0} is not contained within a Window. The UserControlSupportsUnloadingEventBehavior cannot be used."
.FormatWith(AssociatedObject.GetType().Name));
window.Closing += WindowClosingHandler;
}
/// <summary>
/// The containing window is closing, raise the UserControlClosing event.
/// </summary>
private void WindowClosingHandler(object sender, CancelEventArgs e)
{
OnUserControlClosing();
}
/// <summary>
/// This event will be raised when the containing window of the associated <see cref="UserControl"/> is closing.
/// </summary>
public event EventHandler UserControlClosing;
protected virtual void OnUserControlClosing()
{
var handler = UserControlClosing;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
A handle is whatever you want it to be.
A handle can be a unsigned integer used in some lookup table.
A handle can be a pointer to, or into, a larger set of data.
It depends on how the code that uses the handle behaves. That determines the handle type.
The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.
For a start, you have them backwards: &
is reference and *
is dereference.
Referencing a variable means accessing the memory address of the variable:
int i = 5;
int * p;
p = &i; //&i returns the memory address of the variable i.
Dereferencing a variable means accessing the variable stored at a memory address:
int i = 5;
int * p;
p = &i;
*p = 7; //*p returns the variable stored at the memory address stored in p, which is i.
//i is now 7
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
// Below will handle proper sizes
public static String binaryString(int i) {
return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}
public static String binaryString(long i) {
return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}
If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:
newidx = []
for (n1,n2) in df.columns.ravel():
newidx.append("%s-%s" % (n1,n2))
df.columns=newidx
It will change your dataframe from:
I V
mean std first
V
4200.0 25.499536 31.557133 4200.0
4300.0 25.605662 31.678046 4300.0
4400.0 26.679005 32.919996 4400.0
4500.0 26.786458 32.811633 4500.0
to
I-mean I-std V-first
V
4200.0 25.499536 31.557133 4200.0
4300.0 25.605662 31.678046 4300.0
4400.0 26.679005 32.919996 4400.0
4500.0 26.786458 32.811633 4500.0
Not possible through mockito. From their wiki
Why Mockito doesn't mock private methods?
Firstly, we are not dogmatic about mocking private methods. We just don't care about private methods because from the standpoint of testing private methods don't exist. Here are a couple of reasons Mockito doesn't mock private methods:
It requires hacking of classloaders that is never bullet proof and it changes the api (you must use custom test runner, annotate the class, etc.).
It is very easy to work around - just change the visibility of method from private to package-protected (or protected).
It requires me to spend time implementing & maintaining it. And it does not make sense given point #2 and a fact that it is already implemented in different tool (powermock).
Finally... Mocking private methods is a hint that there is something wrong with OO understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.
A great resource is iosfonts.com, which says that the name for that font is HelveticaNeue-UltraLight
. So you'd use this code:
label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30)
If the system can't find the font, it defaults to a 'normal' font - I think it's something like 11-point Helvetica. This can be quite confusing, always check your font names.
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
1. Choose project, right click, in context menu, choose Show in Explorer
(on Mac, select Reveal in Finder
).
2. Choose menu File \ Close Project
3. In Windows Explorer, press Del or Shift+Del for permanent delete.
4. At IntelliJ IDEA startup windows, hover cursor on old project name (what has been deleted) press Del for delelte.
Try This:
$.ajax({
url:"",
type: "POST",
data: new FormData($('#uploadDatabaseForm')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
Here's a simple hash function that I use for a hash table I built. Its basically for taking a text file and stores every word in an index which represents the alphabetical order.
int generatehashkey(const char *name)
{
int x = tolower(name[0])- 97;
if (x < 0 || x > 25)
x = 26;
return x;
}
What this basically does is words are hashed according to their first letter. So, word starting with 'a' would get a hash key of 0, 'b' would get 1 and so on and 'z' would be 25. Numbers and symbols would have a hash key of 26. THere is an advantage this provides; You can calculate easily and quickly where a given word would be indexed in the hash table since its all in an alphabetical order, something like this: Code can be found here: https://github.com/abhijitcpatil/general
Giving the following text as input: Atticus said to Jem one day, “I’d rather you shot at tin cans in the backyard, but I know you’ll go after birds. Shoot all the blue jays you want, if you can hit ‘em, but remember it’s a sin to kill a mockingbird.” That was the only time I ever heard Atticus say it was a sin to do something, and I asked Miss Maudie about it. “Your father’s right,” she said. “Mockingbirds don’t do one thing except make music for us to enjoy. They don’t eat up people’s gardens, don’t nest in corn cribs, they don’t do one thing but sing their hearts out for us. That’s why it’s a sin to kill a mockingbird.
This would be the output:
0 --> a a about asked and a Atticus a a all after at Atticus
1 --> but but blue birds. but backyard
2 --> cribs corn can cans
3 --> do don’t don’t don’t do don’t do day
4 --> eat enjoy. except ever
5 --> for for father’s
6 --> gardens go
7 --> hearts heard hit
8 --> it’s in it. I it I it’s if I in
9 --> jays Jem
10 --> kill kill know
11 -->
12 --> mockingbird. music make Maudie Miss mockingbird.”
13 --> nest
14 --> out one one only one
15 --> people’s
16 --> 17 --> right remember rather
18 --> sin sing said. she something sin say sin Shoot shot said
19 --> to That’s their thing they They to thing to time the That to the the tin to
20 --> us. up us
21 -->
22 --> why was was want
23 -->
24 --> you you you’ll you
25 -->
26 --> “Mockingbirds ” “Your ‘em “I’d
d = {}
# import list of year,value pairs
for year,value in mylist:
try:
d[year].append(value)
except KeyError:
d[year] = [value]
The Python way - it is easier to receive forgiveness than ask permission!
Using Java Class
new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Using Annotation
@JsonIgnoreProperties(ignoreUnknown=true)
You can use the find function:
if($('#popup').find('p.filled-text').length !== 0)
// Do Stuff
Function was written to handle seeding of randomized set creation. You should not rely on set splitting that doesn't randomize the sets.
import numpy as np
import pandas as pd
def train_validate_test_split(df, train_percent=.6, validate_percent=.2, seed=None):
np.random.seed(seed)
perm = np.random.permutation(df.index)
m = len(df.index)
train_end = int(train_percent * m)
validate_end = int(validate_percent * m) + train_end
train = df.iloc[perm[:train_end]]
validate = df.iloc[perm[train_end:validate_end]]
test = df.iloc[perm[validate_end:]]
return train, validate, test
np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE'))
df
train, validate, test = train_validate_test_split(df)
train
validate
test
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
Quick fix:
/etc/paths
In my case /etc/paths
looks like:
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
If you want to know more about paths in OSX I found this article quite useful:
http://muttsnutts.github.com/blog/2011/09/12/manage-path-on-mac-os-x-lion/
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
This a simpler method , and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
You can give a try to my jQuery plugin, FixTo.
Usage:
$('#mydiv').fixTo('#centeredContainer');
Stored procedure to insert multiple records using single insertion:
ALTER PROCEDURE [dbo].[Ins]
@i varchar(50),
@n varchar(50),
@a varchar(50),
@i1 varchar(50),
@n1 varchar(50),
@a1 varchar(50),
@i2 varchar(50),
@n2 varchar(50),
@a2 varchar(50)
AS
INSERT INTO t1
SELECT @i AS Expr1, @i1 AS Expr2, @i2 AS Expr3
UNION ALL
SELECT @n AS Expr1, @n1 AS Expr2, @n2 AS Expr3
UNION ALL
SELECT @a AS Expr1, @a1 AS Expr2, @a2 AS Expr3
RETURN
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = new SqlCommand("Ins",cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@i",TextBox1.Text);
cmd.Parameters.AddWithValue("@n",TextBox2.Text);
cmd.Parameters.AddWithValue("@a",TextBox3.Text);
cmd.Parameters.AddWithValue("@i1",TextBox4.Text);
cmd.Parameters.AddWithValue("@n1",TextBox5.Text);
cmd.Parameters.AddWithValue("@a1",TextBox6.Text);
cmd.Parameters.AddWithValue("@i2",TextBox7.Text);
cmd.Parameters.AddWithValue("@n2",TextBox8.Text);
cmd.Parameters.AddWithValue("@a2",TextBox9.Text);
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("inserted");
clear();
}
While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:
ng-click="hidePrefs()"
and then in your controller:
$scope.hidePrefs = function() {
$scope.prefs = false;
}
From user @jamylak an alternative form of open("filename","w").close()
is
with open('filename.txt','w'): pass
You can use the substr
function like this:
echo substr($myStr, 0, 5);
The second argument to substr
is from what position what you want to start and third arguments is for how many characters you want to return.
Another approach for same issue may help you Read and write file in private context of application
String NOTE = "note.txt";
private void writeToFile() {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
NOTES, 0));
out.write("testing");
out.close();
}
catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}
private void ReadFromFile()
{
try {
InputStream in = openFileInput(NOTES);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
String temp = "Not Working";
temp = buf.toString();
Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}
No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled
to chnage line endings from LF to CRLF:
open Sublime and follow the steps:-
1 press Ctrl+shift+p then install package name line unify endings
then again press Ctrl+shift+p
2 in the blank input box type "Line unify ending "
3 Hit enter twice
Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF
An alternative to setting the system property on tomcat configuration is to use CATALINA_OPTS environment variable
You can use CSS3 font-face
or webfonts
@font-face usage
@font-face {
font-family: Delicious;
src: url('Delicious-Roman.otf');
}
webfonts
take a look at Google Webfonts, http://www.google.com/webfonts
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
You can use include=FALSE
to exclude everything in a chunk.
```{r include=FALSE}
source("C:/Rscripts/source.R")
```
If you only want to suppress messages, use message=FALSE
instead:
```{r message=FALSE}
source("C:/Rscripts/source.R")
```
Link order certainly does matter, at least on some platforms. I have seen crashes for applications linked with libraries in wrong order (where wrong means A linked before B but B depends on A).
This has happened to me. My issue was caused when I didn't mount Docker file system correctly, so I configured the Disk Image Location and re-bind File sharing mount, and this now worked correctly. For reference, I use Docker Desktop in Windows.
What if you use a character-based BufferedReader instead of byte-based InputStream?
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
...
line = reader.readLine();
}
Don't forget that readLine()
skips the new-lines!
There is a simple solution to this problem using this library. I store an instance of the CallRecord class in MyService.class. When the service is first initialized, the following code is executed:
public class MyService extends Service {
public static CallRecord callRecord;
@Override
public void onCreate() {
super.onCreate();
callRecord = new CallRecord.Builder(this)
.setRecordFileName("test")
.setRecordDirName("Download")
.setRecordDirPath(Environment.getExternalStorageDirectory().getPath()) // optional & default value
.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) // optional & default value
.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB) // optional & default value
.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION) // optional & default value
.setShowSeed(false) // optional, default=true ->Ex: RecordFileName_incoming.amr || RecordFileName_outgoing.amr
.build();
callRecord.enableSaveFile();
callRecord.startCallReceiver();
}
@Override
public void onDestroy() {
super.onDestroy();
callRecord.stopCallReceiver();
}
}
Next, do not forget to specify permissions in the manifest. (I may have some extras here, but keep in mind that some of them are necessary only for newer versions of Android)
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also it is crucial to request some permissions at the first start of the application. A guide is provided here.
If my code doesn't work, alternative code can be found here. I hope I helped you.
Simple but works well for me
FileName = ActiveWorkbook.Name
If InStr(FileName, ".") > 0 Then
FileName = Left(FileName, InStr(FileName, ".") - 1)
End If
You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.
The general form for this would be an UPDATE
statement:
UPDATE <table name>
SET
ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
ColumnA = <bad value> /* or any other search conditions */
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { EmailComposer } from '@ionic-native/email-composer';
@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
sendObj = {
to: '',
cc: '',
bcc: '',
attachments:'',
subject:'',
body:''
}
constructor(public navCtrl: NavController,private emailComposer: EmailComposer) {}
sendEmail(){
let email = {
to: this.sendObj.to,
cc: this.sendObj.cc,
bcc: this.sendObj.bcc,
attachments: [this.sendObj.attachments],
subject: this.sendObj.subject,
body: this.sendObj.body,
isHtml: true
};
this.emailComposer.open(email);
}
}
starts here html about
<ion-header>
<ion-navbar>
<ion-title>
Send Invoice
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label stacked>To</ion-label>
<ion-input [(ngModel)]="sendObj.to"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>CC</ion-label>
<ion-input [(ngModel)]="sendObj.cc"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>BCC</ion-label>
<ion-input [(ngModel)]="sendObj.bcc"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Add pdf</ion-label>
<ion-input [(ngModel)]="sendObj.attachments" type="file"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Subject</ion-label>
<ion-input [(ngModel)]="sendObj.subject"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>Text message</ion-label>
<ion-input [(ngModel)]="sendObj.body"></ion-input>
</ion-item>
<button ion-button full (click)="sendEmail()">Send Email</button>
</ion-content>
other stuff here
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';
import { EmailComposer } from '@ionic-native/email-composer';
@NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
EmailComposer,
{provide: ErrorHandler, useClass: IonicErrorHandler},
File,
FileOpener
]
})
export class AppModule {}
Like said in docs, use
<meta property="og:url" content="http://www.your-domain.com/your-page.html" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Your Website Title" />
<meta property="og:description" content="Your description" />
<meta property="og:image" content="http://www.your-domain.com/path/image.jpg" />
image size recommended: 1 200 x 630
Here is my solution - The method takes an array of integers(assuming the range between 0 to 100) as input and returns the number of occurrences of each element.
let's say the input is [21,34,43,21,21,21,45,65,65,76,76,76]
.
So the output would be in a map and it is: {34=1, 21=4, 65=2, 76=3, 43=1, 45=1}
public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) {
int[] possibleNumbers = new int[100];
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (int i = 0; i < numbersToProcess.length; ++i) {
possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1;
result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]);
}
return result;
}
function mailValidation(val) {
var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}
I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.
Check the JavaDocs of the java.util.concurrent.atomic package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)
For opening a file, try this:
objexcel.Workbooks.Open(@"C:\YourPath\YourExcelFile.xls",
missing, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing,missing, missing);
You must supply those stupid looking 'missing' arguments. If you were writing the same code in VB.Net you wouldn't have needed them, but you can't avoid them in C#.
The Columns collection is only populated when AutoGenerateColumns=false, and you manually generate the columns yourself.
A nice work-around for this is to dynamically populate the Columns collection yourself, before setting the DataSource property and calling DataBind().
I have a function that manually adds the columns based on the contents of the DataTable that I want to display. Once I have done that (and then set the DataSource and called DataBind(), I can use the Columns collection and the Count value is correct, and I can turn the column visibility on and off as I initially wanted to.
static void AddColumnsToGridView(GridView gv, DataTable table)
{
foreach (DataColumn column in table.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName;
gv.Columns.Add(field);
}
}
What about that?
private static List<String> extractString(List<Optional<String>> list) {
List<String> result = new ArrayList<>();
list.forEach(element -> element.ifPresent(result::add));
return result;
}
The accepted answer does not work for databases that have large numbers of tables, e.g. Drupal databases. Instead, see the script here: https://stackoverflow.com/a/12917793/1507877 which does work on MySQL 5.5. CAUTION: Around line 11, there is a "WHERE table_schema = SCHEMA();" This should instead be "WHERE table_schema = 'INSERT NAME OF DB INTO WHICH IMPORT WILL OCCUR';"
For your case you could also look into numpy.bincount
In [56]: a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
In [57]: np.bincount(a)
Out[57]: array([8, 4]) #count of zeros is at index 0 : 8
#count of ones is at index 1 : 4
You can have an auto-Incrementing column that is not the PRIMARY KEY
, as long as there is an index (key) on it:
CREATE TABLE members (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
memberid VARCHAR( 30 ) NOT NULL ,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
firstname VARCHAR( 50 ) NULL ,
lastname VARCHAR( 50 ) NULL ,
PRIMARY KEY (memberid) ,
KEY (id) --- or: UNIQUE KEY (id)
) ENGINE = MYISAM;
You can Implement this also:- setPage(1, n); where, n = any number.
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'price', 'small_image'))
->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
->addAttributeToFilter('status', 1) // enabled
->setStoreId($storeId)
->setOrder('created_at', 'desc')
->setPage(1, 6);
Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.
That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.
One of the few common idioms for inspecting these dictionaries is for easy string interpolation:
>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe
This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.
Be careful with arrays. We must write a checking variable after ?
, because:
$params = ['param1' => 'value1',
'param2' => 'value2',
'param3' => 'value3',];
$param1 = isset($params['param1'])?:null;
$param2 = !empty($params['param2'])?:null;
$param3 = $params['param3']?:null; // get E_NOTICE, if $params['param3'] eq false
var_dump($param1,$param2,$param3);
true // would like to expect `value1`
true // would like to expect `value2`
param3 // properly, but problem above
Updated
From RFC. In PHP 7 the operator Null Coalesce Operator will do it, for example:
$param1 = $params['param1'] ?? null;
// Equivalent to: $param1 = isset($params['param1']) ? $params['param1'] : null;
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.