I'm a bit late but here's how I did this. The steps:
This is the code I used on DataFrame called aft_tmt
. Feel free to extrapolate to your use case..
import pandas as pd
# setting options to print without truncating output
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
import statsmodels.formula.api as smf
import itertools
# This section gets the column names of the DF and removes some columns which I don't want to use as predictors.
itercols = aft_tmt.columns.tolist()
itercols.remove("sc97")
itercols.remove("sc")
itercols.remove("grc")
itercols.remove("grc97")
print itercols
len(itercols)
# results DF
regression_res = pd.DataFrame(columns = ["Rsq", "predictors", "excluded"])
# excluded cols
exc = []
# change 9 to the number of columns you want to combine from N columns.
#Possibly run an outer loop from 0 to N/2?
for x in itertools.combinations(itercols, 9):
lmstr = "+".join(x)
m = smf.ols(formula = "sc ~ " + lmstr, data = aft_tmt)
f = m.fit()
exc = [item for item in x if item not in itercols]
regression_res = regression_res.append(pd.DataFrame([[f.rsquared, lmstr, "+".join([y for y in itercols if y not in list(x)])]], columns = ["Rsq", "predictors", "excluded"]))
regression_res.sort_values(by="Rsq", ascending = False)
for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){
double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT;
}
if you want to get around the + 1 issue
VAR1=value1 VAR2=value2 myScript args ...
I got the error with a space in a Sheet Name:
using (var range = _excelApp.Range["Sheet Name Had Space!$A$1"].WithComCleanup())
I fixed it by putting single quotes around Sheet Names with spaces:
using (var range = _excelApp.Range["'Sheet Name Had Space'!$A$1"].WithComCleanup())
I had a lot of trouble with the ExecuteSqlCommand
and ExecuteSqlCommandAsync
, IN parameters were easy, but OUT parameters were very difficult.
I had to revert to using DbCommand
like so -
DbCommand cmd = _context.Database.GetDbConnection().CreateCommand();
cmd.CommandText = "dbo.sp_DoSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@firstName", SqlDbType.VarChar) { Value = "Steve" });
cmd.Parameters.Add(new SqlParameter("@lastName", SqlDbType.VarChar) { Value = "Smith" });
cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.BigInt) { Direction = ParameterDirection.Output });
I wrote more about it in this post.
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
Using double
to store large integers is dubious; the largest integer that can be stored reliably in double
is much smaller than DBL_MAX
. You should use long long
, and if that's not enough, you need your own arbitrary-precision code or an existing library.
tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.
pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.
I was passing the values without the quotes. Once I passed the conditions inside the single quotes worked like a charm.
Select * from emp_table where emp_id=123;
instead of the above use this:
Select * from emp_table where emp_id='123';
This version works better on Windows than the top answer because it understands both /
and path.sep
so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd
).
/**
* Creates a folder and if necessary, parent folders also. Returns true
* if any folders were created. Understands both '/' and path.sep as
* path separators. Doesn't try to create folders that already exist,
* which could cause a permissions error. Gracefully handles the race
* condition if two processes are creating a folder. Throws on error.
* @param targetDir Name of folder to create
*/
export function mkdirSyncRecursive(targetDir) {
if (!fs.existsSync(targetDir)) {
for (var i = targetDir.length-2; i >= 0; i--) {
if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
mkdirSyncRecursive(targetDir.slice(0, i));
break;
}
}
try {
fs.mkdirSync(targetDir);
return true;
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
return false;
}
Just think of bool? as having 3 values, then things get easier:
if (someNullableBool == true) // only if true
if (someNullableBool == false) // only if false
if (someNullableBool == null) // only if null
Adding up to other answers you need to export the class to use in a different class. This is a typescript version of it.
//Constants.tsx
const DEBUG: boolean = true;
export class Constants {
static get DEBUG(): boolean {
return DEBUG;
}
}
//Anotherclass.tsx
import { Constants } from "Constants";
if (Constants.DEBUG) {
console.log("debug mode")
}
_x000D_
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
DELETE FROM table_name
WHERE id BETWEEN 79 AND 296;
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
Here's what I ended up with. This works for me if I import my script in the interpreter, and also if I execute it as a script:
import os
import sys
# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path)
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
Try Shift-Tab-Tab
a bigger documentation appears, than with Shift-Tab
. It's the same but you can scroll down.
Shift-Tab-Tab-Tab
and the tooltip will linger for 10 seconds while you type.
Shift-Tab-Tab-Tab-Tab
and the docstring appears in the pager (small part at the bottom of the window) and stays there.
The following css statement disables click events
pointer-events:none;
The new File System Access API will make our life easy again :)
try {
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
// ...
}
catch (e) {
console.log('Cancelled, no file selected');
}
Browser support is very limited (Jan, 2021). The example code works well in Chrome Desktop 86.
Try this:
.greenText{ background-color:green; }_x000D_
_x000D_
.blueText{ background-color:blue; }_x000D_
_x000D_
.redText{ background-color:red; }
_x000D_
<select_x000D_
onchange="this.className=this.options[this.selectedIndex].className"_x000D_
class="greenText">_x000D_
<option class="greenText" value="apple" >Apple</option>_x000D_
<option class="redText" value="banana" >Banana</option>_x000D_
<option class="blueText" value="grape" >Grape</option>_x000D_
</select>
_x000D_
There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with setState
.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper); // creating copy of state variable jasper
jasper.name = 'someothername'; // update the name property, assign a new value
return { jasper }; // return new object jasper object
})
Instead of using Object.assign
we can also write it like this:
let jasper = { ...prevState.jasper };
2- Using spread syntax:
this.setState(prevState => ({
jasper: { // object that we want to update
...prevState.jasper, // keep all other key-value pairs
name: 'something' // update the value of specific key
}
}))
Note: Object.assign
and Spread Operator
creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach.
Assume you have defined state as:
this.state = {
food: {
sandwich: {
capsicum: true,
crackers: true,
mayonnaise: true
},
pizza: {
jalapeno: true,
extraCheese: false
}
}
}
To update extraCheese of pizza object:
this.setState(prevState => ({
food: {
...prevState.food, // copy all other key-value pairs of food object
pizza: { // specific object of food object
...prevState.food.pizza, // copy all pizza key-value pairs
extraCheese: true // update value of specific key
}
}
}))
Lets assume you have a todo app, and you are managing the data in this form:
this.state = {
todoItems: [
{
name: 'Learn React Basics',
status: 'pending'
}, {
name: 'Check Codebase',
status: 'pending'
}
]
}
To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of condition=true
, return the new object with updated value, else same object.
let key = 2;
this.setState(prevState => ({
todoItems: prevState.todoItems.map(
el => el.key === key? { ...el, status: 'done' }: el
)
}))
Suggestion: If object doesn't have a unique value, then use array index.
Old post but as it comes up for what I was searching for I thought I'd add some information to this topic. I was going to add a comment but I don't have enough rep.
As others have said:
connection.ConnectionTimeout is used for the initial connection
command.CommandTimeout is used for individual searches, updates, etc.
But:
connection.ConnectionTimeout is also used for committing and rolling back transactions.
Yes, this is an absolutely insane design decision.
So, if you are running into a timeout on commit or rollback you'll need to increase this value through the connection string.
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
Have a look at: http://www.javaspecialists.eu/archive/Issue068.html and http://www.javaspecialists.eu/archive/Issue105.html
Do the same tests in your environment and check if newer JDK or your Java implementation do some type of string operation better with String
or better with StringBuilder
.
The probably only way which is marginally faster than
d = [[] for x in xrange(n)]
is
from itertools import repeat
d = [[] for i in repeat(None, n)]
It does not have to create a new int
object in every iteration and is about 15 % faster on my machine.
Edit: Using NumPy, you can avoid the Python loop using
d = numpy.empty((n, 0)).tolist()
but this is actually 2.5 times slower than the list comprehension.
We usually use One Main Window
for the application and other windows can be used in situations like when you need popups because instead of using popup controls in XAML which are not visible we can use a Window that is visible at design time so that'll be easy to work with
on the other hand we use many pages to navigate from one screen to another like User management screen to Order Screen etc In the main Window we can use Frame
control for navigation like below
XAML
<Frame Name="mainWinFrame" NavigationUIVisibility="Hidden" ButtonBase.Click="mainWinFrame_Click">
</Frame>
C#
private void mainWinFrame_Click(object sender, RoutedEventArgs e)
{
try
{
if (e.OriginalSource is Button)
{
Button btn = (Button)e.OriginalSource;
if ((btn.CommandParameter != null) && (btn.CommandParameter.Equals("Order")))
{
mainWinFrame.Navigate(OrderPage);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
That's one way of doing it We can also use a Tab Control instead of Fram and Add pages to it using a Dictionary while adding new page check if the control already exists then only navigate otherwise add and navigate. I hope that'll help someone
This is what worked for me:
In the build.gradle
file, setting the minSdkVersion
under defaultConfig
:
Good Luck...
gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(9.491327, 76.571404), 10, 30, 0)));
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
You may also delete gradle file, if you don't use gradle any where else:
rm -Rfv ~/.gradle/
because .gradle folder contains cached artifacts that are no longer needed.
I have encountered this problem in Eclipse Luna EE. My solution was simply restart eclipse and it magically started loading servlet properly.
$('#carousel-example-generic').on('slid.bs.carousel', function () {_x000D_
$(".item.active:nth-child(" + ($(".carousel-inner .item").length -1) + ") + .item").insertBefore($(".item:first-child"));_x000D_
$(".item.active:last-child").insertBefore($(".item:first-child"));_x000D_
});
_x000D_
.item.active,_x000D_
.item.active + .item,_x000D_
.item.active + .item + .item {_x000D_
width: 33.3%;_x000D_
display: block;_x000D_
float:left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="max-width:800px;">_x000D_
<!-- Indicators -->_x000D_
<ol class="carousel-indicators">_x000D_
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>_x000D_
<li data-target="#carousel-example-generic" data-slide-to="1"></li>_x000D_
<li data-target="#carousel-example-generic" data-slide-to="2"></li>_x000D_
</ol>_x000D_
_x000D_
<!-- Wrapper for slides -->_x000D_
<div class="carousel-inner" role="listbox">_x000D_
<div class="item active">_x000D_
<img data-src="holder.js/300x200?text=1">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=2">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=3">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=4">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=5">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=6">_x000D_
</div>_x000D_
<div class="item">_x000D_
<img data-src="holder.js/300x200?text=7">_x000D_
</div> _x000D_
</div>_x000D_
_x000D_
<!-- Controls -->_x000D_
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">_x000D_
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>_x000D_
<span class="sr-only">Previous</span>_x000D_
</a>_x000D_
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">_x000D_
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>_x000D_
<span class="sr-only">Next</span>_x000D_
</a>_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/holder/2.9.1/holder.min.js"></script>_x000D_
_x000D_
Shortest version to prettify existing JSON: (edit: using JSON.net)
JToken.Parse("mystring").ToString()
Input:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Output:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
To pretty-print an object:
JToken.FromObject(myObject).ToString()
Updating my answer with Xcode 9 and Swift
Archive
xcodebuild -workspace <ProjectName>/<ProjectName>.xcworkspace \
-scheme <schemeName> clean archive -configuration release \
-sdk iphoneos -archivePath <ProjectName>.xcarchive
IPA Export (please note the export option plist)
xcodebuild -exportArchive -archivePath <ProjectName>.xcarchive \
-exportOptionsPlist <ProjectName>/exportOptions.plist \
-exportPath <ProjectName>.ipa
For those who don't know about exportOptions.plist, https://blog.bitrise.io/new-export-options-plist-in-xcode-9
Those who were using this for building project in CI/CD tools like teamcity/jenkins, please make sure you are using the right xcode installed in the build agent for for both archive and export.
You can use either of below 2 options for this.
/Applications/Xcode 9.3.1.app/Contents/Developer/usr/bin/xcodebuild
xcode-select -switch /Applications/Xcode 9.3.1.app
Below is my old answer
Here is command line script for creating archive and IPA example. I have an iPhone xcode project , which is located in Desktop/MyiOSApp folder.
Execute following commands one by one:
cd /Users/username/Desktop/MyiOSApp/
xcodebuild -scheme MyiOSApp archive \
-archivePath /Users/username/Desktop/MyiOSApp.xcarchive
xcodebuild -exportArchive -exportFormat ipa \
-archivePath "/Users/username/Desktop/MyiOSApp.xcarchive" \
-exportPath "/Users/username/Desktop/MyiOSApp.ipa" \
-exportProvisioningProfile "MyCompany Distribution Profile"
This is tested with Xcode 5 and working fine for me.
Well if you have given
@ManyToOne ()
@JoinColumn (name = "countryId")
private Country country;
then object of that class i mean Country need to be save first.
because it will only allow User to get saved into the database if there is key available for the Country of that user for the same. means it will allow user to be saved if and only if that country is exist into the Country table.
So for that you need to save that Country first into the table.
None of the solutions above worked for me.
If you use IntelliJ, what resolved it for me was simply refreshing all Gradle projects:
I had the same problem, even after trying "mvn eclipse:eclipse -Dwtpversion=2.0" and "mvn clean install". But after I clean my server it just worked. So maybe after you are sure you have all the dependency needed try to clean the server.
I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
MAKE sure you have thymleaf on page already
//Use this in java
@Controller
@RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
Try os.system("pause")
— I used it and it worked for me.
Make sure to include import os
at the top of your script.
|=
reads the same way as +=
.
notification.defaults |= Notification.DEFAULT_SOUND;
is the same as
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
where |
is the bit-wise OR operator.
All operators are referenced here.
A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.
If you look at those constants, you'll see that they're in powers of two :
public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary
So you can use bit-wise OR to add flags
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011
so
myFlags |= DEFAULT_LIGHTS;
simply means we add a flag.
And symmetrically, we test a flag is set using &
:
boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.
After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.
Good luck! David
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
Maybe your file contains CRLF terminator. Every lines followed by \r\n.
awk
recognizes the $2
actually $2\r
. The \r
means goto the start of the line.
{print $2\r$1}
will print $2
first, then return to the head, then print $1
. So the field 2 is overlaid by the field 1.
openssl rsa -in privkey.pem -out private.key
does the job.
I got the same error from IIS under windows 7. To fix this error i had to add full control permissions to IUSR account for sqlite database file. You don't need to change permissions if you use sqlite under webmatrix instead of IIS.
As rcs stated, cex
will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2
but if you do, there's a size
aesthetic attribute, that you can easily control (ggplot2
has user-friendly function arguments: instead of typing cex
(character expansion), in ggplot2
you can type e.g. size = 2
and you'll get 2mm point).
Here's the example:
### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)
### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)
I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
The following algorithm will deal with self-referential data structures, numbers, strings, dates, and of course plain nested javascript objects:
Objects are considered equivalent when
===
(String and Number are unwrapped first to ensure 42
is equivalent to Number(42)
)valueOf()
==
(catches numbers/strings/booleans)undefined
value they have the same properties all of which are considered recursively equivalent.Functions are not considered identical by function text. This test is insufficient because functions may have differing closures. Functions are only considered equal if ===
says so (but you could easily extend that equivalent relation should you choose to do so).
Infinite loops, potentially caused by circular datastructures, are avoided. When areEquivalent
attempts to disprove equality and recurses into an object's properties to do so, it keeps track of the objects for which this sub-comparison is needed. If equality can be disproved, then some reachable property path differs between the objects, and then there must be a shortest such reachable path, and that shortest reachable path cannot contain cycles present in both paths; i.e. it is OK to assume equality when recursively comparing objects. The assumption is stored in a property areEquivalent_Eq_91_2_34
, which is deleted after use, but if the object graph already contains such a property, behavior is undefined. The use of such a marker property is necessary because javascript doesn't support dictionaries using arbitrary objects as keys.
function unwrapStringOrNumber(obj) {
return (obj instanceof Number || obj instanceof String
? obj.valueOf()
: obj);
}
function areEquivalent(a, b) {
a = unwrapStringOrNumber(a);
b = unwrapStringOrNumber(b);
if (a === b) return true; //e.g. a and b both null
if (a === null || b === null || typeof (a) !== typeof (b)) return false;
if (a instanceof Date)
return b instanceof Date && a.valueOf() === b.valueOf();
if (typeof (a) !== "object")
return a == b; //for boolean, number, string, xml
var newA = (a.areEquivalent_Eq_91_2_34 === undefined),
newB = (b.areEquivalent_Eq_91_2_34 === undefined);
try {
if (newA) a.areEquivalent_Eq_91_2_34 = [];
else if (a.areEquivalent_Eq_91_2_34.some(
function (other) { return other === b; })) return true;
if (newB) b.areEquivalent_Eq_91_2_34 = [];
else if (b.areEquivalent_Eq_91_2_34.some(
function (other) { return other === a; })) return true;
a.areEquivalent_Eq_91_2_34.push(b);
b.areEquivalent_Eq_91_2_34.push(a);
var tmp = {};
for (var prop in a)
if(prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in b)
if (prop != "areEquivalent_Eq_91_2_34")
tmp[prop] = null;
for (var prop in tmp)
if (!areEquivalent(a[prop], b[prop]))
return false;
return true;
} finally {
if (newA) delete a.areEquivalent_Eq_91_2_34;
if (newB) delete b.areEquivalent_Eq_91_2_34;
}
}
I needed to disable swiping on one specific page, and give it a nice rubber-band animation, here's how:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (position == MANDATORY_PAGE_LOCATION && positionOffset > 0.5) {
mViewPager.setCurrentItem(MANDATORY_PAGE_LOCATION, true);
}
}
Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.
# import time and OS modules to use to build file folder name
import time
import os
# Build string for directory to hold files
# Output Configuration
# drive_letter = Output device location (hard drive)
# folder_name = directory (folder) to receive and store PDF files
drive_letter = r'D:\\'
folder_name = r'downloaded-files'
folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
folder_to_save_files = drive_letter + folder_name + folder_time
# IF no such folder exists, create one automatically
if not os.path.exists(folder_to_save_files):
os.mkdir(folder_to_save_files)
In my case, the error was:
java.net.SocketException: Software caused connection abort: recv failed
It was received in eclipse while debugging a java application accessing a H2 database. The source of the error was that I had initially opened the database with SQuirreL to check manually for integrity. I did use the flag to enable multiple connections to the same DB (i.e. AUTO_SERVER=TRUE
), so there was no problem connecting to the DB from java.
The error appeared when, after a while --it is a long java process-- I decided to close SQuirreL to free resources. It appears as if SQuirreL were the one "owning" the DB server instance and that it was shut down with the SQuirreL connection.
Restarting the Java application did not yield the error again.
config
I had this error occur when building an Azure Function (with a queue trigger, should it make a difference)
The issue in this case was because the AzureFunctionsVersion
was set to v2 instead of v3. To update it via VS2019, unload the project then edit the csproj file. Within the PropertyGroup
node, add/edit the following:
<PropertyGroup>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
check if a user exists or not. If not insert
$exist = DB::table('User')->where(['username'=>$username,'password'=>$password])->get();
if(count($exist) >0) {
echo "User already exist";;
}
else {
$data=array('username'=>$username,'password'=>$password);
DB::table('User')->insert($data);
}
Laravel 5.4
In my case, I got a CAPTCHA error. If you get that, first logout/login to Bitbucket, Github, .... on the website and enter the required captcha.
After that, try again from intellij and it should prompt for another password.
Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).
Hope this helps:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");
pictureBox1.ContextMenu = cm;
They both represent floating point numbers. A FLOAT
is for single-precision, while a DOUBLE
is for double-precision numbers.
MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
There is a big difference from floating point numbers and decimal (numeric) numbers, which you can use with the DECIMAL
data type. This is used to store exact numeric data values, unlike floating point numbers, where it is important to preserve exact precision, for example with monetary data.
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
Inspired by Nathanael Smith's answer and Eric Freese's comment, it could be as simple as:
var exec = require('child_process').exec;
exec('coffee -cw my_file.coffee').stdout.pipe(process.stdout);
As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
'Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.
regex example:
boolean = (var.to_s =~ /^true$/i) == 0
ternary example:
boolean = var.to_s.eql?('true') ? true : false
The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:
boolean = (var.to_s =~ /^[Tt].*$/i) == 0
The other option, which could turn out to be a lot of work if you have a lot of commits, is an interactive rebase (assuming your git version is >=1.7.12):git rebase --root -i
When presented with a list of commits in your editor:
Save and close. Git will start rebasing.
At the end you would have a new root commit that is a combination of all the ones that came after it.
The advantage is that you don't have to delete your repository and if you have second thoughts you always have a fallback.
If you really do want to nuke your history, reset master to this commit and delete all other branches.
Not clear where My_ConnectionString
is coming from in your example, but try this
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
like this
Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
I had this problem too and couldn't solve it without using VBA.
In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.
i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."
Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.
Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
'clean
.FormatConditions.Delete
'green rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""GREEN"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -11489280
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
'amber rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""AMBER"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.ThemeColor = xlThemeColorAccent6
.TintAndShade = -0.249946592608417
End With
.FormatConditions(1).StopIfTrue = False
'red rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""RED"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -16776961
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
End With
Next Cell
End Sub
Emulation is a multi-faceted area. Here are the basic ideas and functional components. I'm going to break it into pieces and then fill in the details via edits. Many of the things I'm going to describe will require knowledge of the inner workings of processors -- assembly knowledge is necessary. If I'm a bit too vague on certain things, please ask questions so I can continue to improve this answer.
Emulation works by handling the behavior of the processor and the individual components. You build each individual piece of the system and then connect the pieces much like wires do in hardware.
There are three ways of handling processor emulation:
With all of these paths, you have the same overall goal: execute a piece of code to modify processor state and interact with 'hardware'. Processor state is a conglomeration of the processor registers, interrupt handlers, etc for a given processor target. For the 6502, you'd have a number of 8-bit integers representing registers: A
, X
, Y
, P
, and S
; you'd also have a 16-bit PC
register.
With interpretation, you start at the IP
(instruction pointer -- also called PC
, program counter) and read the instruction from memory. Your code parses this instruction and uses this information to alter processor state as specified by your processor. The core problem with interpretation is that it's very slow; each time you handle a given instruction, you have to decode it and perform the requisite operation.
With dynamic recompilation, you iterate over the code much like interpretation, but instead of just executing opcodes, you build up a list of operations. Once you reach a branch instruction, you compile this list of operations to machine code for your host platform, then you cache this compiled code and execute it. Then when you hit a given instruction group again, you only have to execute the code from the cache. (BTW, most people don't actually make a list of instructions but compile them to machine code on the fly -- this makes it more difficult to optimize, but that's out of the scope of this answer, unless enough people are interested)
With static recompilation, you do the same as in dynamic recompilation, but you follow branches. You end up building a chunk of code that represents all of the code in the program, which can then be executed with no further interference. This would be a great mechanism if it weren't for the following problems:
These combine to make static recompilation completely infeasible in 99% of cases. For more information, Michael Steil has done some great research into static recompilation -- the best I've seen.
The other side to processor emulation is the way in which you interact with hardware. This really has two sides:
Certain platforms -- especially older consoles like the NES, SNES, etc -- require your emulator to have strict timing to be completely compatible. With the NES, you have the PPU (pixel processing unit) which requires that the CPU put pixels into its memory at precise moments. If you use interpretation, you can easily count cycles and emulate proper timing; with dynamic/static recompilation, things are a /lot/ more complex.
Interrupts are the primary mechanism that the CPU communicates with hardware. Generally, your hardware components will tell the CPU what interrupts it cares about. This is pretty straightforward -- when your code throws a given interrupt, you look at the interrupt handler table and call the proper callback.
There are two sides to emulating a given hardware device:
Take the case of a hard-drive. The functionality is emulated by creating the backing storage, read/write/format routines, etc. This part is generally very straightforward.
The actual interface of the device is a bit more complex. This is generally some combination of memory mapped registers (e.g. parts of memory that the device watches for changes to do signaling) and interrupts. For a hard-drive, you may have a memory mapped area where you place read commands, writes, etc, then read this data back.
I'd go into more detail, but there are a million ways you can go with it. If you have any specific questions here, feel free to ask and I'll add the info.
I think I've given a pretty good intro here, but there are a ton of additional areas. I'm more than happy to help with any questions; I've been very vague in most of this simply due to the immense complexity.
It's been well over a year since this answer was submitted and with all the attention it's been getting, I figured it's time to update some things.
Perhaps the most exciting thing in emulation right now is libcpu, started by the aforementioned Michael Steil. It's a library intended to support a large number of CPU cores, which use LLVM for recompilation (static and dynamic!). It's got huge potential, and I think it'll do great things for emulation.
emu-docs has also been brought to my attention, which houses a great repository of system documentation, which is very useful for emulation purposes. I haven't spent much time there, but it looks like they have a lot of great resources.
I'm glad this post has been helpful, and I'm hoping I can get off my arse and finish up my book on the subject by the end of the year/early next year.
Best way to convince... find a bug, write a unit test for it, fix the bug.
That particular bug is unlikely to ever appear again, and you can prove it with your test.
If you do this enough, others will catch on quickly.
you call function on page load time but not call on button event, you will need to call function onclick
event, you may add event inline element style or event bining
function Choice(elem) {_x000D_
var box = document.getElementById("box");_x000D_
if (elem.id == "no") {_x000D_
box.style.backgroundColor = "red";_x000D_
} else if (elem.id == "yes") {_x000D_
box.style.backgroundColor = "green";_x000D_
} else {_x000D_
box.style.backgroundColor = "purple";_x000D_
};_x000D_
};
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
or event binding,
window.onload = function() {_x000D_
var box = document.getElementById("box");_x000D_
document.getElementById("yes").onclick = function() {_x000D_
box.style.backgroundColor = "red";_x000D_
}_x000D_
document.getElementById("no").onclick = function() {_x000D_
box.style.backgroundColor = "green";_x000D_
}_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateClient {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.
With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));
OR
String[] membersArray = request.getParameterValues('members');
ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));
You may use this in shell:
wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/
The Parameters are:
-r //recursive Download
and
--no-parent // Don´t download something from the parent directory
If you don't want to download the entire content, you may use:
-l1 just download the directory (tzivi in your case)
-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')
And so on. If you insert no -l
option, wget
will use -l 5
automatically.
If you insert a -l 0
you´ll download the whole Internet, because wget
will follow every link it finds.
-
WHERE SUBSTR('Hello world', -4)
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
There is also a 'hack' that can be used although it might be removed from matlab at some point: Function eval actually accepts two arguments of which the second is run if an error occurred with the first.
Thus we can use
function output = fun(input)
eval('input;', 'input = 1;');
...
end
to use value 1 as default for the argument
using static System.Console;
namespace IntToBits
{
class Program
{
static void Main()
{
while (true)
{
string s = Console.ReadLine();
Clear();
uint i;
bool b = UInt32.TryParse(s, out i);
if (b) IntPrinter(i);
}
}
static void IntPrinter(uint i)
{
int[] iarr = new int [32];
Write("[");
for (int j = 0; j < 32; j++)
{
uint tmp = i & (uint)Math.Pow(2, j);
iarr[j] = (int)(tmp >> j);
}
for (int j = 32; j > 0; j--)
{
if(j%8==0 && j != 32)Write("|");
if(j%4==0 && j%8 !=0) Write("'");
Write(iarr[j-1]);
}
WriteLine("]");
}
}
}```
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.
private Path getFolderPath() throws URISyntaxException, IOException {
URI uri = getClass().getClassLoader().getResource("folder").toURI();
if ("jar".equals(uri.getScheme())) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
return fileSystem.getPath("path/to/folder/inside/jar");
} else {
return Paths.get(uri);
}
}
Requires java 7+.
You can think of a mysql database
as a schema/user in Oracle
. If you have the privileges, you can query the DBA_USERS
view to see the list of schema.
Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.
Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none
version: '3.7'
services:
app:
image: ramansharma/einwohnertomcat:v0.0.1
deploy:
replicas: 1
ports:
- '8080:8080'
volumes:
- type: bind
source: /proc
target: /hostfs/proc
read_only: true
- type: bind
source: /sys/fs/cgroup
target: /hostfs/sys/fs/cgroup
read_only: true
- type: bind
source: /
target: /hostfs
read_only: true
networks:
hostnet: {}
networks:
- einwohner_net
- elk_elk_net
networks:
einwohner_net:
elk_elk_net:
external: true
hostnet:
external: true
name: host
Just add this to the beginning of your JavaScript code:
google.maps.LatLng.prototype.distanceFrom = function(latlng) {
var lat = [this.lat(), latlng.lat()]
var lng = [this.lng(), latlng.lng()]
var R = 6378137;
var dLat = (lat[1]-lat[0]) * Math.PI / 180;
var dLng = (lng[1]-lng[0]) * Math.PI / 180;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
Math.sin(dLng/2) * Math.sin(dLng/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return Math.round(d);
}
and then use the function like this:
var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);
var dist = loc2.distanceFrom(loc1);
alert(dist/1000);
You can't but what if you set expire time to now + 100 years ?
It's !=
without type coercion. See the MDN documentation for comparison operators.
Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with ==
and !=
. (null == undefined
, false == "0"
, etc.)
Short answer: always use ===
and !==
unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)
In the right side of Android Studio go to Gradle -> Tasks -> android -> signingReport
and run it.
Copy the SHA-1 key and transform it into base64 using this, and then add the converted base64 hash to your app in the Facebook Developer Console.
If you want to use a release hash run this in the command line:keytool -exportcert -alias YOUR_KEYSTORE_ALIAS -keystore YOUR_KEYSTORE | openssl sha1 -binary | openssl base64
Where YOUR_KEYSTORE
is the path to the .keystore
or .jks
that you used as signinConfig
for your release variant and YOUR_KEYSTORE_ALIAS
is the alias which you gave when you created the keystore. If you do not remember the alias you can run keytool -v -list -keystore YOUR_KEYSTORE
and see all the info about the keystore
The entity
produces a non-breaking space, which is used when you don't want an automatic line break at that position. The regular space has the character code 32, while the non-breaking space has the character code 160.
For example when you display numbers with space as thousands separator: 1 234 567, then you use non-breaking spaces so that the number can't be split on separate lines. If you display currency and there is a space between the amount and the currency: 42 SEK, then you use a non-breaking space so that you don't get the amount on one line and the currency on the next.
foreach (DataColumn col in rightsTable.Columns)
{
foreach (DataRow row in rightsTable.Rows)
{
Console.WriteLine(row[col.ColumnName].ToString());
}
}
download attribute do it
<a class="btn btn-success btn-sm" href="/file_path/file.type" download>
<span>download </span> <i class="fa fa-download"></i>
</a>
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf
Always try to do an associative fetch, that way you can easy get what you want in multiple case result
Here's an example
$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";
Yes you can and your DBA will hate you and will find you to nail your shoes to the floor because that will cause lots of I/O and bring the database performance really down as the cache purges.
select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;
for a start.
I would start with the running queries, using the v$session
and the v$sqlarea
. This changes based on oracle version. This will narrow down the space and not hit everything.
Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()
).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.
If your deployment descriptor tab is disabled, then click on update libraries it will also do your work. It will create. Xml file in Web content
Press Ctrl + T on the method name (rather than F3). This gives the type hierarchy as a pop-up so is slightly faster than using F4 and the type hierarchy view.
Also, when done on a method, subtypes that don't implement/override the method will be greyed out, and when you double click on a class in the list it will take you straight to the method in that class.
Use this code is whork :
if (!preg_match('#^http(s)?://#', $url)) {
$url = 'http://' . $url;
}
$urlParts = parse_url($url);
$url = preg_replace('/^www\./', '', $urlParts['host']);
try
{
}
catch (Exception err)
{
if (err is Web2PDFException)
DoWhatever();
}
but there is probably a better way of doing whatever it is you want.
Here is the code which I am using in my project and it is working fine:
public function getClient(){
$client = new Google_Client();
$client->setApplicationName(APPNAME); // app name
$client->setClientId(CLIENTID); // client id
$client->setClientSecret(CLIENTSECRET); // client secret
$client->setRedirectUri(REDIRECT_URI); // redirect uri
$client->setApprovalPrompt('auto');
$client->setAccessType('offline'); // generates refresh token
$token = $_COOKIE['ACCESSTOKEN']; // fetch from cookie
// if token is present in cookie
if($token){
// use the same token
$client->setAccessToken($token);
}
// this line gets the new token if the cookie token was not present
// otherwise, the same cookie token
$token = $client->getAccessToken();
if($client->isAccessTokenExpired()){ // if token expired
$refreshToken = json_decode($token)->refresh_token;
// refresh the token
$client->refreshToken($refreshToken);
}
return $client;
}
If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"
You may try one of these methods:
Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.
Using a double quote password: "your password" <-- this one also solved my problem.
From RFC 5321, section 2.3.11:
The standard mailbox naming convention is defined to be "local-part@domain"; contemporary usage permits a much broader set of applications than simple "user names". Consequently, and due to a long history of problems when intermediate hosts have attempted to optimize transport by modifying them, the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.
So yes, the part before the "@" could be case-sensitive, since it is entirely under the control of the host system. In practice though, no widely used mail systems distinguish different addresses based on case.
The part after the @ sign however is the domain and according to RFC 1035, section 3.1,
"Name servers and resolvers must compare [domains] in a case-insensitive manner"
In short, you are safe to treat email addresses as case-insensitive.
It affects the whole child divs when you use the opacity feature with positions other than absolute. So another way to achieve it not to put divs inside each other and then use the position absolute for the divs. Dont use any background color for the upper div.
It's impossible, and for a good reason (for one, think about all those catch(Exception){} around).
If you want to continue execution after stack overflow, run dangerous code in a different AppDomain. CLR policies can be set to terminate current AppDomain on overflow without affecting original domain.
There is no such particular way in which you can initialize the array after declaring it once.
There are three options only:
1.) initialize them in different lines :
int array[SIZE];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...
But thats not what you want i guess.
2.) Initialize them using a for or while loop:
for (i = 0; i < MAX ; i++) {
array[i] = i;
}
This is the BEST WAY by the way to achieve your goal.
3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.
And can I ask you why specifically you want to do so???
I always do it like this:
$("#id").css("width", "50%");
For your case Elasticdump is the perfect answer.
First, you need to download the mapping and then the index
# Install the elasticdump
npm install elasticdump -g
# Dump the mapping
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_mapping.json --type=mapping
# Dump the data
elasticdump --input=http://<your_es_server_ip>:9200/index --output=es_index.json --type=data
If you want to dump the data on any server I advise you to install esdump through docker. You can get more info from this website Blog Link
A comment by madeddie looks most elegant to me:
CID=$(basename $(cat /proc/1/cpuset))
This is caused by the regional settings of your computer.
When you paste data into excel it is only a bunch of strings (not dates).
Excel has some logic in it to recognize your current data formats as well as a few similar date formats or obvious date formats where it can assume it is a date. When it is able to match your pasted in data to a valid date then it will format it as a date in the cell it is in.
Your specific example is due to your list of dates is formatted as "m/d/yy" which is US format. it pastes correctly in my excel because I have my regional setting set to "US English" (even though I'm Canadian :) )
If you system is set to Canadian English/French format then it will expect "d/m/yy" format and not recognize any date where the month is > 13.
The best way to import data, that contains dates, into excel is to copy it in this format.
2011-04-22
2011-12-19
2011-11-04
2011-12-08
2011-09-27
2011-09-27
2011-04-01
Which is "yyyy-MM-dd", this format is recognized the same way on every computer I have ever seen (is often refered to as ODBC format or Standard format) where the units are always from greatest to least weight ("yyyy-MM-dd HH:mm:ss.fff") another side effect is it will sort correctly as a string.
To avoid swaping your regional settings back and forth you may consider writting a macro in excel to paste the data in. a simple popup format and some basic logic to reformat the dates would not be too difficult.
//It is working
#include<iostream>
using namespace std;
void main()
{
int a[5];
int temp=0;
cout<<"Enter Values"<<endl;
for(int i=0;i<5;i++)
{
cin>>a[i];
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Asending Series"<<endl;
for(int i=0;i<5;i++)
{
cout<<endl;
cout<<a[i]<<endl;
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Desnding Series"<<endl;
for(int i=0;i<5;i++)
{
cout<<endl;
cout<<a[i]<<endl;
}
}
ConfigurationManager.AppSettings returns the settings defined for the application, not for the specific DLL, you can access them but it's the application settings that will be returned.
If you're using you dll from another application then the ConnectionString shall be in the app.settings of the application.
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
this works in all browsers (IE is an oddball)
setTimeout( (function(x) {
return function() {
postinsql(x);
};
})(topicId) , 4000);
round(..)
function returning a floatThat float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)
See the discussion here for details.
You can use the curses.h
library in linux as mentioned in the other answer.
You can install it in Ubuntu by:
sudo apt-get update
sudo apt-get install ncurses-dev
I took the installation part from here.
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"
I was able to fix the problems on Windows machine by changing core.autocrlf from false to core.autocrlf=input
git config core.autocrlf input
as it's suggested in https://stackoverflow.com/a/1112313/52277
If you want to allow a comma delimiter which will pass the following test cases:
0,00 => true
0.00 => true
01,00 => true
01.00 => true
0.000 => false
0-01 => false
then use this:
^\d+(\.|\,)\d{2}$
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
Yes, it is possible to merge .NET executables with libraries. There are multiple tools available to get the job done:
In addition this can be combined with the Mono Linker, which does remove unused code and therefor makes the resulting assembly smaller.
Another possibility is to use .NETZ, which does not only allow compressing of an assembly, but also can pack the dlls straight into the exe. The difference to the above mentioned solutions is that .NETZ does not merge them, they stay separate assemblies but are packed into one package.
.NETZ is a open source tool that compresses and packs the Microsoft .NET Framework executable (EXE, DLL) files in order to make them smaller.
Let's see how to get and print day,month,year in python from current time:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
result:
day_month_year: 2019-03-26
In my case it was just caused because there was not enough space on the disk for cvtres.exe
to write the files it had to.
The error was preceded by this line
CVTRES : fatal error CVT1106: cannot write to file
Use JavaScript's hasOwnProperty()
function:
if (json_object.hasOwnProperty('name')) {
//do struff
}
SUBSTRING(CONVERT(VARCHAR(34), SYSDATETIMEOFFSET()), 29, 5)
Returns (for example):
-06:0
Not 100% positive this will always work.
Using Ubuntu 12.04 it appears to work fine for me:
jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
python-psycopg2-doc
The following NEW packages will be installed
python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.
What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update
to make sure your repo. is up to date.
Although I agree completely with delnan's answer, it's not impossible:
loop = range(NUM_ITERATIONS+1)
while loop.pop():
do_stuff()
Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False
, you will get another iteration and an exception on the next pass: IndexError: pop from empty list
. Also, your list (loop
) will be empty after the loop.
Just for curiosity's sake. ;)
You missed the each=
argument to rep()
:
R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
so your example can be done with a simple
R> rep(1:8, each=20)
Well in my case, my project A had a dependency on another, say X(A was using some of the classes defined in X). So when I added X as a reference project in the build path of A , I got this error. However when I removed X as the referenced project and included X's jar as one of the libraries, the problem was solved.
1) Ensure that the enable32BitAppOnWin64 setting for the "SharePoint Central Administration" app pool is set to False, and the same for the "SharePoint Web Services Root" app pool
2) Edit applicationHost.config:
bitness64 being the magic word here
I was facing same issue: Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object
Follow below steps to resolve issue :
Step 1. Goto C:\Program Files\ and search for Java folder.
Step 2. Delete C:\Program Files\Java folder.
Step 3. Download new Jdk for your version 32 bit/64 bit from http://www.oracle.com/technetwork/java/javase/downloads/index.html
Step 4. Install JDK
Step 5: Now Set JAVA_HOME to "C:\Program Files\Java\jdk1.8.0_91"
Step 6: Open command prompt and enter java -version.
It works.
You can try using:
select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual
Provided the windows are from the same security domain, and you have a reference to the other window, yes.
Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.
Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.
Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle
.
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Gradle 1.7+, Android gradle plugin 0.6.+ are required.
Note, that only try with resources require minSdkVersion
19. Other features works on previous platforms.
pd.DataFrame.loc
can take one or two indexers. For the rest of the post, I'll represent the first indexer as i
and the second indexer as j
.
If only one indexer is provided, it applies to the index of the dataframe and the missing indexer is assumed to represent all columns. So the following two examples are equivalent.
df.loc[i]
df.loc[i, :]
Where :
is used to represent all columns.
If both indexers are present, i
references index values and j
references column values.
Now we can focus on what types of values i
and j
can assume. Let's use the following dataframe df
as our example:
df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['X', 'Y'])
loc
has been written such that i
and j
can be
scalars that should be values in the respective index objects
df.loc['A', 'Y']
2
arrays whose elements are also members of the respective index object (notice that the order of the array I pass to loc
is respected
df.loc[['B', 'A'], 'X']
B 3
A 1
Name: X, dtype: int64
Notice the dimensionality of the return object when passing arrays. i
is an array as it was above, loc
returns an object in which an index with those values is returned. In this case, because j
was a scalar, loc
returned a pd.Series
object. We could've manipulated this to return a dataframe if we passed an array for i
and j
, and the array could've have just been a single value'd array.
df.loc[['B', 'A'], ['X']]
X
B 3
A 1
boolean arrays whose elements are True
or False
and whose length matches the length of the respective index. In this case, loc
simply grabs the rows (or columns) in which the boolean array is True
.
df.loc[[True, False], ['X']]
X
A 1
In addition to what indexers you can pass to loc
, it also enables you to make assignments. Now we can break down the line of code you provided.
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
iris_data['class'] == 'versicolor'
returns a boolean array.class
is a scalar that represents a value in the columns object.iris_data.loc[iris_data['class'] == 'versicolor', 'class']
returns a pd.Series
object consisting of the 'class'
column for all rows where 'class'
is 'versicolor'
When used with an assignment operator:
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
We assign 'Iris-versicolor'
for all elements in column 'class'
where 'class'
was 'versicolor'
when initializing dialog builder, pass second parameter as the theme. It will automatically show material design with API level 21.
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_DARK);
or,
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
WHERE p.[Type] = isnull(@SearchType, p.[Type])
You can't update tables from a function like you would a stored procedure, but you CAN update table variables.
So for example, you can't do this in your function:
create table MyTable
(
ID int,
column1 varchar(100)
)
update [MyTable]
set column1='My value'
but you can do:
declare @myTable table
(
ID int,
column1 varchar(100)
)
Update @myTable
set column1='My value'
Some overly complex answers here. The Debruin technique should only be used when the input is already a power of two, otherwise there's a better way. For a power of 2 input, Debruin is the absolute fastest, even faster than _BitScanReverse
on any processor I've tested. However, in the general case, _BitScanReverse
(or whatever the intrinsic is called in your compiler) is the fastest (on certain CPU's it can be microcoded though).
If the intrinsic function is not an option, here is an optimal software solution for processing general inputs.
u8 inline log2 (u32 val) {
u8 k = 0;
if (val > 0x0000FFFFu) { val >>= 16; k = 16; }
if (val > 0x000000FFu) { val >>= 8; k |= 8; }
if (val > 0x0000000Fu) { val >>= 4; k |= 4; }
if (val > 0x00000003u) { val >>= 2; k |= 2; }
k |= (val & 2) >> 1;
return k;
}
Note that this version does not require a Debruin lookup at the end, unlike most of the other answers. It computes the position in place.
Tables can be preferable though, if you call it repeatedly enough times, the risk of a cache miss becomes eclipsed by the speedup of a table.
u8 kTableLog2[256] = {
0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
};
u8 log2_table(u32 val) {
u8 k = 0;
if (val > 0x0000FFFFuL) { val >>= 16; k = 16; }
if (val > 0x000000FFuL) { val >>= 8; k |= 8; }
k |= kTableLog2[val]; // precompute the Log2 of the low byte
return k;
}
This should produce the highest throughput of any of the software answers given here, but if you only call it occasionally, prefer a table-free solution like my first snippet.
Please read this article: How To Implement a LinkedList Class From Scratch In Java
package com.crunchify.tutorials;
/**
* @author Crunchify.com
*/
public class CrunchifyLinkedListTest {
public static void main(String[] args) {
CrunchifyLinkedList lList = new CrunchifyLinkedList();
// add elements to LinkedList
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
/*
* Please note that primitive values can not be added into LinkedList
* directly. They must be converted to their corresponding wrapper
* class.
*/
System.out.println("lList - print linkedlist: " + lList);
System.out.println("lList.size() - print linkedlist size: " + lList.size());
System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
System.out.println("lList.remove(2) - remove 2nd element: " + lList.remove(2));
System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
System.out.println("lList.size() - print linkedlist size: " + lList.size());
System.out.println("lList - print linkedlist: " + lList);
}
}
class CrunchifyLinkedList {
// reference to the head node.
private Node head;
private int listCount;
// LinkedList constructor
public CrunchifyLinkedList() {
// this is an empty list, so the reference to the head node
// is set to a new node with no data
head = new Node(null);
listCount = 0;
}
public void add(Object data)
// appends the specified element to the end of this list.
{
Node crunchifyTemp = new Node(data);
Node crunchifyCurrent = head;
// starting at the head node, crawl to the end of the list
while (crunchifyCurrent.getNext() != null) {
crunchifyCurrent = crunchifyCurrent.getNext();
}
// the last node's "next" reference set to our new node
crunchifyCurrent.setNext(crunchifyTemp);
listCount++;// increment the number of elements variable
}
public void add(Object data, int index)
// inserts the specified element at the specified position in this list
{
Node crunchifyTemp = new Node(data);
Node crunchifyCurrent = head;
// crawl to the requested index or the last element in the list,
// whichever comes first
for (int i = 1; i < index && crunchifyCurrent.getNext() != null; i++) {
crunchifyCurrent = crunchifyCurrent.getNext();
}
// set the new node's next-node reference to this node's next-node
// reference
crunchifyTemp.setNext(crunchifyCurrent.getNext());
// now set this node's next-node reference to the new node
crunchifyCurrent.setNext(crunchifyTemp);
listCount++;// increment the number of elements variable
}
public Object get(int index)
// returns the element at the specified position in this list.
{
// index must be 1 or higher
if (index <= 0)
return null;
Node crunchifyCurrent = head.getNext();
for (int i = 1; i < index; i++) {
if (crunchifyCurrent.getNext() == null)
return null;
crunchifyCurrent = crunchifyCurrent.getNext();
}
return crunchifyCurrent.getData();
}
public boolean remove(int index)
// removes the element at the specified position in this list.
{
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node crunchifyCurrent = head;
for (int i = 1; i < index; i++) {
if (crunchifyCurrent.getNext() == null)
return false;
crunchifyCurrent = crunchifyCurrent.getNext();
}
crunchifyCurrent.setNext(crunchifyCurrent.getNext().getNext());
listCount--; // decrement the number of elements variable
return true;
}
public int size()
// returns the number of elements in this list.
{
return listCount;
}
public String toString() {
Node crunchifyCurrent = head.getNext();
String output = "";
while (crunchifyCurrent != null) {
output += "[" + crunchifyCurrent.getData().toString() + "]";
crunchifyCurrent = crunchifyCurrent.getNext();
}
return output;
}
private class Node {
// reference to the next node in the chain,
// or null if there isn't one.
Node next;
// data carried by this node.
// could be of any type you need.
Object data;
// Node constructor
public Node(Object dataValue) {
next = null;
data = dataValue;
}
// another Node constructor if we want to
// specify the node to point to.
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
// these methods should be self-explanatory
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Output
lList - print linkedlist: [1][2][3][4][5]
lList.size() - print linkedlist size: 5
lList.get(3) - get 3rd element: 3
lList.remove(2) - remove 2nd element: true
lList.get(3) - get 3rd element: 4
lList.size() - print linkedlist size: 4
lList - print linkedlist: [1][3][4][5]
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
strtok
is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE
value for $allTheRest
which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
O(1) does not necessarily mean "quickly". It means that the time it takes is constant, and not based on the size of the input to the function. Constant could be fast or slow. O(n) means that the time the function takes will change in direct proportion to the size of the input to the function, denoted by n. Again, it could be fast or slow, but it will get slower as the size of n increases.
Since Spring 3.1 the id
attribute is an xsd:string
and permits the same range of characters as the name
attribute.
The only difference between an id
and a name
is that a name
can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id
must be a single value.
From the Spring 3.2 documentation:
In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.
well, there are many ways to do this in javascript just like other says. I don't think there's a way to do it in react. here's what I would do:
in a js file:
module.exports = {
small_square: 's',
large_square: 'q'
}
in your react file:
'use strict';
var Constant = require('constants');
....
var something = Constant.small_square;
something for you to consider, hope this helps
In conf/hdfs-site.xml, you should have a property like
<property>
<name>dfs.name.dir</name>
<value>/home/user/hadoop/name/data</value>
</property>
The property "dfs.name.dir" allows you to control where Hadoop writes NameNode metadata. And giving it another dir rather than /tmp makes sure the NameNode data isn't being deleted when you reboot.
If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.
If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.
public void fixedAdd(List<Integer> list, int val, int size) {
list.add(val);
if(list.size() > size) list.remove(0);
}
LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.
The solution I post will consider a month with 30 days
select CONCAT (CONCAT (num_months,' MONTHS '), CONCAT ((days-(num_months)*30),' DAYS '))
from (
SELECT floor(Months_between(To_date('20120325', 'YYYYMMDD'),
To_date('20120101', 'YYYYMMDD')))
num_months,
( To_date('20120325', 'YYYYMMDD') - To_date('20120101', 'YYYYMMDD') )
days
FROM dual);
To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
It can be used like this, with validation functions:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
TESTED
import Vue from 'vue'
Vue.filter('formatYear', (value) => {
if (!value) return ''
return moment(value).format('YYYY')
})
My problem was my Target profile didn't have the proper code signing option selected:
Target Menu -> Code Signing -> Code Signing Identity
Choose "iPhone developer" then select the provisional profile you created.
Comparing to writing your styles in a CSS file, React's style attribute has the following advantages:
However, the React's style attribute comes with a few drawbacks - you can't
Using CSS in JS, you can get all the advantages of a style tag, without those drawbacks. As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium. Those libraries are to CSS kind of what React is to HTML. They allow you to write your CSS and control your CSS in your JS code.
let's compare how our code will look for styling a simple element. We'll style a "hello world" div so it shows big on desktop and smaller on mobile.
Using the style attribute
return (
<div style={{fontSize:24}} className="hello-world">
Hello world
</div>
)
Since media query is not possible in a style tag, we'll have to add a className to the element and add a css rule.
@media screen and (max-width: 700px){
.hello-world {
font-size: 16px;
}
}
Using Emotion's 10 CSS tag
return (
<div
css={{
fontSize: 24,
[CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
fontSize: 16
}
}
>
Hello world
</div>
)
Emotion also supports template strings as well as styled-components. So if you prefer you can write:
return (
<Box>
Hello world
</Box>
)
const Box = styled.div`
font-size: 24px;
${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
font-size: 16px;
}
`
Behind the hoods "CSS in JS" uses CSS classes. Emotion specifically built with performance in mind and uses caching. Compared to React style attributes CSS in JS will provide better performance.
###Best Practices
Here are a few best practices I recommend:
Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?
should I avoid inline styles completely?
// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
BUTTON: css`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
}
// SomeButton.js
const SomeButton = (props) => {
...
return (
<button
css={COMMON_STYLES.BUTTON}
...
>
Click Me
</button>
)
}
// Option 2 - Write your common styles in a dedicated component
const Button = styled.button`
background-color: blue;
color: white;
:hover {
background-color: dark-blue;
}
`
const SomeButton = (props) => {
...
return (
<Button ...>
Click me
</Button>
)
}
React coding pattern is of encapsulated components - HTML and JS that controls a component is written in one file. That is where your css/style code to style that component belongs.
When necessary, add a styling prop to your component. This way you can reuse code and style written in a child component, and customize it to your specific needs by the parent component.
const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])
const SmallButton = (props)=>(
<Button
...
stl={css`font-size: 12px`}
>
Click me if you can see me
</Button>
)
const BigButton = (props) => (
<Button
...
stl={css`font-size: 30px;`}
>
Click me
</Button>
)
You can do it like this:
using System.IO;
static void Main(string[] args)
{
using(var reader = new StreamReader(@"C:\test.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
}
}
}
If your column will only have one value something like pd.series.tolist()
will produce an error. To guarantee that it will work for all cases, use the code below:
(
df
.filter(['column_name'])
.values
.reshape(1, -1)
.ravel()
.tolist()
)
Just do
git pull origin [branch]
and then you should be able to push.
If you have commits on your own and didn't push it the branch yet, try
git pull --rebase origin [branch]
and then you should be able to push.
Read more about handling branches with Git.
I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.
In vanilla Oracle, the feature called LOCATOR (a crippled version of Spatial) requires that the coordinate data be stored using the datatype of NUMBER (no precision). When you try to create Function Based Indexes to support spatial queries it'll gag otherwise.
You don't need getInputDOMNode
?? in this case...
Just simply get the ref
and focus()
it when component gets mounted -- componentDidMount...
import React from 'react';
import { render } from 'react-dom';
class myApp extends React.Component {
componentDidMount() {
this.nameInput.focus();
}
render() {
return(
<div>
<input ref={input => { this.nameInput = input; }} />
</div>
);
}
}
ReactDOM.render(<myApp />, document.getElementById('root'));
5 step to do what you want if you made the pull request from a forked repository:
And everything is done, good luck!
Think of it as just another safety level. You can design your table without foreign key relationships - perfectly valid - and ensure existence of associated entities entirely on the business layer. However, foreign keys are considered good design practice because they add another constraint level in case something messes up on the business layer. Same goes for field size limitation and not using varchar MAX.
select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy
The more correct way to do it:
DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)
If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >=
and <
you can do it within one single statement, but it's just that the value is used twice.
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
By using just jQuery, you cannot avoid a server call.
However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.
To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.
Answer 1:
To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's encode
method. If you don't supply an encoding parameter 'ascii'
is used, which will always be good enough for numeric digits.
s = str(n).encode()
In Python 2 str(n)
already produces bytes; the encode
will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.
Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a different question, I'll answer that question too. If you want to convert 10
to b'10'
use the answer above, but if you want to convert 10
to b'\x0a\x00\x00\x00'
then keep reading.
The struct
module was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with struct.pack
. There's a format parameter fmt
that determines which conversion it should perform. For a 4-byte integer, that would be i
for signed numbers or I
for unsigned numbers. For more possibilities see the format character table, and see the byte order, size, and alignment table for options when the output is more than a single byte.
import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
You should look at the members of the thrown exception, particularly .Message
and .InnerException
.
I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.
Try removing the uses-sdk
part form AndroidManifest.xml
file. it worked for me!
Don't use the Android Virtual Device with too low configuration. Let it be medium.
a = "MandY"
alow = a.lower()
if "mandy" in alow:
print "true"
work around
MySQL prior to version 8.0 doesn't support the WITH clause (CTE in SQL Server parlance; Subquery Factoring in Oracle), so you are left with using:
The request for the feature dates back to 2006.
As mentioned, you provided a poor example - there's no need to perform a subselect if you aren't altering the output of the columns in any way:
SELECT *
FROM ARTICLE t
JOIN USERINFO ui ON ui.user_userid = t.article_ownerid
JOIN CATEGORY c ON c.catid = t.article_categoryid
WHERE t.published_ind = 0
ORDER BY t.article_date DESC
LIMIT 1, 3
Here's a better example:
SELECT t.name,
t.num
FROM TABLE t
JOIN (SELECT c.id
COUNT(*) 'num'
FROM TABLE c
WHERE c.column = 'a'
GROUP BY c.id) ta ON ta.id = t.id
He is trying find and display the duplicate rows in a table.
SELECT *, COUNT(*) AS NoOfOccurrences
FROM TableName GROUP BY *
HAVING COUNT(*) > 1
Do we have a simple way to accomplish this?
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false
is deliberate (neither != false
nor === true
will return the desired result); strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
Edit:
Now with PHP 8 you can do this:
if (str_contains('How are you', 'are')) {
echo 'true';
}
\n
is a line feed (LF) character, character code 10. \r
is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF). On Unix systems and their derivatives, only LF is used. (Macs prior to Mac OS X used CR, but Mac OS X is a *nix derivative and so uses LF.)
In the old days, LF literally did just a line feed on printers (moving down one line without moving where you are horizonally on the page), and CR similarly moved back to the beginning of the line without moving the paper up, hence some systems (like Windows) sending CR (return to the left-hand side) and LF (and feed the paper up).
Because of all this confusion, some output targets will accept multiple line break sequences, so you could see the same effect from either character depending on what you're outputting to.
You are looking for something like the following
ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b
Also you can use guppy module.
>>> from guppy import hpy; hp=hpy()
>>> hp.heap()
Partition of a set of 25853 objects. Total size = 3320992 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 11731 45 929072 28 929072 28 str
1 5832 23 469760 14 1398832 42 tuple
2 324 1 277728 8 1676560 50 dict (no owner)
3 70 0 216976 7 1893536 57 dict of module
4 199 1 210856 6 2104392 63 dict of type
5 1627 6 208256 6 2312648 70 types.CodeType
6 1592 6 191040 6 2503688 75 function
7 199 1 177008 5 2680696 81 type
8 124 0 135328 4 2816024 85 dict of class
9 1045 4 83600 3 2899624 87 __builtin__.wrapper_descriptor
<90 more rows. Type e.g. '_.more' to view.>
And:
>>> hp.iso(1, [1], "1", (1,), {1:1}, None)
Partition of a set of 6 objects. Total size = 560 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 17 280 50 280 50 dict (no owner)
1 1 17 136 24 416 74 list
2 1 17 64 11 480 86 tuple
3 1 17 40 7 520 93 str
4 1 17 24 4 544 97 int
5 1 17 16 3 560 100 types.NoneType
On Microsoft SQL Server Management Studio 2019:
On Restore Database window:
Choose Device
Choose Add and pick target file
OK to confirm
OK to confirm restore
If you have used chmod command already then check the difference of file, It shows previous file mode and current file mode such as:
new mode : 755
old mode : 644
set old mode of all files using below command
sudo chmod 644 .
now set core.fileMode to false in config file either using command or manually.
git config core.fileMode false
then apply chmod command to change the permissions of all files such as
sudo chmod 755 .
and again set core.fileMode to true.
git config core.fileMode true
For best practises don't Keep core.fileMode false always.
I just would like to add how it may happen that a reference breaks.
On my system (Windows 7 64-bit), when a BSOD happens, some of the stored reference files (most likely currently opened/being written into when BSOD happened) are overwritten with NULL
characters (ASCII 0).
As others mentioned, to fix it, it's enough to just delete those invalid reference files and re-fetch or re-pull the repository.
Error: cannot lock ref 'refs/remotes/origin/some/branch': unable to resolve reference 'refs/remotes/origin/some/branch': reference broken
Solution: delete the file %repo_root%/.git/refs/remotes/origin/some/branch
I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.
.feature_wrapper span {
float: left;
clear: left;
display:inline
}
EDIT: now browsers have better support you can make use of the do inline-block.
.feature_wrapper span {
display:inline-block;
*display:inline; *zoom:1;
}
Depending on the text-align this will appear as through its inline while also acting like a block element.
Functional decision for @pegah answer:
from itertools import groupby
mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])
result = { k : [*map(lambda v: v[1], values)]
for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
}
print(result)
# {'a': [1, 2], 'b': [3, 4]}
You can use npm uninstall <package-name>
will remove it from your package.json file and from node_modules.
If you do ng help
command, you will see that there is no ng remove/delete
supported command. So, basically you cannot revert the ng add
behavior yet.
You have to add type="text/css"
you can also specify href="./style.css"
which the .
specifies the current directory
According to the UI dialog documentation, the dialog plugin generates something like this:
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
<a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
</div>
<div class="ui-dialog-content ui-widget-content" id="dialog_style1">
<p>One content</p>
</div>
</div>
That means what you can add to any class to exactly to first or second dialog using jQuery's closest() method. For example:
$('#dialog_style1').closest('.ui-dialog').addClass('dialog_style1');
$('#dialog_style2').closest('.ui-dialog').addClass('dialog_style2');
and then CSS it.
The javadocs for Scanner answer your question
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You might change the default whitespace pattern the Scanner is using by doing something like
Scanner s = new Scanner();
s.useDelimiter("\n");
It works in my react project:
import FileSaver from 'file-saver';
// ...
onTestSaveFile() {
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");
}
Just finished a 2 hour wild goose chase trying to solve this. None of the posted answers worked for me. Im on a Mac (Mojave Version 10.14.6, Xcode Version 11.3).
It turns out the ruby file headers were missing so i had to run open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
That didnt work for me at first because the version of CommandLineTools i had installed did not have the "Packages" folder. So i uninstalled and reinstalled like this:
rm -rf /Library/Developer/CommandLineTools
xcode-select --install
Then i ran the previous command again:
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
After install the error was fixed!
From the first answer,
"Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB."
You can now also define schema with mongoDB native driver using
##For new collection
`db.createCollection("recipes",
validator: { $jsonSchema: {
<<Validation Rules>>
}
}
)`
##For existing collection
`db.runCommand( {
collMod: "recipes",
validator: { $jsonSchema: {
<<Validation Rules>>
}
}
} )`
##full example
`db.createCollection("recipes", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "servings", "ingredients"],
additionalProperties: false,
properties: {
_id: {},
name: {
bsonType: "string",
description: "'name' is required and is a string"
},
servings: {
bsonType: ["int", "double"],
minimum: 0,
description:
"'servings' is required and must be an integer with a minimum of zero."
},
cooking_method: {
enum: [
"broil",
"grill",
"roast",
"bake",
"saute",
"pan-fry",
"deep-fry",
"poach",
"simmer",
"boil",
"steam",
"braise",
"stew"
],
description:
"'cooking_method' is optional but, if used, must be one of the listed options."
},
ingredients: {
bsonType: ["array"],
minItems: 1,
maxItems: 50,
items: {
bsonType: ["object"],
required: ["quantity", "measure", "ingredient"],
additionalProperties: false,
description: "'ingredients' must contain the stated fields.",
properties: {
quantity: {
bsonType: ["int", "double", "decimal"],
description:
"'quantity' is required and is of double or decimal type"
},
measure: {
enum: ["tsp", "Tbsp", "cup", "ounce", "pound", "each"],
description:
"'measure' is required and can only be one of the given enum values"
},
ingredient: {
bsonType: "string",
description: "'ingredient' is required and is a string"
},
format: {
bsonType: "string",
description:
"'format' is an optional field of type string, e.g. chopped or diced"
}
}
}
}
}
}
}
});`
Insert collection Example
`db.recipes.insertOne({
name: "Chocolate Sponge Cake Filling",
servings: 4,
ingredients: [
{
quantity: 7,
measure: "ounce",
ingredient: "bittersweet chocolate",
format: "chopped"
},
{ quantity: 2, measure: "cup", ingredient: "heavy cream" }
]
});`
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
The DUAL table is a special one-row table present by default in all Oracle database installations. It is suitable for use in selecting a pseudocolumn such as SYSDATE or USER
The table has a single VARCHAR2(1) column called DUMMY that has a value of "X"
You can read all about it in http://en.wikipedia.org/wiki/DUAL_table
It's kind of pointless to talk about "database performance", "query performance" is a better term here. And the answer is: it depends on the query, data that it operates on, indexes, hardware, etc. You can get an idea of how many rows are going to be scanned and what indexes are going to be used with EXPLAIN syntax.
2GB does not really count as a "large" database - it's more of a medium size.
Here is a version that JSLint likes:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var param = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = param.length,
tmp,
p;
for (p = 0; p < plength; p += 1) {
tmp = param[p].split('=');
GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:
/*jslint browser: true */
var GET = {};
(function (input) {
'use strict';
if (input.length > 1) {
var params = input.slice(1).replace(/\+/g, ' ').split('&'),
plength = params.length,
tmp,
key,
val,
obj,
p;
for (p = 0; p < plength; p += 1) {
tmp = params[p].split('=');
key = decodeURIComponent(tmp[0]);
val = decodeURIComponent(tmp[1]);
if (GET.hasOwnProperty(key)) {
obj = GET[key];
if (obj.constructor === Array) {
obj.push(val);
} else {
GET[key] = [obj, val];
}
} else {
GET[key] = val;
}
}
}
}(window.location.search));
window.alert(JSON.stringify(GET));
Only this sample working without problem:
var crop = new Rectangle(0, y, bitmap.Width, h);
var bmp = new Bitmap(bitmap.Width, h);
var tempfile = Application.StartupPath+"\\"+"TEMP"+"\\"+Path.GetRandomFileName();
using (var gr = Graphics.FromImage(bmp))
{
try
{
var dest = new Rectangle(0, 0, bitmap.Width, h);
gr.DrawImage(image,dest , crop, GraphicsUnit.Point);
bmp.Save(tempfile,ImageFormat.Jpeg);
bmp.Dispose();
}
catch (Exception)
{
}
}
Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".
Google indeed ignores most punctuation, with the following exceptions:
As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.
Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.
For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.
There two alternate ways to set accept header, which are as below:
1) setRequestHeader('Accept','application/json; charset=utf-8');
2) $.ajax({
dataType: ($.browser.msie) ? "text" : "json",
accepts: {
text: "application/json"
}
});
grep
will print any lines matching the pattern you provide. If you only want to print the part of the line that matches the pattern, you can pass the -o option:
-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Like this:
echo 'Here is a line mentioning 99% somewhere' | grep -o '[0-9]+'
I suppose subqueries and PIVOT would qualify, as well as multiple joins, unions and the like.
According to Scott Myers, Effective C++ (3rd ed.) item 42 (which must, of course, be the ultimate answer) - the difference is "nothing".
Advice is to use "class" if it is expected T will always be a class, with "typename" if other types (int, char* whatever) may be expected. Consider it a usage hint.