you can use "__range" for example :
from datetime import datetime
start_date=datetime(2009, 12, 30)
end_end=datetime(2020,12,30)
Sample.objects.filter(date__range=[start_date,end_date])
Simply put, hash-based collections aren't indexed so you have to do it manually.
Not sure if I understand your question, but max(id) won't give you the number of lines at all. For example if you have only one line with id = 13 (let's say you deleted the previous lines), you'll have max(id) = 13 but the number of rows is 1. The correct (and fastest) solution is to use count(). BTW if you wonder why there's a star, it's because you can count lines based on a criteria.
Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.
i was looking for the same. and found this solution.
Use negative regex assertion:
location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) {
.... # your stuff
}
Source Negated Regular Expressions in location
Explanation of Regex :
If URL does not match any of the following path
example.com/favicon.ico
example.com/resources
example.com/robots.txt
Then it will go inside that location block and will process it.
I think is a little late but
sudo yum install -y gcc ruby-devel libxml2 libxml2-devel libxslt libxslt-devel
worked for me on fedora.
A delegate is a simple class that is used to point to methods with a specific signature, becoming essentially a type-safe function pointer. A delegate's purpose is to facilitate a call back to another method (or methods), after one has been completed, in a structured way.
While it could be possible to create an extensive set of code to perform this functionality, you don’t need too. You can use a delegate.
Creating a delegate is easy to do. Identify the class as a delegate with the "delegate" keyword. Then specify the signature of the type.
You can't search a text field without converting it from text to varchar.
declare @table table (a text)
insert into @table values ('a')
insert into @table values ('a')
insert into @table values ('b')
insert into @table values ('c')
insert into @table values ('d')
select *
from @table
where a ='a'
This give an error:
The data types text and varchar are incompatible in the equal to operator.
Wheras this does not:
declare @table table (a varchar(max))
Interestingly, LIKE
still works, i.e.
where a like '%a%'
Try this it's working for me
RequestOptions requestOptions = new RequestOptions();
Glide.with(getContext())
.load("video_url")
.apply(requestOptions)
.thumbnail(Glide.with(getContext()).load("video_url"))
.into("yourimageview");
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Another way of doing it is using HttpResponsePermanentRedirect like so:
In view.py
def url_redirect(request):
return HttpResponsePermanentRedirect("/new_url/")
In the url.py
url(r'^old_url/$', "website.views.url_redirect", name="url-redirect"),
I know this is a bit late but what I did to our application is this. Hope this will help someone tho. But it works for me:
SELECT * FROM `landmarks` WHERE `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE 'keyword%'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword%'
__repr__
is used by the standalone Python interpreter to display a class in printable format. Example:
~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
... def __init__(self):
... pass
... def __repr__(self):
... return '<StackOverflow demo object __repr__>'
...
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>
In cases where a __str__
method is not defined in the class, it will call the __repr__
function in an attempt to create a printable representation.
>>> str(demo)
'<StackOverflow demo object __repr__>'
Additionally, print()
ing the class will call __str__
by default.
Documentation, if you please
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute
. If so, you should make sure that you inherit that, and not ActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
If you want to extract the hours, minutes and seconds, try this:
String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);
// if numeric
if (is_numeric($field)) {
$whole = floor($field);
$fraction = $field - $whole;
// if decimal
if ($fraction > 0)
// do sth
else
// if integer
// do sth
}
else
// if non-numeric
// do sth
There is a lot of options and they all have their pro and cons.
Pros
Cons
Pros
Cons
Pros
Cons
Pros
Cons
Disclosure: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
Replace bigint(20) not null auto_increment
by bigserial not null
and
datetime
by timestamp
Assuming you got it from https://curl.haxx.se/download.html, just unzip it wherever you want. No need to install. If you are going to use SSL, you need to download the OpenSSL DLLs, available from curl's website.
You cannot use a constant literal for a default parameter for the same reason you cannot use one as a parameter to the function call. Reference values must have an address, constant references values need not (ie they can be r-values or constant literals).
int* foo (int& i )
{
return &i;
}
foo(0); // compiler error.
const int* bar ( const int& i )
{
return &i;
}
bar(0); // ok.
Ensure that you're default value has an address and you're fine.
int null_object = 0;
int Write(int &state = null_object, bool sequence = true)
{
if( &state == &null_object )
{
// called with default paramter
return sequence? 1: rand();
}
else
{
// called with user parameter
state += sequence? 1: rand();
return state;
}
}
I've used this pattern a few times where I had a parameter that could be a variable or null. The regular approach is to have the user pass in a pointer this is case. They pass in a NULL pointer if they don't want you to fill in the value. I like to null object approach. It makes the callers life easier without terribly complicating the callee code.
This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.
from:
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
to:
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
Screenshot showing problem in JRE:
Is there anything I can do other than break in the middle of the tags rather than between them?
Not really. Since <img>
s are inline elements, spaces between these elements are considered by the HTML renderer as true spaces in text – redundant spaces (and line breaks) will be truncated but single spaces will be inserted into the character data of the text element.
Positioning the <img>
tags absolutely can prevent this but I'd advise against this since this would mean positioning each of the images manually to some pixel measure which can be a lot of work.
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
As metioned by nixxx adding ob_start()
before adding any php code will prevent the headers already sent error.
It worked for me
The code below also works. But it first loads the page and then redirects when I use it.
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';
ul {
width: 90%;
list-style-type:none;
margin:auto;
padding:0;
position:relative;
left:5%;
}
You can try this code:
public void itemClicked(View v) {
//code to check if this checkbox is checked!
if(((Checkbox)v).isChecked()){
// code inside if
}
}
The simplest in my opinion is just this:
it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
print x, y
Out: 1 2
3 4
5 6
No extra imports or anything. And very elegant, in my opinion.
Check it out -
<input type="button" id="btnclick" value="click" />
var intervalA;
var intervalB;
$(document).ready(function () {
$('#btnclick').click(function () {
blinkFont();
setTimeout(function () {
clearInterval(intervalA);
clearInterval(intervalB);
}, 5000);
});
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("blinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
<div id="blink" class="live-chat">
<span>This is blinking text and background</span>
</div>
Open a terminal window
cd into YOUR_PROJECT/ios
Remove the build folder with rm -r build
After that open your project in Xcode and run once. it will run with starting the server and create the main.jsbundle
file.
Now if you Run react-native run-ios
from terminal again it will work as expected.
Hope it will help!.
As @bmleite already mentioned in the comments, you probably forgot to load angular.js.
If I create a fiddle with angular directives in it, but don't include angular.js I get the exact same error in the Chrome console: Uncaught ReferenceError: angular is not defined
public Form1()
{
InitializeComponent();
string myHost = System.Net.Dns.GetHostName();
string myIP = null;
for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
{
myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
}
}
}
Declare myIP and myHost in public Variable and use in any function of the form.
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!
Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
Finally create a new Date
object and strip minutes and seconds
let finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
For completeness, guava also has a handy utility for this
ByteStreams.copy(input, output);
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
Both styles, with a touch of tweaking, would work.
The first method uses a Javascript Constructor, which like most things has pros and cons.
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
The basic syntax for using ternary operator is like this:
(condition) ? (if_true) : (if_false)
For you case it is like this:
number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if
as a top-level step in declarative, so you need to wrap it in a script
step. here's a working declarative version:
pipeline {
agent any
stages {
stage('test') {
steps {
sh 'echo hello'
}
}
stage('test1') {
steps {
sh 'echo $TEST'
}
}
stage('test3') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
}
}
you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!
You must check this: Docblock Comment standards
filter: blur(0)
transition: filter .3s ease-out
transition-timing-function: steps(3, end) // add this string with steps equal duration
I was helped by setting the value of transition duration .3s
equal transition timing steps .3s
You should try console_runner gem. This gem makes your pure Ruby code executable from command-line. All you need is to add YARD annotations to your code:
# @runnable This tool can talk to you. Run it when you are lonely.
# Written in Ruby.
class MyClass
def initialize
@hello_msg = 'Hello'
@bye_msg = 'Good Bye'
end
# @runnable Say 'Hello' to you.
# @param [String] name Your name
# @param [Hash] options options
# @option options [Boolean] :second_meet Have you met before?
# @option options [String] :prefix Your custom prefix
def say_hello(name, options = {})
second_meet = nil
second_meet = 'Nice to see you again!' if options['second_meet']
prefix = options['prefix']
message = @hello_msg + ', '
message += "#{prefix} " if prefix
message += "#{name}. "
message += second_meet if second_meet
puts message
end
end
Then run it from console:
$ c_run /projects/example/my_class.rb say_hello -n John --second-meet --prefix Mr.
-> Hello, Mr. John. Nice to see you again!
Here's an extension to find the nearest vector in an array of vectors.
import numpy as np
def find_nearest_vector(array, value):
idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
return array[idx]
A = np.random.random((10,2))*100
""" A = array([[ 34.19762933, 43.14534123],
[ 48.79558706, 47.79243283],
[ 38.42774411, 84.87155478],
[ 63.64371943, 50.7722317 ],
[ 73.56362857, 27.87895698],
[ 96.67790593, 77.76150486],
[ 68.86202147, 21.38735169],
[ 5.21796467, 59.17051276],
[ 82.92389467, 99.90387851],
[ 6.76626539, 30.50661753]])"""
pt = [6, 30]
print find_nearest_vector(A,pt)
# array([ 6.76626539, 30.50661753])
// if you need to check if all items' MyProperty doesn't have null
if (list.All(x => x.MyProperty != null))
// do something
// or if you need to check if at least one items' property has doesn't have null
if (list.Any(x => x.MyProperty != null))
// do something
But you always have to check for null
Inside the DataTemplate
you're working in the context of a Rule
, that's why you cannot bind to SelectedRule.Name
-- there is no such property on a Rule
.
To bind to the original data context (which is your ViewModel) you can write:
<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />
UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:
XAML:
<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ListBoxSelectedItem" Height="300" Width="300"
xmlns:app="clr-namespace:TestWpfApplication">
<Window.DataContext>
<app:ListBoxSelectedItemViewModel/>
</Window.DataContext>
<ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" />
<TextBox Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
Code behind:
namespace TestWpfApplication
{
/// <summary>
/// Interaction logic for ListBoxSelectedItem.xaml
/// </summary>
public partial class ListBoxSelectedItem : Window
{
public ListBoxSelectedItem()
{
InitializeComponent();
}
}
public class Rule
{
public string Name { get; set; }
}
public class ListBoxSelectedItemViewModel
{
public ListBoxSelectedItemViewModel()
{
Rules = new ObservableCollection<Rule>()
{
new Rule() { Name = "Rule 1"},
new Rule() { Name = "Rule 2"},
new Rule() { Name = "Rule 3"},
};
}
public ObservableCollection<Rule> Rules { get; private set; }
private Rule selectedRule;
public Rule SelectedRule
{
get { return selectedRule; }
set
{
selectedRule = value;
}
}
}
}
The concept is simple:
M =[(1, 1), (5, 6), (0, 0)]
1) print([any(x) for x in M])
[True, True, False] #only the last tuple does not have any true element
2) print([all(x) for x in M])
[True, True, False] #all elements of the last tuple are not true
3) print([not all(x) for x in M])
[False, False, True] #NOT operator applied to 2)
4) print([any(x) and not all(x) for x in M])
[False, False, False] #AND operator applied to 1) and 3)
# if we had M =[(1, 1), (5, 6), (1, 0)], we could get [False, False, True] in 4)
# because the last tuple satisfies both conditions: any of its elements is TRUE
#and not all elements are TRUE
For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
see my answer here:
How can I get the current date and time in UTC or GMT in Java?
I've fully tested it by changing the timezones on the emulator
It Work for me !
private: System::Void MyButton_Delete_Click(System::Object^ sender, System::EventArgs^ e) {
// ??????? ???????(Row).
MydataGridView->Rows->RemoveAt(MydataGridView->CurrentCell->RowIndex);
}
Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.
The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.
Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!
Steps with version 4.35.1:
click 'Add Connection'
Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.
Under 'Provider' choose 'SQL CE 4.0'.
Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.
Click 'OK'.
Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
There is a point to only put commands and options in variables.
#! /bin/bash
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
exit 1
fi
. standard_tools
directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"
${tar_create} "${directory}" | ${openssl} | ${split_1024} "$backup_file"
You can relocate the commands to another file you source, so you can reuse the same commands and options across many scripts. This is very handy when you have a lot of scripts and you want to control how they all use tools. So standard_tools would contain:
export tar_create="tar cv"
export openssl="openssl des3 -salt"
export split_1024="split -b 1024m -"
This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.
Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011
. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.
When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY
, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.
Whether that is the problem or not, you should always specify the date model:
UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');
Since you aren't specifying a time component - all Oracle DATE
columns include a time, even if it's midnight - you could also use a date literal:
UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';
You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.
You can do the following(jackson version < 2):
Custom mapper class:
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
super.getSerializationConfig()
.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
super.getSerializationConfig()
.set(SerializationConfig.Feature.INDENT_OUTPUT, false);
}
}
Spring config:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="package.CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right
only push the div to the right, but not the content inside the div.
HTML:
<div class="row">
<div class="container">
<div class="col-md-4 someclass">
left content
</div>
<div class="col-md-4 col-md-offset-4 someclass">
<div class="yellow_background totheright">right content</div>
</div>
</div>
</div>
CSS:
.someclass{ /*this class for testing purpose only*/
border:1px solid blue;
line-height:2em;
}
.totheright{ /*this will align the text to the right*/
text-align:right;
}
.yellow_background{
background-color:yellow;
}
Another modification:
...
<div class="yellow_background totheright">
<span>right content</span>
<br/>image also align-right<br/>
<img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...
hope it will clear your problem
You should look into Video For Everyone:
Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.
The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.
In other browsers that do not support , it falls back to QuickTime.
If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.
The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).
<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
<source src="__VIDEO__.mp4" type="video/mp4" />
<source src="__VIDEO__.webm" type="video/webm" />
<source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
<object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
[endif]--><!--[if !IE]><!-->
<object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
<param name="src" value="__VIDEO__.mp4" />
<param name="autoplay" value="false" />
<param name="showlogo" value="false" />
<object width="640" height="380" type="application/x-shockwave-flash"
data="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4">
<param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4" />
<img src="__POSTER__.jpg" width="640" height="360" />
<p>
<strong>No video playback capabilities detected.</strong>
Why not try to download the file instead?<br />
<a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
<a href="__VIDEO__.ogv">Ogg Theora & Vorbis “.ogv” (Linux)</a>
</p>
</object><!--[if gt IE 6]><!-->
</object><!--<![endif]-->
</video>
There is an updated version that is a bit more readable:
<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
=================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0 -->
<video width="640" height="360" controls preload="none">
<!-- MP4 must be first for iPad! -->
<source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video -->
<source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
<source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
<!-- fallback to Flash: -->
<object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
<!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
<param name="movie" value="__FLASH__.SWF" />
<param name="flashvars" value="image=__POSTER__.JPG&file=__VIDEO__.MP4" />
<!-- fallback image. note the title field below, put the title of the video there -->
<img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
title="No video playback capabilities, please download the video below" />
</object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
Closed Format: <a href="__VIDEO__.MP4">"MP4"</a>
Open Format: <a href="__VIDEO__.OGV">"OGG"</a>
</p>
Find config.inc
file under C:\wamp\apps\phpmyadmin3.5.1
Inside this file find
this one line
$cfg['Servers'][$i]['password'] =";
and replace it with
$cfg['Servers'][$i]['password'] = 'Type your root password here';
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
String a = "...";
String b = "...";
int compare = a.compareTo(b);
if (compare < 0) {
//a is smaller
}
else if (compare > 0) {
//a is larger
}
else {
//a is equal to b
}
plundberg: The "disconnect" button is only available for the TFS provider starting in VS 2008. Even then, I'm not sure if it's officially supported. The recommended way to use the Go Offline feature is to [re]open the solution.
Martin Pritchard: if you get stuck mid-operation, you can force VS to timeout by pulling the network plug (literally) or running ipconfig /release.
Once you're marked offline, here's a step by step guide to working in that mode: http://teamfoundation.blogspot.com/2007/12/offline-and-back-again-in-vs2008.html
More detailed info on tweaking the behind-the-scenes behavior: http://blogs.msdn.com/benryan/archive/2007/12/12/when-and-how-does-my-solution-go-offline.aspx http://blogs.msdn.com/benryan/archive/2007/12/12/how-to-make-tfs-offline-strictly-solution-based.aspx
Cell spacing and margin is the space between cells.
Cell padding is space inside cells, between the cell border (even if invisible) and the cell content, such as text.
On form fields like these
<input type="text" name="user[name]" value="MyName">
<input type="text" name="user[email]" value="[email protected]">
some of the above answers will fail because they only support flat data.
For now I am using the Casey Chu answer but with the "qs" instead of the "querystring" module. This is the module "body-parser" uses as well. So if you want nested data you have to install qs.
npm install qs --save
Then replace the first line like:
//var qs = require('querystring');
var qs = require('qs');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
console.log(post.user.name); // should work
// use post['blah'], etc.
});
}
}
I'm able to get the Class of the generic type this way:
class MyList<T> {
Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}
You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java
For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860
In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:
C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"
For anyone arriving here still looking for good a solution for "upserting" with hooks support, this is what I have tested and working. It still requires 2 DB calls but is much more stable than anything I've tried in a single call.
// Create or update a Person by unique email.
// @param person - a new or existing Person
function savePerson(person, done) {
var fieldsToUpdate = ['name', 'phone', 'address'];
Person.findOne({
email: person.email
}, function(err, toUpdate) {
if (err) {
done(err);
}
if (toUpdate) {
// Mongoose object have extra properties, we can either omit those props
// or specify which ones we want to update. I chose to update the ones I know exist
// to avoid breaking things if Mongoose objects change in the future.
_.merge(toUpdate, _.pick(person, fieldsToUpdate));
} else {
toUpdate = person;
}
toUpdate.save(function(err, updated, numberAffected) {
if (err) {
done(err);
}
done(null, updated, numberAffected);
});
});
}
Based off a few answers already given here I decided to mostly back JoelFan's answer. I love extension methods and these have been working great for me when none of the other solutions would using them to compare my complex classes.
using System.IO;
using System.Xml.Serialization;
static class ObjectHelpers
{
public static string SerializeObject<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
public static bool EqualTo(this object obj, object toCompare)
{
if (obj.SerializeObject() == toCompare.SerializeObject())
return true;
else
return false;
}
public static bool IsBlank<T>(this T obj) where T: new()
{
T blank = new T();
T newObj = ((T)obj);
if (newObj.SerializeObject() == blank.SerializeObject())
return true;
else
return false;
}
}
if (record.IsBlank())
throw new Exception("Record found is blank.");
if (record.EqualTo(new record()))
throw new Exception("Record found is blank.");
I really liked Al P's answer but wanted uniqueness enforced cheaply so I took it one step further - use a directory. There are some obvious limitations (directory file limits, invalid file names) but it should work for most cases.
hinit() {
rm -rf /tmp/hashmap.$1
mkdir -p /tmp/hashmap.$1
}
hput() {
printf "$3" > /tmp/hashmap.$1/$2
}
hget() {
cat /tmp/hashmap.$1/$2
}
hkeys() {
ls -1 /tmp/hashmap.$1
}
hdestroy() {
rm -rf /tmp/hashmap.$1
}
hinit ids
for (( i = 0; i < 10000; i++ )); do
hput ids "key$i" "value$i"
done
for (( i = 0; i < 10000; i++ )); do
printf '%s\n' $(hget ids "key$i") > /dev/null
done
hdestroy ids
It also performs a tad bit better in my tests.
$ time bash hash.sh
real 0m46.500s
user 0m16.767s
sys 0m51.473s
$ time bash dirhash.sh
real 0m35.875s
user 0m8.002s
sys 0m24.666s
Just thought I'd pitch in. Cheers!
Edit: Adding hdestroy()
I know this is an old question, but nowadays there is a super easy form to do that, which is CCS Grid, so let me put the divs as example:
<div id="full">
<div id="header">Contents of 1</div>
<div id="someid">Contents of 2</div>
</div>
then the CSS code:
.full{
width:/*the width you need*/;
height:/*the height you need*/;
display:grid;
grid-template-rows: minmax(100px,auto) 1fr;
}
And that's it, the second row, scilicet, the someide, will take the rest of the height because of the property 1fr, and the first div will have a min of 100px and a max of whatever it requires.
I must say CSS has advanced a lot to make easier programmers lives.
Use juffrou-reflect's BeanWrapper. It is very performant.
Here is how you can transform a bean into a map:
public static Map<String, Object> getBeanMap(Object bean) {
Map<String, Object> beanMap = new HashMap<String, Object>();
BeanWrapper beanWrapper = new BeanWrapper(BeanWrapperContext.create(bean.getClass()));
for(String propertyName : beanWrapper.getPropertyNames())
beanMap.put(propertyName, beanWrapper.getValue(propertyName));
return beanMap;
}
I developed Juffrou myself. It's open source, so you are free to use it and modify. And if you have any questions regarding it, I'll be more than happy to respond.
Cheers
Carlos
Using base R aggregate
function:
aggregate(value ~ name, dat1, I)
# name value.1 value.2 value.3 value.4
#1 firstName 0.4145 -0.4747 0.0659 -0.5024
#2 secondName -0.8259 0.1669 -0.8962 0.1681
if (array[0]=1)
should be if (array[0]==1)
.
The same with else if (array[0]=2)
.
Note that the expression of the assignment returns the assigned value, in this case if (array[0]=1)
will be always true, that's why the code below the if-statement will be always executed if you don't change the =
to ==
.
=
is the assignment operator, you want to compare, not to assign. So you need ==
.
Another thing, if you want only one integer, why are you using array? You might want also to scanf("%d", &array[0]);
The standard way is to use audio/mpeg
which is something like this in your PHP header function ...
header('Content-Type: audio/mpeg');
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
import os
head, tail = os.path.split('path/to/file.exe')
tail is what you want, the filename.
See python os module docs for detail
You can use the tee
command to redirect output:
/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz) | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1
see documentation here
Starting OracleServiceHari where 'HARI' is the SID, worked for me.
Others facing same problem may check status of the service.
For Android 4.0 (Ice Cream Sandwich) and later, I needed to add these, besides the landscape
value.
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
Using only keyboardHidden|orientation
would still result in memory leaks and recreation of my activities when pressing the power button.
This is a maven error. It says that it is expecting a web.xml file in your project because it is a web application, as indicated by <packaging>war</packaging>
. However, for recent web applications a web.xml file is totally optional. Maven needs to catch up to this convention.
Add this to your maven pom.xml
to let maven catch up and you don't need to add a useless web.xml
to your project:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
This is a better solution than adding an empty web.xml
because this way your final product stays clean, your are just changing your build parameters.
For more current versions of maven you can also use the shorter version:
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
Pulling loads of binary data out of your DB over the wire is going to cause huge latency issues and won't scale well.
Store paths in the DB and let your webserver take the load - it's what it was designed for!
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
This should work:
GetCountries():Observable<CountryData[]> {
return this.http.get(`http://services.groupkt.com/country/get/all`)
.map((res:Response) => <CountryData[]>res.json());
}
For this to work you will need to import the following:
import 'rxjs/add/operator/map'
Gives the Max Count of record in table
select max(len(Description))from Table_Name
Gives Record Having Greater Count
select Description from Table_Name group by Description having max(len(Description)) >27
Hope helps someone.
I was building a simple tipCalculator and there was a lot of answers here that seem to overcomplicate the issue. So I found summarizing the issue to be the best way to truly answer this question
if you want to create a rounded decimal number, first you call toFixed(# of decimal places you want to keep)
and then wrap that in a Number()
so end result:
let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip) // 57.29 instead of 57.288
In my case I use a template component in Blazor.
<BTable ID="Table1" TotalRows="MyList.Count()">
The problem is calling a method (Count) in the component header. To resolve the problem I changed it like this :
int total = MyList.Count();
and later :
<BTable ID="Table1" TotalRows="total">
You can't initialize arrays like this:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.
for 1D arrays:
int tomultiply[Array_size]={0};
I solved the same problem by installing "matplotlib".
from foo import *
adds all the names without leading underscores (or only the names defined in the modules __all__
attribute) in foo
into your current module.
In the above code with from socket import *
you just want to catch timeout
as you've pulled timeout
into your current namespace.
from socket import *
pulls in the definitions of everything inside of socket
but doesn't add socket
itself.
try:
# socketstuff
except timeout:
print 'caught a timeout'
Many people consider import *
problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.
For example, consider the following three python files:
# a.py
def foo():
print "this is a's foo function"
# b.py
def foo():
print "this is b's foo function"
# yourcode.py
from a import *
from b import *
foo()
If you run yourcode.py
you'll see just the output "this is b's foo function".
For this reason I'd suggest either importing the module and using it or importing specific names from the module:
For example, your code would look like this with explicit imports:
import socket
from socket import AF_INET, SOCK_DGRAM
def main():
client_socket = socket.socket(AF_INET, SOCK_DGRAM)
client_socket.settimeout(1)
server_host = 'localhost'
server_port = 1234
while(True):
client_socket.sendto('Message', (server_host, server_port))
try:
reply, server_address_info = client_socket.recvfrom(1024)
print reply
except socket.timeout:
#more code
Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.
Try this in the .htaccess of the external root folder
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Be careful on : Header add Access-Control-Allow-Origin "*" This is not judicious at all to grant access to everybody. I think you should user:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://example.com"
</IfModule>
Use python Sets when you need to compare hm... sets of data. Strings can be represented as sets of characters quite fast. Here I test if string is allowed phone number. First string is allowed, second not. Works fast and simple.
In [17]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(898) 64-901-63 ');p.issubset(allowed)").timeit()
Out[17]: 0.8106249139964348
In [18]: timeit.Timer("allowed = set('0123456789+-() ');p = set('+7(950) 64-901-63 ???');p.issubset(allowed)").timeit()
Out[18]: 0.9240323599951807
Never use regexps if you can avoid them.
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
instead of using add() we can use addall()
{ seeAlso.addall(groupDn); }
add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.
I have done it like this and it seems to work:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
}
It looks like Google actively frowns on using IP-to-location mapping:
https://developers.google.com/maps/articles/geolocation?hl=en
That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:
numpy 1D array --> column/row matrix:
>>> a=np.array([1,2,4])
>>> a[:, None] # col
array([[1],
[2],
[4]])
>>> a[None, :] # row, or faster `a[None]`
array([[1, 2, 4]])
And as @joe-kington said, you can replace None
with np.newaxis
for readability.
Adding this answer for completeness, though it's only usable under certain conditions.
If you have very large lists, removing from the end of the list avoids CPython internals having to memmove
, for situations where you can re-order the list. It gives a performance gain to remove from the end of the list, since it won't need to memmove
every item after the one your removing - back one step (1).
For one-off removals the performance difference may be acceptable, but if you have a large list and need to remove many items - you will likely notice a performance hit.
Although admittedly, in these cases, doing a full list search is likely to be a performance bottleneck too, unless items are mostly at the front of the list.
This method can be used for more efficient removal,
as long as re-ordering the list is acceptable. (2)
def remove_unordered(ls, item):
i = ls.index(item)
ls[-1], ls[i] = ls[i], ls[-1]
ls.pop()
You may want to avoid raising an error when the item
isn't in the list.
def remove_unordered_test(ls, item):
try:
i = ls.index(item)
except ValueError:
return False
ls[-1], ls[i] = ls[i], ls[-1]
ls.pop()
return True
A simple way to test this, compare the speed difference from removing from the front of the list with removing the last element:
python -m timeit 'a = [0] * 100000' 'while a: a.remove(0)'
With:
python -m timeit 'a = [0] * 100000' 'while a: a.pop()'
(gives an order of magnitude speed difference where the second example is faster with CPython and PyPy).
set
, especially if the list isn't meant to store duplicates.set
. Also check on btree's if the data can be ordered.For me, the problem was caused by the .bat
included a cd
to a network drive. This failed, and then the later call to the program in that network drive did nothing.
I figured this out by adding > log.txt
in the Add arguments field of the Edit action window for the task.
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit
to exit on any error
CONTEXT_INFO is used to keep track of the state.
SET CONTEXT_INFO 0x1 --Just to make sure everything's ok
GO
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2
BEGIN
SELECT CONTEXT_INFO()
SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT
WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO
----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------
Streams are EventEmitter
s so you can listen to certain events. As you said there is a finish
event for request (previously end
).
var stream = request(...).pipe(...);
stream.on('finish', function () { ... });
For more information about which events are available you can check the stream documentation page.
If you copy paste your project the .angular-cli.json you wil not find this file try to create a new file with the same name and add the code and it wil work.
You just need to supply a password. You can do it within the same command line with the following syntax:
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password]
You will then be prompted for a password to encrypt the private key in your output file. Include the "nodes" option in the line above if you want to export the private key unencrypted (plaintext):
openssl pkcs12 -export -in "path.p12" -out "newfile.pem" -passin pass:[password] -nodes
More info: http://www.openssl.org/docs/apps/pkcs12.html
I'm trying to find a method to redirect my request from filter to login page
Don't
You just invoke
chain.doFilter(request, response);
from filter and the normal flow will go ahead.
I don't know how to redirect from servlet
You can use
response.sendRedirect(url);
to redirect from servlet
Can't be iterating directly in dictionary. So you can through converting into tuple.
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
tup_field=tuple(fields.items())
for names in fields.items():
field,possible_values = names
tup_possible_values=tuple(possible_values)
for pvalue in tup_possible_values:
print (field + "is" + pvalue)
The only way I think then to get the functionality you want would be to do something like
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("TestEverything");
//$JUnit-BEGIN$
suite.addTestSuite(TestOne.class);
suite.addTestSuite(TestTwo.class);
suite.addTestSuite(TestThree.class);
//$JUnit-END$
}
public static void main(String[] args)
{
AllTests test = new AllTests();
Test testCase = test.suite();
TestResult result = new TestResult();
setUp();
testCase.run(result);
tearDown();
}
public void setUp() {}
public void tearDown() {}
}
I use something like this in eclipse, so I'm not sure how portable it is outside of that environment
It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.
import ftplib
import os
def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
myFTP = ftplib.FTP(server, username, password)
if destinationDirectory in [name for name, data in list(remote.mlsd())]:
print "Destination Directory does not exist. Creating it first"
myFTP.mkd(destinationDirectory)
# Changing Working Directory
myFTP.cwd(destinationDirectory)
if os.path.isfile(sourceFilePath):
fh = open(sourceFilePath, 'rb')
myFTP.storbinary('STOR %s' % f, fh)
fh.close()
else:
print "Source File does not exist"
I solved my problem in AngularJS as follows:
var configPopOver = {
animation: 500,
container: 'body',
placement: function (context, source) {
var elBounding = source.getBoundingClientRect();
var pageWidth = angular.element('body')[0].clientWidth
var pageHeith = angular.element('body')[0].clientHeith
if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "left";
}
if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
return "right";
}
if (elBounding.top < 110){
return "bottom";
}
return "top";
},
html: true
};
This function do the position of Bootstrap popover float to the best position, based on element position.
Adamski provided the best answer, but it is not quite complete, so read his reply, as it explains the details I'm not.
If you have a system function that requires an unsigned byte to be passed to it, you can pass a signed byte as it will automatically treat it as an unsigned byte.
So if a system function requires four bytes, for example, 192 168 0 1 as unsigned bytes you can pass -64 -88 0 1, and the function will still work, because the act of passing them to the function will un-sign them.
However you are unlikely to have this problem as system functions are hidden behind classes for cross-platform compatibility, though some of the java.io read methods return unsighed bytes as an int.
If you want to see this working, try writing signed bytes to a file and read them back as unsigned bytes.
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.
It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE
statements, OUTPUT
clauses, and other finicky stuff.
The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.
In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).
Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!
Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
What you should do is convert every char using charCodeAt
function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2)
:
HTML:
<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>
JS:
function convert() {
var output = document.getElementById("ti2");
var input = document.getElementById("ti1").value;
output.value = "";
for (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}
And here's a fiddle: http://jsfiddle.net/fA24Y/1/
T-SQL supports only AFTER and INSTEAD OF triggers, it does not feature a BEFORE trigger, as found in some other RDBMSs.
I believe you will want to use an INSTEAD OF trigger.
I am a .NET developer, and have used Git and Visual Studio for years. My strong recommendation is set line endings to true. And do it as early as you can in the lifetime of your Repository.
That being said, I HATE that Git changes my line endings. A source control should only save and retrieve the work I do, it should NOT modify it. Ever. But it does.
What will happen if you don't have every developer set to true, is ONE developer eventually will set to true. This will begin to change the line endings of all of your files to LF in your repo. And when users set to false check those out, Visual Studio will warn you, and ask you to change them. You will have 2 things happen very quickly. One, you will get more and more of those warnings, the bigger your team the more you get. The second, and worse thing, is that it will show that every line of every modified file was changed(because the line endings of every line will be changed by the true guy). Eventually you won't be able to track changes in your repo reliably anymore. It is MUCH easier and cleaner to make everyone keep to true, than to try to keep everyone false. As horrible as it is to live with the fact that your trusted source control is doing something it should not. Ever.
create table like this,
CommentId UserId
---------------------
1 usr1
1 usr2
In this way you can check whether the user posted the comments are not..
Apart from this there should be tables for Comments
and Users
with respective id's
@Christoph: just adding someting . i dont think so this is a correct way.to logout at both places at the same time.(<a href="/logout" onclick="FB.logout();">Logout</a>
).
Just add id to the anchor tag . <a id='fbLogOut' href="/logout" onclick="FB.logout();">Logout</a>
$(document).ready(function(){
$('#fbLogOut').click(function(e){
e.preventDefault();
FB.logout(function(response) {
// user is now logged out
var url = $(this).attr('href');
window.location= url;
});
});});
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient
I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/
Your current code:
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
is telling ggplot
to construct one histogram using all the values in f0
and then color the bars of this single histogram according to the variable utt
.
What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram
, where each one gets it's own data frame and fill:
ggplot(histogram, aes(f0)) +
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) +
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2) +
Here's a concrete example with some output:
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
which produces something like this:
Edited to fix typos; you wanted fill, not colour.
Can you override the function? Will this not work:
function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}
new Double(99.9999).intValue()
@variable
s are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [Across all methods in the class]
Variables without the @
symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only. Limited to the local scope.
Example of Instance Variables:
class Customer
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details
puts "Customer id #{@cust_id}"
puts "Customer name #{@cust_name}"
puts "Customer address #{@cust_addr}"
end
end
In the above example @cust_id
, @cust_name
, @cust_addr
are accessed in another method within the class. But the same thing would not be accessible with local variables.
What you want is:
cp -R t1/. t2/
The dot at the end tells it to copy the contents of the current directory, not the directory itself. This method also includes hidden files and folders.
I do this:
Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
...
})
This will show the most recent things first.
if(is_array($arr) && count($arr) > 1)
Just to be sure that $arr is indeed an array.
sizeof
is an alias of count
, I prefer to use count because:
Much simpler using only SimpleDateFormat, without passing all the parameters individual:
String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date = new Date();
XMLGregorianCalendar gDateFormatted =
DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));
Full example here.
Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd
.
You need to be aware of named export
and default export
. See When should I use curly braces for ES6 import?
In my case, I fixed it by changing from
import Provider from 'react-redux'
to
import { Provider } from 'react-redux'
Please try as below to get the time difference in hh:mm:ss format
Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]
// Form A
public void loaddata()
{
//do what you do in load data in order to update data in datagrid
}
then on Form B define:
// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];
private void button1_Click(object sender, EventArgs e)
{
obj.loaddata();
datagridview1.Update();
datagridview1.Refresh();
}
I think it is good to categorize relations like this
When to use eager loading
When to use lazy loading
Note: like Transcendent said there may be disposal problem with lazy loading.
You can do it using the Github API
This is the Python example:
import requests
if __name__ == '__main__':
base_api_url = 'https://api.github.com/repos'
git_repository_url = 'https://github.com/garysieling/wikipedia-categorization.git'
github_username, repository_name = git_repository_url[:-4].split('/')[-2:] # garysieling and wikipedia-categorization
res = requests.get(f'{base_api_url}/{github_username}/{repository_name}')
repository_size = res.json().get('size')
print(repository_size)
One shoudn't try to import android.R
. Try to fix all errors that appear in XML files, including the manifest file. When all errors are cleared, R.java
will reappear.
//1 year from today's date
echo date('d-m-Y', strtotime('+1 year'));
//1 year from from specific date
echo date('22-09-Y', strtotime('+1 year'));
hope this simpler bit of code helps someone in future :)
Not an OP direct response, but I thought I would jimmy in here responding to the the OP's ERROR messsage, which may point you in another direction entirely!
All these answers are referring to an overall ORDER BY once the record set has been retrieved and you sort the lot.
What if you want to ORDER BY each portion of the UNION independantly, and still have them "joined" in the same SELECT?
SELECT pass1.* FROM
(SELECT TOP 1000 tblA.ID, tblA.CustomerName
FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL
SELECT pass2.* FROM
(SELECT TOP 1000 tblB.ID, tblB.CustomerName
FROM TABLE_B AS tblB ORDER BY 2) AS pass2
Note the TOP 1000 is an arbitary number. Use a big enough number to capture all of the data you require.
You can attach to a running process with gdb -p PID
.
i think the assets folder is public, you can access it directly on the browser
unlike other privates folders, drop your json file in the assets folder
Regarding the error
'CREATE VIEW' must be the first statement in a query batch.
Microsoft SQL Server has a quirky reqirement that CREATE VIEW
be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION
. It is not true of CREATE TABLE
, so go figure …
The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.
The more convenient solution is to get the client to send the script in small isolated batches.
The GO
keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.
As a result, you end up writing something like:
DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO
None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find
... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
Just for reference as it was something I was looking for, you can test for presence within the values or the index by appending the ".values" method, e.g.
g in df.<your selected field>.values
g in df.index.values
I find that adding the ".values" to get a simple list or ndarray out makes exist or "in" checks run more smoothly with the other python tools. Just thought I'd toss that out there for people.
Java doesn't have a general purpose define
preprocessor directive.
In the case of constants, it is recommended to declare them as static finals
, like in
private static final int PROTEINS = 100;
Such declarations would be inlined by the compilers (if the value is a compile-time constant).
Please note also that public static final constant fields are part of the public interface and their values shouldn't change (as the compiler inlines them). If you do change the value, you would need to recompile all the sources that referenced that constant field.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;
List<Address> addList=new ArrayList<Address>();
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
return addList;
}
public void setAddList(List<Address> addList) {
this.addList = addList;
}
}
We have two entities Employee and Address with One to Many relationship.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private int address_id;
private String address;
Employee employee;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
return address_id;
}
public void setAddress_id(int address_id) {
this.address_id = address_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
By this way we can implement inner join between two tables
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
saveEmployee();
retrieveEmployee();
}
private static void saveEmployee() {
Employee employee=new Employee();
Employee employee1=new Employee();
Employee employee2=new Employee();
Employee employee3=new Employee();
Address address=new Address();
Address address1=new Address();
Address address2=new Address();
Address address3=new Address();
address.setAddress("1485,Sector 42 b");
address1.setAddress("1485,Sector 42 c");
address2.setAddress("1485,Sector 42 d");
address3.setAddress("1485,Sector 42 a");
employee.setEmpName("Varun");
employee1.setEmpName("Krishan");
employee2.setEmpName("Aasif");
employee3.setEmpName("Dut");
address.setEmployee(employee);
address1.setEmployee(employee1);
address2.setEmployee(employee2);
address3.setEmployee(employee3);
employee.getAddList().add(address);
employee1.getAddList().add(address1);
employee2.getAddList().add(address2);
employee3.getAddList().add(address3);
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(employee);
session.save(employee1);
session.save(employee2);
session.save(employee3);
session.getTransaction().commit();
session.close();
}
private static void retrieveEmployee() {
try{
String sqlQuery="select e from Employee e inner join e.addList";
Session session=HibernateUtil.getSessionFactory().openSession();
Query query=session.createQuery(sqlQuery);
List<Employee> list=query.list();
list.stream().forEach((p)->{System.out.println(p.getEmpName());});
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Address.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.
See this article for an example.
You need a dependency property for this:
public BindingList<User> Users
{
get { return (BindingList<User>)GetValue(UsersProperty); }
set { SetValue(UsersProperty, value); }
}
public static readonly DependencyProperty UsersProperty =
DependencyProperty.Register("Users", typeof(BindingList<User>),
typeof(OptionsDialog));
Once that is done, you bind the checkbox to the dependency property:
<CheckBox x:Name="myCheckBox"
IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" />
For that to work you have to name your Window or UserControl in its openning tag, and use that name in the ElementName parameter.
With this code, whenever you change the property on the code side, you will change the textbox. Also, whenever you check/uncheck the textbox, the Dependency Property will change too.
EDIT:
An easy way to create a dependency property is typing the snippet propdp, which will give you the general code for Dependency Properties.
All the code:
XAML:
<Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" x:Name="window1" Height="300" Width="300">
<Grid>
<StackPanel Orientation="Vertical">
<CheckBox Margin="10"
x:Name="myCheckBox"
IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}">
Bound CheckBox
</CheckBox>
<Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}"
ContentStringFormat="Is checkbox checked? {0}" />
</StackPanel>
</Grid>
</Window>
C#:
using System.Windows;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public bool IsCheckBoxChecked
{
get { return (bool)GetValue(IsCheckBoxCheckedProperty); }
set { SetValue(IsCheckBoxCheckedProperty, value); }
}
// Using a DependencyProperty as the backing store for
//IsCheckBoxChecked. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckBoxCheckedProperty =
DependencyProperty.Register("IsCheckBoxChecked", typeof(bool),
typeof(Window1), new UIPropertyMetadata(false));
public Window1()
{
InitializeComponent();
}
}
}
Notice how the only code behind is the Dependency Property. Both the label and the checkbox are bound to it. If the checkbox changes, the label changes too.
You can try:
SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)
Where id
is a primary key of the your_table
One of the Honeycomb samples refers to ?android:attr/actionBarSize
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
I have faced same issue but copying the xampp\mysql\data\ibdata1
was not solved my problem, because I install new version of xampp, if you upgrading your xampp first make backup from all htdocs
and mysql
folder, in my case I just backup the all xampp to the new folder like old-xampp
then install new xampp and then you need do the following steps before starting your new xampp servers:
phpmyadmin
folder and ibdata1
from your new installation form this location xampp\mysql\data
.old-xampp\mysql\data
and copy the ibdata1
file and phpmyadmin
from old location.xampp\mysql\data
and past them there.Try using unbindService() in OnUserLeaveHint(). It prevents the the ServiceConnection leaked scenario and other exceptions.
I used it in my code and works fine.
it seems
command args overwrite environment variable
Makefile
send:
echo $(MESSAGE1) $(MESSAGE2)
Run example
$ MESSAGE1=YES MESSAGE2=NG make send MESSAGE2=OK
echo YES OK
YES OK
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
I think you are looking for nested loops.
Example (based on your edit):
t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]
t3=[]
for it1, e1 in enumerate(t1):
for it2, e2 in enumerate(t2):
if e1==e2:
t3.append((it1,it2,e1))
# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]
Which can be reduced to a single comprehension:
[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2]
But to find the common elements, you can just do:
print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
If your list contains non-hashable objects (like other lists, dicts) use a frozen set:
from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2
Should use this solution as a last choice, when other solutions don't work.
Original answer:
Work on macOS Chrome/Safari
body { font-family: '.SFNSDisplay-Regular', sans-serif; }
This should display 'Tue':
new SimpleDateFormat("EEE").format(new Date());
This should display 'Tuesday':
new SimpleDateFormat("EEEE").format(new Date());
This should display 'T':
new SimpleDateFormat("EEEEE").format(new Date());
So your specific example would be:
new SimpleDateFormat("yyyy-MM-EEE").format(new Date());
It's used to write js codes inside of href
instead of event listeners like onclick
and avoiding #
links in href
to make a
tags valid for HTML.
I had a research on how to use javascript:
inside of href
attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
For windows(7 in my case):
create one some.bat file with content
@echo off
C:\Python36\python.exe -m pip -V
C:\Python36\python.exe -m pip install scipy-0.19.1-cp36-cp36m-win32.whl
C:\Python36\python.exe -m pip list
pause
then run this batch file some.bat
import scipy
Execute Exec DBMS_XDB.SETHTTPPORT(8181);
as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.
Source : http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html
MultiProgramming - In a multiprogramming system, there are more than one programs loaded in main memory which are ready to execute. Only one program at a time is able to get the CPU for executing its instructions while all others are waiting their turn. The main idea of multiprogramming is to maximize the use of CPU time. Suppose currently running process is performing an I/O task, then OS may interrupt that process and give the control to one of the other in - main memory programs that are ready to execute (i.e. process context switching). In this way, no CPU time is wasted by system waiting for the I/O task to be completed.
MultiProcessing - Multiprocessing is the ability of an operating system to execute more than one process simultaneously on a multi processor machine. In multiprocessing system, a computer uses more than one CPU at a tme.
Multitasking - Multitasking is the ability of an operating system to execute more than one task simultaneously on single processor machine, these multiple tasks share common resources such as CPU and memory. In multitasking system, CPU switches from one task to next task so quickly that appears as all tasks are executing at the same time.
There are differences between multitasking and multiprogramming. A task in a multitasking system is not whole application program but it can refres to a "thread of execution" when one process is divided into sub-tasks. Each smaller task does not hijack the CPU until it finishes, they share a small amount of the CPU time called Quantum. Multiprogramming and multitasking operating systems are time sharing systems.
Multithreading - Multithreading is the extension of multitasking. Multithreading is the ability of an operating system to subdivide the specific operation within a single application into individual threads. Each of these threads can run in parallel. The OS divides processing time not only among different applications but also among each thread within an application.
Since I haven't seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict
argument to the function requiring the calling module's globals, and then pass the dict into the function when calling; e.g:
# external_module
def imported_function(global_dict=None):
print(global_dict["a"])
# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())
>>> 12
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
https://github.com/app-z/Json-to-SQLite
At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/
Main method
void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...
Fields name will create dynamically
My two cents on this topic, trying to provide a generic, double conversion method:
private static double ParseDouble(object value)
{
double result;
string doubleAsString = value.ToString();
IEnumerable<char> doubleAsCharList = doubleAsString.ToList();
if (doubleAsCharList.Where(ch => ch == '.' || ch == ',').Count() <= 1)
{
double.TryParse(doubleAsString.Replace(',', '.'),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else
{
if (doubleAsCharList.Where(ch => ch == '.').Count() <= 1
&& doubleAsCharList.Where(ch => ch == ',').Count() > 1)
{
double.TryParse(doubleAsString.Replace(",", string.Empty),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else if (doubleAsCharList.Where(ch => ch == ',').Count() <= 1
&& doubleAsCharList.Where(ch => ch == '.').Count() > 1)
{
double.TryParse(doubleAsString.Replace(".", string.Empty).Replace(',', '.'),
System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture,
out result);
}
else
{
throw new ParsingException($"Error parsing {doubleAsString} as double, try removing thousand separators (if any)");
}
}
return result;
}
Works as expected with:
No default conversion is implemented, so it would fail trying to parse 1.3,14
, 1,3.14
or similar cases.
Using UTL_FILE
instead of DBMS_OUTPUT
will redirect output to a file:
CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
BEGIN
DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS VARCHAR(2))
DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS VARCHAR(2))
DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
RETURN @Time
END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------
This is an old question, nevertheless this topic never ceases to bug me.
As many of the answers here and across the web focus on "enforcing" the interface, I'd like to suggest an alternative view:
I feel the lack of interfaces the most when I'm using multiple classes that behave similarly (i.e. implement an interface).
For example, I have an Email Generator that expects to receive Email Sections Factories, that "know" how to generate the sections' content and HTML. Hence, they all need to have some sort of getContent(id)
and getHtml(content)
methods.
The closest pattern to interfaces (albeit it's still a workaround) I could think of is using a class that'll get 2 arguments, which will define the 2 interface methods.
The main challenge with this pattern is that the methods either have to be static
, or to get as argument the instance itself, in order to access its properties. However there are cases in which I find this trade-off worth the hassle.
class Filterable {_x000D_
constructor(data, { filter, toString }) {_x000D_
this.data = data;_x000D_
this.filter = filter;_x000D_
this.toString = toString;_x000D_
// You can also enforce here an Iterable interface, for example,_x000D_
// which feels much more natural than having an external check_x000D_
}_x000D_
}_x000D_
_x000D_
const evenNumbersList = new Filterable(_x000D_
[1, 2, 3, 4, 5, 6], {_x000D_
filter: (lst) => {_x000D_
const evenElements = lst.data.filter(x => x % 2 === 0);_x000D_
lst.data = evenElements;_x000D_
},_x000D_
toString: lst => `< ${lst.data.toString()} >`,_x000D_
}_x000D_
);_x000D_
_x000D_
console.log('The whole list: ', evenNumbersList.toString(evenNumbersList));_x000D_
evenNumbersList.filter(evenNumbersList);_x000D_
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
_x000D_
This helped for me:
All you need to do, is to specify a envirnoment variable called JAVA_TOOL_OPTIONS. If you set this variable to -Dfile.encoding=UTF8, everytime a JVM is started, it will pick up this information.
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
Try:
.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address
If your worksheet name (strProjectName
) has spaces, you need to include the single quotes in the formula string.
If this does not resolve it, please provide more information about the specific error or failure.
Update
In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:
strProjectName = Replace(strProjectName," ", "_")
But if you're not also pushing that change to the Worksheet.Name
property, you can expect these to happen:
#REF
errorThe reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.
So you need to do:
Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")
Then, your formula should work.
I use an extension to eliminate this problem for me, which may or may not be what you are after.
It goes like this:
public static class Extensions
{
public String TrimString(this object item)
{
return String.Format("{0}", item).Trim();
}
}
This extension does not return null
values! If the item is null
or DBNull.Value, it will return an empty String.
public string GetCustomerNumber(Guid id)
{
var obj =
DBSqlHelperFactory.ExecuteScalar(
connectionStringSplendidmyApp,
CommandType.StoredProcedure,
"GetCustomerNumber",
new SqlParameter("@id", id)
);
return obj.TrimString();
}
These are few things which will help you in understanding everything... using iloc
In iloc, [initial row:ending row, initial column:ending column]
case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:]
this means that you want only the last column...
case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1]
this means that you want all columns and all rows except the last column...
case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:]
this means that you want only the last row...
case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:]
this means that you want all columns and all rows except the last column...
case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1]
this means that you want all columns and all rows except the last column and last row...
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
mkmf
is part of the ruby1.9.1-dev
package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev
package by doing:
sudo apt-get install ruby1.9.1-dev
Then you can install Rails as per normal.
Generally it's easier to just do:
sudo apt-get install ruby-dev
To see how much space each container's log is taking up, use this:
docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl
(you might need a sudo
before ls
).
May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....
By transforming your int array into an Integer one and then using public static <T> void Arrays.sort(T[] a,
Comparator<? super T> c)
(the first step is only needed as I fear autoboxing may bot work on arrays).
You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.
I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.
localStorage.clear()
That'll clear the stored data. Then refresh and things should start to work.
Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper
. When you extend it you will need to implement onCreate
and onUpgrade
method.
When onCreate
and onUpgrade
methods called
onCreate
called when app newly installed.onUpgrade
called when app updated. Organizing Database versions
I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1
class, second version create MigrationV1ToV2
(these are my naming convention)
public interface Migration {
void run(SQLiteDatabase db);//create tables, alter tables
}
Example migration:
public class MigrationV1ToV2 implements Migration{
public void run(SQLiteDatabase db){
//create new tables
//alter existing tables(add column, add/remove constraint)
//etc.
}
}
onCreate
: Since onCreate
will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate
will looks like this:
public void onCreate(SQLiteDatabase db){
Migration mV1=new MigrationV1();
//put your first database schema in this class
mV1.run(db);
Migration mV1ToV2=new MigrationV1ToV2();
mV1ToV2.run(db);
//other migration if any
}
onUpgrade
: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.
For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2
). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2
like this:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
//means old version is 1
Migration migration = new MigrationV1ToV2();
migration.run(db);
}
if (oldVersion < 3) {
//means old version is 2
}
}
Note: All upgrades (mentioned in
onUpgrade
) in to database schema should be executed inonCreate
Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....
what difference does this make?
For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript
method:
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.
But, if instead it was written like this (using the RegisterClientScriptBlock
method):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Focus will not get to the textbox control and a JavaScript error will be generated on the page
The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.
Here is the code that I am using:
Inside WebViewClient:
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progress1).setVisibility(View.GONE);
}
Here is the XML :
<ProgressBar
android:id="@+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Hope this helps..
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
Chrome://chrome/settings/Privacy/Content settings/JavaScript
and there you can PASTE your website's URL in Manage exceptions..
and change the JavaScript priority from ALLOW to BLOCK.
I think this might help you:
Here is the JSFiddle demo:
And here is the code:
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
init: function() {_x000D_
if (arguments.callee.done) return;_x000D_
arguments.callee.done = true;_x000D_
if (_timer) clearInterval(_timer);_x000D_
if (!document.createElement || !document.getElementsByTagName) return;_x000D_
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
forEach(document.getElementsByTagName('table'), function(table) {_x000D_
if (table.className.search(/\bsortable\b/) != -1) {_x000D_
sorttable.makeSortable(table);_x000D_
}_x000D_
});_x000D_
},_x000D_
makeSortable: function(table) {_x000D_
if (table.getElementsByTagName('thead').length == 0) {_x000D_
the = document.createElement('thead');_x000D_
the.appendChild(table.rows[0]);_x000D_
table.insertBefore(the, table.firstChild);_x000D_
}_x000D_
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
if (table.tHead.rows.length != 1) return;_x000D_
sortbottomrows = [];_x000D_
for (var i = 0; i < table.rows.length; i++) {_x000D_
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
}_x000D_
}_x000D_
if (sortbottomrows) {_x000D_
if (table.tFoot == null) {_x000D_
tfo = document.createElement('tfoot');_x000D_
table.appendChild(tfo);_x000D_
}_x000D_
for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
tfo.appendChild(sortbottomrows[i]);_x000D_
}_x000D_
delete sortbottomrows;_x000D_
}_x000D_
headrow = table.tHead.rows[0].cells;_x000D_
for (var i = 0; i < headrow.length; i++) {_x000D_
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
if (mtch) {_x000D_
override = mtch[1];_x000D_
}_x000D_
if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
} else {_x000D_
headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
}_x000D_
headrow[i].sorttable_columnindex = i;_x000D_
headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted',_x000D_
'sorttable_sorted_reverse');_x000D_
this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
sortrevind = document.createElement('span');_x000D_
sortrevind.id = "sorttable_sortrevind";_x000D_
sortrevind.innerHTML = stIsIE ? ' <font face="webdings">5</font>' : ' ▴';_x000D_
this.appendChild(sortrevind);_x000D_
return;_x000D_
}_x000D_
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
sorttable.reverse(this.sorttable_tbody);_x000D_
this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
'sorttable_sorted');_x000D_
this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
return;_x000D_
}_x000D_
theadrow = this.parentNode;_x000D_
forEach(theadrow.childNodes, function(cell) {_x000D_
if (cell.nodeType == 1) {_x000D_
cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
}_x000D_
});_x000D_
sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
if (sortfwdind) {_x000D_
sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
}_x000D_
sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
if (sortrevind) {_x000D_
sortrevind.parentNode.removeChild(sortrevind);_x000D_
}_x000D_
_x000D_
this.className += ' sorttable_sorted';_x000D_
sortfwdind = document.createElement('span');_x000D_
sortfwdind.id = "sorttable_sortfwdind";_x000D_
sortfwdind.innerHTML = stIsIE ? ' <font face="webdings">6</font>' : ' ▾';_x000D_
this.appendChild(sortfwdind);_x000D_
row_array = [];_x000D_
col = this.sorttable_columnindex;_x000D_
rows = this.sorttable_tbody.rows;_x000D_
for (var j = 0; j < rows.length; j++) {_x000D_
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
}_x000D_
row_array.sort(this.sorttable_sortfunction);_x000D_
tb = this.sorttable_tbody;_x000D_
for (var j = 0; j < row_array.length; j++) {_x000D_
tb.appendChild(row_array[j][1]);_x000D_
}_x000D_
delete row_array;_x000D_
});_x000D_
}_x000D_
}_x000D_
},_x000D_
_x000D_
guessType: function(table, column) {_x000D_
sortfn = sorttable.sort_alpha;_x000D_
for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
if (text != '') {_x000D_
if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
return sorttable.sort_numeric;_x000D_
}_x000D_
possdate = text.match(sorttable.DATE_RE)_x000D_
if (possdate) {_x000D_
first = parseInt(possdate[1]);_x000D_
second = parseInt(possdate[2]);_x000D_
if (first > 12) {_x000D_
return sorttable.sort_ddmm;_x000D_
} else if (second > 12) {_x000D_
return sorttable.sort_mmdd;_x000D_
} else {_x000D_
sortfn = sorttable.sort_ddmm;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
return sortfn;_x000D_
},_x000D_
getInnerText: function(node) {_x000D_
if (!node) return "";_x000D_
hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
node.getElementsByTagName('input').length;_x000D_
if (node.getAttribute("sorttable_customkey") != null) {_x000D_
return node.getAttribute("sorttable_customkey");_x000D_
} else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
} else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
return node.text.replace(/^\s+|\s+$/g, '');_x000D_
} else {_x000D_
switch (node.nodeType) {_x000D_
case 3:_x000D_
if (node.nodeName.toLowerCase() == 'input') {_x000D_
return node.value.replace(/^\s+|\s+$/g, '');_x000D_
}_x000D_
case 4:_x000D_
return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
case 1:_x000D_
case 11:_x000D_
var innerText = '';_x000D_
for (var i = 0; i < node.childNodes.length; i++) {_x000D_
innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
}_x000D_
return innerText.replace(/^\s+|\s+$/g, '');_x000D_
break;_x000D_
default:_x000D_
return '';_x000D_
}_x000D_
}_x000D_
},_x000D_
reverse: function(tbody) {_x000D_
// reverse the rows in a tbody_x000D_
newrows = [];_x000D_
for (var i = 0; i < tbody.rows.length; i++) {_x000D_
newrows[newrows.length] = tbody.rows[i];_x000D_
}_x000D_
for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
tbody.appendChild(newrows[i]);_x000D_
}_x000D_
delete newrows;_x000D_
},_x000D_
sort_numeric: function(a, b) {_x000D_
aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(aa)) aa = 0;_x000D_
bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
if (isNaN(bb)) bb = 0;_x000D_
return aa - bb;_x000D_
},_x000D_
sort_alpha: function(a, b) {_x000D_
if (a[0] == b[0]) return 0;_x000D_
if (a[0] < b[0]) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_ddmm: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
m = mtch[2];_x000D_
d = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
sort_mmdd: function(a, b) {_x000D_
mtch = a[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt1 = y + m + d;_x000D_
mtch = b[0].match(sorttable.DATE_RE);_x000D_
y = mtch[3];_x000D_
d = mtch[2];_x000D_
m = mtch[1];_x000D_
if (m.length == 1) m = '0' + m;_x000D_
if (d.length == 1) d = '0' + d;_x000D_
dt2 = y + m + d;_x000D_
if (dt1 == dt2) return 0;_x000D_
if (dt1 < dt2) return -1;_x000D_
return 1;_x000D_
},_x000D_
shaker_sort: function(list, comp_func) {_x000D_
var b = 0;_x000D_
var t = list.length - 1;_x000D_
var swap = true;_x000D_
while (swap) {_x000D_
swap = false;_x000D_
for (var i = b; i < t; ++i) {_x000D_
if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i + 1];_x000D_
list[i + 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
t--;_x000D_
_x000D_
if (!swap) break;_x000D_
_x000D_
for (var i = t; i > b; --i) {_x000D_
if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
var q = list[i];_x000D_
list[i] = list[i - 1];_x000D_
list[i - 1] = q;_x000D_
swap = true;_x000D_
}_x000D_
}_x000D_
b++;_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
var script = document.getElementById("__ie_onload");_x000D_
script.onreadystatechange = function() {_x000D_
if (this.readyState == "complete") {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
};_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
var _timer = setInterval(function() {_x000D_
if (/loaded|complete/.test(document.readyState)) {_x000D_
sorttable.init(); // call the onload handler_x000D_
}_x000D_
}, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
if (element.addEventListener) {_x000D_
element.addEventListener(type, handler, false);_x000D_
} else {_x000D_
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
if (!element.events) element.events = {};_x000D_
var handlers = element.events[type];_x000D_
if (!handlers) {_x000D_
handlers = element.events[type] = {};_x000D_
if (element["on" + type]) {_x000D_
handlers[0] = element["on" + type];_x000D_
}_x000D_
}_x000D_
handlers[handler.$$guid] = handler;_x000D_
element["on" + type] = handleEvent;_x000D_
}_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
if (element.removeEventListener) {_x000D_
element.removeEventListener(type, handler, false);_x000D_
} else {_x000D_
if (element.events && element.events[type]) {_x000D_
delete element.events[type][handler.$$guid];_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
var returnValue = true;_x000D_
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
var handlers = this.events[event.type];_x000D_
for (var i in handlers) {_x000D_
this.$$handleEvent = handlers[i];_x000D_
if (this.$$handleEvent(event) === false) {_x000D_
returnValue = false;_x000D_
}_x000D_
}_x000D_
return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
event.preventDefault = fixEvent.preventDefault;_x000D_
event.stopPropagation = fixEvent.stopPropagation;_x000D_
return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
Array.forEach = function(array, block, context) {_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
block.call(context, array[i], i, array);_x000D_
}_x000D_
};_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
for (var key in object) {_x000D_
if (typeof this.prototype[key] == "undefined") {_x000D_
block.call(context, object[key], key, object);_x000D_
}_x000D_
}_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
Array.forEach(string.split(""), function(chr, index) {_x000D_
block.call(context, chr, index, string);_x000D_
});_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
if (object) {_x000D_
var resolve = Object;_x000D_
if (object instanceof Function) {_x000D_
resolve = Function;_x000D_
} else if (object.forEach instanceof Function) {_x000D_
object.forEach(block, context);_x000D_
return;_x000D_
} else if (typeof object == "string") {_x000D_
resolve = String;_x000D_
} else if (typeof object.length == "number") {_x000D_
resolve = Array;_x000D_
}_x000D_
resolve.forEach(object, block, context);_x000D_
}_x000D_
}
_x000D_
table.sortable thead {_x000D_
background-color: #eee;_x000D_
color: #666666;_x000D_
font-weight: bold;_x000D_
cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>S.L.</th>_x000D_
<th>name</th>_x000D_
<th>Goal</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Ronaldo</td>_x000D_
<td>120</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Messi</td>_x000D_
<td>66</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Ribery</td>_x000D_
<td>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>Bale</td>_x000D_
<td>22</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
JS is used here without any other JQuery Plugin.
Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.
Angular no longer supports --env instead you have to use
ng serve -c dev
for development environment and,
ng serve -c prod
for production.
NOTE: -c
or --configuration
On heroku server (readonly filesystem), If you want runtime compilation of css (its not recommended but you can do it), make sure you have done settings like below -
# inside config/application.rb
config.assets.enabled = true
config.assets.prefix = Rails.root.join('tmp/assets').to_s
# If you are using sass then keep gem outside of asset group
gem 'sass-rails', '3.1.4'
# inside config/environments/production.rb
config.assets.compile = true
For Swift:
self.tableView.tableFooterView = UIView(frame: CGRectZero)
For newest Swift:
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
hoat4's solution is very elegant and simple. It works for all sane ini files. However, I have seen many that have un-escaped space characters in the key.
To solve this, I have downloaded and modified a copy of java.util.Properties
. Though this is a little unorthodox, and short-term, the actual mods were but a few lines and quite simple. I will be puting forward a proposal to the JDK community to include the changes.
By adding an internal class variable:
private boolean _spaceCharOn = false;
I control the processing related to scanning for the key/value separation point.
I replaced the space characters search code with a small private method that returns a boolean depending on the state of the above variable.
private boolean isSpaceSeparator(char c) {
if (_spaceCharOn) {
return (c == ' ' || c == '\t' || c == '\f');
} else {
return (c == '\t' || c == '\f');
}
}
This method is used in two places within the private method load0(...)
.
There is also a public method to switch it on, but it would be better to use the original version of Properties
if the space separator is not an issue for your application.
If there is interest, I would be willing to post the code to my IniFile.java
file. It works with either version of Properties
.