I don't know why that doesn't work, but this one is logically equivalent and it does work:
-(myField:superneat AND -myOtherField:somethingElse)
Maybe it has something to do with defining the same field twice in the query...
Try asking in the solr-user group, then post back here the final answer!
elaborating on the above answers for server deployment.
$hostname = gethostname();
if($hostname=="mydevpc")
{
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
should do the trick for development environment without compromising the server when deployed.
You should map it to FLOAT(53)- that's what LINQ to SQL does.
Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):
select *
from calls c join users u
on c.assigned_to = u.user_id
or c.requestor_id = u.user_id
where u.dept = 4
This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.
Without using regex:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
In short:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the real property values.
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.
You can also use this code with support for loading error:
$("img").on('load', function() {
// do stuff on success
})
.on('error', function() {
// do stuff on smth wrong (error 404, etc.)
})
.each(function() {
if(this.complete) {
$(this).load();
} else if(this.error) {
$(this).error();
}
});
In C language, character literal is not a char
type. C considers character literal as integer. So, there is no difference between sizeof('a')
and sizeof(1)
.
So, the sizeof character literal is equal to sizeof integer in C.
In C++ language, character literal is type of char
. The cppreference say's:
1) narrow character literal or ordinary character literal, e.g.
'a'
or'\n'
or'\13'
. Such literal has typechar
and the value equal to the representation of c-char in the execution character set. If c-char is not representable as a single byte in the execution character set, the literal has type int and implementation-defined value.
So, in C++ character literal is a type of char
. so, size of character literal in C++ is one byte.
Alos, In your programs, you have used wrong format specifier for sizeof
operator.
C11 §7.21.6.1 (P9) :
If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, you should use %zu
format specifier instead of %d
, otherwise it is undefined behaviour in C.
Here is another. We had a need to provide friendly names for our EnumValues. We used the System.ComponentModel.DescriptionAttribute to show a custom string value for each enum value.
public static class StaticClass
{
public static string GetEnumDescription(Enum currentEnum)
{
string description = String.Empty;
DescriptionAttribute da;
FieldInfo fi = currentEnum.GetType().
GetField(currentEnum.ToString());
da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
typeof(DescriptionAttribute));
if (da != null)
description = da.Description;
else
description = currentEnum.ToString();
return description;
}
public static List<string> GetEnumFormattedNames<TEnum>()
{
var enumType = typeof(TEnum);
if (enumType == typeof(Enum))
throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");
if (!(enumType.IsEnum))
throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");
List<string> formattedNames = new List<string>();
var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();
foreach (TEnum item in list)
{
formattedNames.Add(GetEnumDescription(item as Enum));
}
return formattedNames;
}
}
In Use
public enum TestEnum
{
[Description("Something 1")]
Dr = 0,
[Description("Something 2")]
Mr = 1
}
static void Main(string[] args)
{
var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
}
This will end returning "Something 1", "Something 2"
The query component is indicated by the first ?
in a URI. "Query string" might be a synonym (this term is not used in the URI standard).
Some examples for HTTP URIs with query components:
http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b
(list of allowed characters in the query component)
The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b
.
Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.
Example URI with parameters in the path, the query, and the fragment:
http://example.com/foo;key1=value1?key2=value2#key3=value3
¹ The URI standard says about the query component:
[…] query components are often used to carry identifying information in the form of "key=value" pairs […]
² The URI standard says about the path component:
[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.
You can use jconsole (standard with most JDKs) to check heap sizes of any java process.
Similar to @James answer, a more pythonic way can be:
fields = map(lambda x:x[0], cursor.description)
result = [dict(zip(fields,row)) for row in cursor.fetchall()]
You can get a single column with map over the result:
extensions = map(lambda x: x['ext'], result)
or filter results:
filter(lambda x: x['filesize'] > 1024 and x['filesize'] < 4096, result)
or accumulate values for filtered columns:
totalTxtSize = reduce(
lambda x,y: x+y,
filter(lambda x: x['ext'].lower() == 'txt', result)
)
The DictWriter()
class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer()
and pass in a simple row for the header:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Date", "temperature 1", "Temperature 2"])
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row + [0.0] for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)
The alternative would be to generate dictionaries when copying across your data:
import csv
with open('combined_file.csv', 'w', newline='') as outcsv:
writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
writer.writeheader()
with open('t1.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)
with open('t2.csv', 'r', newline='') as incsv:
reader = csv.reader(incsv)
writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)
You need to set the correct content type and stringify your object.
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "Ajax.ashx",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert(msg);
}
});
here and now in 2018
using var
for variable declaration is synonymous with public
as in
class Sample{
var $usingVar;
public $usingPublic;
function .....
}
The simplest way is css transform:
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
DEMO: http://codepen.io/candid/pen/dGPZvR
This way also works with dynamically sized background images for the logo and allows us to utilize the text-hide class:
CSS:
.navbar-brand {
background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
transform: translateX(-50%);
left: 50%;
position: absolute;
width: 200px; /* no height needed ... image will resize automagically */
}
HTML:
<a class="navbar-brand text-hide" href="http://disputebills.com">Brand Text
</a>
We can also use flexbox though. However, using this method we'd have to move navbar-brand
outside of navbar-header
. This way is great though because we can now have image and text side by side:
.brand-centered {
display: flex;
justify-content: center;
position: absolute;
width: 100%;
left: 0;
top: 0;
}
.navbar-brand {
display: flex;
align-items: center;
}
Demo: http://codepen.io/candid/pen/yeLZax
To only achieve these results on mobile simply wrap the above css inside a media query:
@media (max-width: 768px) {
}
Here is an at-length description of the behaviour of various browsers http://unixpapa.com/js/key.html
// use `/ 1048576` to get ram in MB
// and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB
private static String getRAMsize()
{
ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject item in moc)
{
return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value) / 1048576, 0)) + " MB";
}
return "RAMsize";
}
In case you don't have access to functools.partial
, you could use a wrapper function for this, as well.
def target(lock):
def wrapped_func(items):
for item in items:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
return wrapped_func
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
lck = multiprocessing.Lock()
pool.map(target(lck), iterable)
pool.close()
pool.join()
This makes target()
into a function that accepts a lock (or whatever parameters you want to give), and it will return a function that only takes in an iterable as input, but can still use all your other parameters. That's what is ultimately passed in to pool.map()
, which then should execute with no problems.
docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage image_id
_x000D_
Below is ouput of dfimage command:
$ dfimage 0f1947a021ce
FROM node:8
WORKDIR /usr/src/app
COPY file:e76d2e84545dedbe901b7b7b0c8d2c9733baa07cc821054efec48f623e29218c in ./
RUN /bin/sh -c npm install
COPY dir:a89a4894689a38cbf3895fdc0870878272bb9e09268149a87a6974a274b2184a in .
EXPOSE 8080
CMD ["npm" "start"]
Building on the answer from Sharfi, edit the /etc/my.cnf file and add just this one line:
validate_password_policy=LOW
That should sufficiently neuter the validation as requested by the OP. You will probably want to restart mysqld after this change. Depending on your OS, it would look something like:
sudo service mysqld restart
validate_password_policy takes either values 0, 1, or 2 or words LOW, MEDIUM, and STRONG which correspond to those numbers. The default is MEDIUM (1) which requires passwords contain at least one upper case letter, one lower case letter, one digit, and one special character, and that the total password length is at least 8 characters. Changing to LOW as I suggest here then only will check for length, which if it hasn't been changed through other parameters will check for a length of 8. If you wanted to shorten that length limit too, you could also add validate_password_length in to the my.cnf file.
For more info about the levels and details, see the mysql doc.
For MySQL 8, the property has changed from "validate_password_policy" to "validate_password.policy". See the updated mysql doc for the latest info.
protected void btnExportExcel_Click(object sender, EventArgs e)
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
ExportDataTableToExcel(_datatable);
}
My solution in code behind was:
System.Web.UI.WebControls.FileUpload fileUpload;
I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
Simple short answer is this:
xcopy /Y /I "$(SolutionDir)<my-src-path>" "$(SolutionDir)<my-dst-path>\"
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
This solutions working for me,
let params = new HttpParams();
Object.keys(data).forEach(p => {
params = params.append(p.toString(), data[p].toString());
});
size_t
is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)
The sizeof
operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. The value of the result is implementation-de?ned, and
its type (an unsigned integer type) is size_t
(ISO C99 Section 6.5.3.4.)
On windows 10 run cmd.exe with admin rights then type :
1) cd \Python27\scripts
2) pip install requests
It should work. My case was with python 2.7
I just wrote this helper function. Put it in App_Code/JS.cshtml
:
@using System.Web.Script.Serialization
@helper Encode(object obj)
{
@(new HtmlString(new JavaScriptSerializer().Serialize(obj)));
}
Then in your example, you can do something like this:
var title = @JS.Encode(Model.Title);
Notice how I don't put quotes around it. If the title already contains quotes, it won't explode. Seems to handle dictionaries and anonymous objects nicely too!
Instead of initializing another new Intent to receive the data, just do this:
String id = getIntent().getStringExtra("id");
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
You can use Gson for this.
GSON
is a Java library that can be used to convert Java Objects into their JSON
representation. It can also be used to convert a JSON
string to an equivalent Java object.
Take a look of this Converting JSON to Java
You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable()
:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
I was struggling to figure it out how to put a div over an image like this:
No matter how I configured z-index in both divs (the image wrapper) and the section I was getting this:
Turns out I hadn't set up the background of the section to be background: white;
so basically it's like this:
<div class="img-wrp">
<img src="myimage.svg"/>
</div>
<section>
<other content>
</section>
section{
position: relative;
background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */
}
.img-wrp{
position: absolute;
z-index: -1; /* also worked with 0 but just to be sure */
}
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
Where it is documented:
From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"
collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!
The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,
Class Dog
has_many :tags
belongs_to :person
end
Class Person
has_many :dogs
end
d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")
or even
t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")
You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)
How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)
There are 2 different places you can set it:
php.ini
post_max_size=20M
upload_max_filesize=20M
.htaccess / httpd.conf / virtualhost include
php_value post_max_size 20M
php_value upload_max_filesize 20M
Which one to use depends on what you have access to.
.htaccess will not require a server restart, but php.ini and the other apache conf files will.
You can use regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
I'm not sure but in this case you can still go with a complete customized AlertDialog by having a seperate layout file set in the alert dialog and set the animation for your imageview using part of your above code that should also do it!
I've seen only one simple way of reading an arbitrarily long string, but I've never used it. I think it goes like this:
char *m = NULL;
printf("please input a string\n");
scanf("%ms",&m);
if (m == NULL)
fprintf(stderr, "That string was too long!\n");
else
{
printf("this is the string %s\n",m);
/* ... any other use of m */
free(m);
}
The m
between %
and s
tells scanf()
to measure the string and allocate memory for it and copy the string into that, and to store the address of that allocated memory in the corresponding argument. Once you're done with it you have to free()
it.
This isn't supported on every implementation of scanf()
, though.
As others have pointed out, the easiest solution is to set a limit on the length of the input. If you still want to use scanf()
then you can do so this way:
char m[100];
scanf("%99s",&m);
Note that the size of m[]
must be at least one byte larger than the number between %
and s
.
If the string entered is longer than 99, then the remaining characters will wait to be read by another call or by the rest of the format string passed to scanf()
.
Generally scanf()
is not recommended for handling user input. It's best applied to basic structured text files that were created by another application. Even then, you must be aware that the input might not be formatted as you expect, as somebody might have interfered with it to try to break your program.
In C# Core DataSource does not exist, but this work fine:
listbox.ItemsSource = null;
listbox.Items.Clear();
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
<?php
$smarty = new Smarty;
$smarty->assign('test', "This is a \n Test");
$smarty->display('index.tpl');
?>
In index.tpl
{$test|nl2br}
In HTML
This is a<br />
test
Why does it take three branches/merges for every task? Can you explain more about that?
If you use a bug tracking system you can use the bug number as part of the branch name. This will keep the branch names unique, and you can prefix them with a short and descriptive word or two to keep them human readable, like "ResizeWindow-43523"
. It also helps make things easier when you go to clean up branches, since you can look up the associated bug. This is how I usually name my branches.
Since these branches are eventually getting merged back into master, you should be safe deleting them after you merge. Unless you're merging with --squash
, the entire history of the branch will still exist should you ever need it.
I think you should tranfer image in base64 to image with blob, because when you use base64 image, it take a lot of log lines or a lot of line will send to server. With blob, it only the file. You can use this code bellow:
dataURLtoBlob = (dataURL) ->
# Decode the dataURL
binary = atob(dataURL.split(',')[1])
# Create 8-bit unsigned array
array = []
i = 0
while i < binary.length
array.push binary.charCodeAt(i)
i++
# Return our Blob object
new Blob([ new Uint8Array(array) ], type: 'image/png')
And canvas code here:
canvas = document.getElementById('canvas')
file = dataURLtoBlob(canvas.toDataURL())
After that you can use ajax with Form:
fd = new FormData
# Append our Canvas image file to the form data
fd.append 'image', file
$.ajax
type: 'POST'
url: '/url-to-save'
data: fd
processData: false
contentType: false
This code using CoffeeScript syntax.
if you want to use javascript, please paste the code to http://js2.coffee
TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem();
tempItem = (TreeViewItem) treeView1.Items.GetItemAt(0); // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0); // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString(); // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true; // will expand the first node
Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:
NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.
Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:
export NLS_LANG=AMERICAN_AMERICA.UTF8
Oracle gets a big fat F for usability.
Use ClipRRect with set image property of fit: BoxFit.fill
ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Image(
fit: BoxFit.fill,
image: AssetImage('images/image.png'),
width: 100.0,
height: 100.0,
),
),
I know it is a bit late to answer this question, but it is the first entry in google, so I think it is worth to answer it.
The problem is not a coding problem, it is an architecture problem.
You have created an interface class Event: public Item
to define the methods which all events should implement. Then you have defined two types of events which inherits from class Event: public Item
; Arrival and Landing and then, you have added a method Landing* createNewLanding(Arrival* arrival);
from the landing functionality in the class Event: public Item
interface. You should move this method to the class Landing: public Event
class because it only has sense for a landing. class Landing: public Event
and class Arrival: public Event
class should know class Event: public Item
but event should not know class Landing: public Event
nor class Arrival: public Event
.
I hope this helps, regards, Alberto
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
I figured out that this behaves like a mousedown event:
button:active:hover {}
Klaus solution has less overhead, on the other hand this one may be more readable
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(myDict, lookup):
for key, value in myDict.items():
for v in value:
if lookup in v:
return key
search(myDict, 'Mary')
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
On Ubuntu 14.04 none of these suggestions worked. Postfix would override with the logged in system user as the sender. What worked was the following solution listed at this link --> Change outgoing mail address from root@servername - rackspace sendgrid postfix
STEPS:
1) Make sure this is set in /etc/postfix/main.cf:
smtp_generic_maps = hash:/etc/postfix/generic
2) echo 'www-data [email protected]' >> /etc/postfix/generic
3) sudo postmap /etc/postfix/generic
4) sudo service postfix restart
moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))
has to format and then convert to moment again.
For those who struggle with this:
const value = $('SELECTOR').iCheck('update')[0].checked;
This directly returns true
or false
as boolean
.
You must use some of the C # conversion systems:
string to boolean: True to true
string str = "True";
bool mybool = System.Convert.ToBoolean(str);
boolean to string: true to True
bool mybool = true;
string str = System.Convert.ToString(mybool);
//or
string str = mybool.ToString();
bool.Parse
expects one parameter which in this case is str, even .
Convert.ToBoolean
expects one parameter.
bool.TryParse
expects two parameters, one entry (str) and one out (result).
If TryParse
is true, then the conversion was correct, otherwise an error occurred
string str = "True";
bool MyBool = bool.Parse(str);
//Or
string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
The following should work. The lambda function filter out the duplicated words.
inputs=[]
input = raw_input("Word: ").strip()
while input:
inputs.append(input)
input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
Mike Schilling's solution with error handling with a shortcut for the error event handler.
function copyFile(source, target, cb) {
var cbCalled = false;
var rd = fs.createReadStream(source);
rd.on("error", done);
var wr = fs.createWriteStream(target);
wr.on("error", done);
wr.on("close", function(ex) {
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}
Instructions for Drupal 8 / FontAwesome 5
Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)
Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
}
?>
Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.
Make sure you import FontAwesome, add this at the top of the CSS file
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
then add this in the CSS
input#edit-submit {
font-family: 'Font Awesome\ 5 Free';
background-color: transparent;
border: 0;
}
FLUSH ALL CACHES AND IT SHOULD WORK FINE
Add Google Font Effects
If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
$form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>
I had the same error but I had the CommonModule imported. Instead I left a comma where it shouldn't be because of copy/paste when splitting a module:
@NgModule({
declarations: [
ShopComponent,
ShoppingEditComponent
],
imports: [
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: 'shop', component: ShopComponent }, <--- offensive comma
])
]
})
Use this to solve your problem:
<context:annotation-config/>
Type npm list graceful-fs
and you will see which versions of graceful-fs are currently installed.
In my case I got:
npm list graceful-fs
@request/[email protected] /projects/request/promise-core
+-- [email protected]
| `-- [email protected]
| +-- [email protected]
| | `-- [email protected]
| | `-- [email protected]
| | `-- [email protected]
| | `-- [email protected] <==== !!!
| `-- [email protected]
`-- [email protected]
+-- [email protected]
| `-- [email protected]
| `-- [email protected]
| `-- [email protected]
| `-- [email protected]
`-- [email protected]
`-- [email protected]
`-- [email protected]
As you can see gulp
deep down depends on a very old version. Unfortunately, I can't update that myself using npm update graceful-fs
. gulp
would need to update their dependencies. So if you have a case like this you are out of luck. But you may open an issue for the project with the old dependency - i.e. gulp
.
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
div.box {_x000D_
background: #EEE;_x000D_
height: 100px;_x000D_
width: 500px;_x000D_
}_x000D_
div.left {_x000D_
background: #999;_x000D_
float: left;_x000D_
height: 100%;_x000D_
width: auto;_x000D_
}_x000D_
div.right {_x000D_
background: #666;_x000D_
height: 100%;_x000D_
}_x000D_
div.clear {_x000D_
clear: both;_x000D_
height: 1px;_x000D_
overflow: hidden;_x000D_
font-size: 0pt;_x000D_
margin-top: -1px;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="box">_x000D_
<div class="left">Tree</div>_x000D_
<div class="right">View</div>_x000D_
<div class="right">View</div>_x000D_
<div style="width: <=100% getTreeWidth()100 %>">Tree</div>_x000D_
<div class="clear" />_x000D_
</div>_x000D_
<div class="ColumnWrapper">_x000D_
<div class="ColumnOneHalf">Tree</div>_x000D_
<div class="ColumnOneHalf">View</div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You can do it like this also:
HTML
<body>
<div id="wrapper_1">
<div id="container_1"></div>
</div>
</body>
CSS
body { width: 100%; margin: 0; padding: 0; overflow: hidden; }
#wrapper_1 { clear: left; float: left; position: relative; left: 50%; }
#container_1 { display: block; float: left; position: relative; right: 50%; }
As Artem Russakovskii mentioned also, read the original article by Mattew James Taylor for full description.
The Range object has both width and height properties, which are measured in points.
Try to profile Netbeans using VisualVM. If the "hot spot" is org.gnome.accessibility.atkwrapper.emitsignal(), try to run Netbeans with
-J-Djavax.accessibility.assistive_technologies=" "
It helped a lot in my case.
I don't really know why exactly this toolkit used, but looks like it's generally safe to disable it.
In generally, java gets installed at /usr/lib/jvm . That is where my sun jdk is installed. check if it is same for open jdk also.
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
In 2014 I still think my point holds:
IMHO, this discussion got blown out of proportion quite a bit. Quoting the aforementioned blog post:
Most JavaScript utility libraries, such as Underscore, Valentine, and wu, rely on the “native-first dual approach.” This approach prefers native implementations, falling back to vanilla JavaScript only if the native equivalent is not supported. But jsPerf revealed an interesting trend: the most efficient way to iterate over an array or array-like collection is to avoid the native implementations entirely, opting for simple loops instead.
As if "simple loops" and "vanilla Javascript" are more native than Array or Object method implementations. Jeez ...
It certainly would be nice to have a single source of truth, but there isn't. Even if you've been told otherwise, there is no Vanilla God, my dear. I'm sorry. The only assumption that really holds is that we are all writing JavaScript code that aims at performing well in all major browsers, knowing that all of them have different implementations of the same things. It's a bitch to cope with, to put it mildly. But that's the premise, whether you like it or not.
Maybe all of you are working on large scale projects that need twitterish performance so that you really see the difference between 850,000 (Underscore.js) vs. 2,500,000 (Lodash) iterations over a list per second right now!
I for one am not. I mean, I worked on projects where I had to address performance issues, but they were never solved or caused by neither Underscore.js nor Lodash. And unless I get hold of the real differences in implementation and performance (we're talking C++ right now) of, let’s say, a loop over an iterable (object or array, sparse or not!), I rather don't get bothered with any claims based on the results of a benchmark platform that is already opinionated.
It only needs one single update of, let’s say, Rhino to set its Array method implementations on fire in a fashion that not a single "medieval loop methods perform better and forever and whatnot" priest can argue his/her way around the simple fact that all of a sudden array methods in Firefox are much faster than his/her opinionated brainfuck. Man, you just can't cheat your runtime environment by cheating your runtime environment! Think about that when promoting ...
your utility belt
... next time.
So to keep it relevant:
Choose whatever approach fits your needs the most. As usual. I'd prefer fallbacks on actual implementations over opinionated runtime cheats anytime, but even that seems to be a matter of taste nowadays. Stick to quality resources like http://developer.mozilla.com and http://caniuse.com and you'll be just fine.
I prefer ANSI timestamp literals:
insert into the_table
(the_timestamp_column)
values
(timestamp '2017-10-12 21:22:23');
More details in the manual: https://docs.oracle.com/database/121/SQLRF/sql_elements003.htm#SQLRF51062
The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at http://www1.cs.columbia.edu/~db2501/ssmtplib.py)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.
Similarly, you can create an array reference variable like so:
int arr1[] = {1, 2, 3, 4, 5};
int(&arr2)[5] = arr1;
A SELECT INTO
statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found
exception. If it returns more than 1 row, you'll get a too_many_rows
exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO
statement here.
Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID
column in both tables)
BEGIN
FOR rec IN (SELECT EMPLOYEE.EMPID,
EMPLOYEE.ENAME,
EMPLOYEE.DESIGNATION,
EMPLOYEE.SALARY,
DEPARTMENT.DEPT_NAME
FROM EMPLOYEE,
DEPARTMENT
WHERE employee.departmentID = department.departmentID
AND EMPLOYEE.SALARY > 3000)
LOOP
DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
END LOOP;
END;
I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output
like this and would not depend on anyone seeing data that you write to the dbms_output
buffer.
The reason you are getting this error is that you have a vector
.
If you want to use the $
operator, you simply need to convert it to a data.frame
. But since you only have one row in this particular case, you would also need to transpose it; otherwise bob
and ed
will become your row names instead of your column names which is what I think you want.
x <- c(1, 2)
x
names(x) <- c("bob", "ed")
x <- as.data.frame(t(x))
x$ed
[1] 2
This worked great I just add the -a option to ping to resolve the hostname. Thanks https://stackoverflow.com/users/4447323/wombat
@echo off setlocal enabledelayedexpansion set OUTPUT_FILE=result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -n 1 -a %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
Try df['quantity'] = df['quantity'] * -1
.
AppCompatActivity
At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity
if you are using an App Bar.
This is the rational given:
Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.
For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.
The general directions for adding a ToolBar are
AppCompatActivity
NoActionBar
.ToolBar
to each activity's xml layout.ToolBar
in each activity's onCreate
.See the documentation directions for more details. They are quite clear and helpful.
WPF4
<DataGrid AutoGenerateColumns="True" Grid.Column="0" Grid.Row="0"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto">
</DataGrid>
with : <ColumnDefinition Width="350" />
& <RowDefinition Height="300" />
works fine.
Scrollbars don't show with <ColumnDefinition Width="Auto" />
& <RowDefinition Height="300" />
.
Also works fine with: <ColumnDefinition Width="*" />
& <RowDefinition Height="300" />
in the case where this is nested within an outer <Grid>
.
Just replace -H
with -h
. Check man grep
for more details on options
find . -name '*.bar' -exec grep -hn FOO {} \;
Make column B in sheet1 the dates but where the day of the month is always the first day of the month, e.g. in B2 put =DATE(YEAR(A2),MONTH(A2),1). Then make E5 on sheet 2 contain the first date of the month you need, e.g. Date(2013,4,1). After that, putting in F5 COUNTIF(Sheet1!B2:B50, E5) will give you the count for the month specified in E5.
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...
I don't know if this is new functionality, but this will plot on separate figures:
df.plot(y='korisnika')
df.plot(y='osiguranika')
while this will plot on the same figure: (just like the code in the op)
df.plot(y=['korisnika','osiguranika'])
I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
Here you can do it by using HttpRequest
or HttpSession
. And think your problem is within the JSP.
If you are going to use the inside servlet do following,
Object obj = new Object();
session.setAttribute("object", obj);
or
HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);
and after setting your attribute by using request or session, use following to access it in the JSP,
<%= request.getAttribute("object")%>
or
<%= session.getAttribute("object")%>
So seems your problem is in the JSP.
If you want use scriptlets it should be as follows,
<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>
Or can use expressions as follows,
<%= session.getAttribute("object")%>
or can use EL as follows,
${object}
or ${sessionScope.object}
You can check it by two methods
A)By converting the array into string and then check the required string by .contains method
String a=Arrays.toString(VALUES);
System.out.println(a.contains("AB"));
System.out.println(a.contains("BC"));
System.out.println(a.contains("CD"));
System.out.println(a.contains("AE"));
B)this is a more efficent method
Scanner s=new Scanner(System.in);
String u=s.next();
boolean d=true;
for(int i=0;i<VAL.length;i++)
{
if(VAL[i].equals(u)==d)
System.out.println(VAL[i] +" "+u+VAL[i].equals(u));
}
The easiest/best supported method is to use <table cellspacing="10">
The css way: border-spacing (not supported by IE I don't think)
<!-- works in firefox, opera, safari, chrome -->_x000D_
<style type="text/css">_x000D_
_x000D_
table.foobar {_x000D_
border: solid black 1px;_x000D_
border-spacing: 10px;_x000D_
}_x000D_
table.foobar td {_x000D_
border: solid black 1px;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<table class="foobar" cellpadding="0" cellspacing="0">_x000D_
<tr><td>foo</td><td>bar</td></tr>_x000D_
</table>
_x000D_
Edit: if you just want to pad the cell content, and not space them you can simply use
<table cellpadding="10">
OR
td {
padding: 10px;
}
For personal usage, I add a vim plugin like Vrapper to Eclipse and just use yy
to copy entire line.
Code Snippet
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Excel.Application excelApp = null;
private void button1_Click(object sender, EventArgs e)
{
excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
}
private void Form1_Load(object sender, EventArgs e)
{
excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
}
}
Thanks
So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\
. However, they were never registered in the GAC.
I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies
to C:\windows\assembly
and the application worked on that problem machine. You could also do this programmatically with Gacutil.
So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Do a git status
to find out if your file is actually in your index or the commit.
It is easy as a beginner to misunderstand the index/staging area.
I view it as a 'progress pinboard'. I therefore have to add
the file to the pinboard before I can commit
it (i.e. a copy of the complete pinboard), I have to update the pinboard when required, and I also have to deliberately remove files from it when I've finished with them - simply creating, editing or deleting a file doesn't affect the pinboard. It's like 'storyboarding'.
Edit: As others noted, You should do the edits locally and then push the updated repo, rather than attempt to edit directly on github.
Be careful with your tests. If you in your form you put the same email as the email address which must receive it will be directly in spam :)
I'm coming late in the game but I tried all of the solutions above! couldn't get it to drop the zero's in the parameter and give me a default (it ignored the formatting or appeared blank). I was using SSRS 2005 so was struggling with its clunky / buggy issues.
My workaround was to add a column to the custom [DimDate] table in my database that I was pulling dates from. I added a column that was a string representation in the desired format of the [date] column. I then created 2 new Datasets in SSRS that pulled in the following queries for 2 defaults for my 'To' & 'From' date defaults -
'from'
SELECT Datestring
FROM dbo.dimDate
WHERE [date] = ( SELECT MAX(date)
FROM dbo.dimdate
WHERE date < DATEADD(month, -3, GETDATE()
)
'to'
SELECT Datestring
FROM dbo.dimDate
WHERE [date] = ( SELECT MAX(date)
FROM dbo.dimdate
WHERE date <= GETDATE()
)
Trying to "transfer an amount larger than my bitcoin balance" is not an unexpected error. You could use Popen.communicate()
directly instead of check_output()
to avoid raising an exception unnecessarily:
from subprocess import Popen, PIPE
p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE)
output = p.communicate()[0]
if p.returncode != 0:
print("bitcoin failed %d %s" % (p.returncode, output))
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
in fact there exists one trick:
create view view_test as
select
*
from
table
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)
... in sql-query:
set context_info 2
select * from view_test
will be the same with
select * from table where id = 2
but using udf is more acceptable
To find the index of a character in a given sting, you can use this code:
package stringmethodindexof;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
* @author ASUS//VERY VERY IMPORTANT
*/
public class StringMethodIndexOf {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String email;
String any;
//char any;
//any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER").charAt(0);
//THE AVOBE LINE IS FOR CHARACTER INPUT LOL
//System.out.println("Enter any character or string to find out its INDEX NUMBER");
//Scanner r=new Scanner(System.in);
// any=r.nextChar();
email = JOptionPane.showInputDialog(null,"Enter any string or anything you want:");
any=JOptionPane.showInputDialog(null,"Enter any character or string to find out its INDEX NUMBER");
int result;
result=email.indexOf(any);
JOptionPane.showMessageDialog(null, result);
}
}
You are setting it't type
as submit
. That means that browser should post your <form>
data to the server.
In fact a tag has no type attribute according to w3schools.
So remote type
attribute and it should work for you.
If you want to use a phenomenical (with a formula in it) blank cell to make an arithmetic/mathematical operation, all you have to do is use this formula:
=N(C1)
assuming C1 is a "blank" cell
It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
Anything running on the client can be decompiled and cracked. Obfusification just makes it harder. I don't know your application, but 99% of the time I just don't think it's worth the effort.
Here is the code
<input type="button" value="Back" onclick="window.history.back()" />
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth
cookie from JavaScript, as it is marked as HttpOnly
. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).
For Javascript Classes in ES6 you can use object.constructor
. In the example class below the getClass()
method returns the ES6 class as you would expect:
var Cat = class {
meow() {
console.log("meow!");
}
getClass() {
return this.constructor;
}
}
var fluffy = new Cat();
...
var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();
ruffles.meow(); // "meow!"
If you instantiate the class from the getClass
method make sure you wrap it in brackets e.g. ruffles = new ( fluffy.getClass() )( args... );
Use []
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
From http://docs.python.org/tutorial/datastructures.html:
"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."
Tried to specify dll path in different ways (proposed by @markm), but nothing has worked for me. Fixed the problem by copying dll into script folder. It's not a good solution, but ok for my purposes.
You better use disabled for your inputs, in order to prevent auto-completion.
<input type="password" ... disabled />
You can actually handle all of this with just a simple template tag. See http://jsfiddle.net/m4ve9/ for an example. Note that I actually didn't need a compile or link property on the super-directive definition.
During the compilation process, Angular pulls in the template values before compiling, so you can attach any further directives there and Angular will take care of it for you.
If this is a super directive that needs to preserve the original internal content, you can use transclude : true
and replace the inside with <ng-transclude></ng-transclude>
Hope that helps, let me know if anything is unclear
Alex
Here's my simple vanilla JavaScript code:
let a = 'one,two,"three, but with a comma",four,"five, with ""quotes"" in it.."'
console.log(splitQuotes(a))
function splitQuotes(line) {
if(line.indexOf('"') < 0)
return line.split(',')
let result = [], cell = '', quote = false;
for(let i = 0; i < line.length; i++) {
char = line[i]
if(char == '"' && line[i+1] == '"') {
cell += char
i++
} else if(char == '"') {
quote = !quote;
} else if(!quote && char == ',') {
result.push(cell)
cell = ''
} else {
cell += char
}
if ( i == line.length-1 && cell) {
result.push(cell)
}
}
return result
}
update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')
and you do it in a single pass.
If you came here because you were looking for a simple way to browse any VOLUME
:
docker volume list
docker run -it --rm --mount source=[NAME OF VOLUME],target=/volume busybox
cd /volume
to enter the volume.I thought I would provide a much more robust example, also in typescript, but it would be easy to convert to pure javascript. This function will query parents using either the ID like so "#my-element" or the class ".my-class" and unlike some of these answers will handle multiple classes. I found I named some similarly and so the examples above were finding the wrong things.
function queryParentElement(el:HTMLElement | null, selector:string) {
let isIDSelector = selector.indexOf("#") === 0
if (selector.indexOf('.') === 0 || selector.indexOf('#') === 0) {
selector = selector.slice(1)
}
while (el) {
if (isIDSelector) {
if (el.id === selector) {
return el
}
}
else if (el.classList.contains(selector)) {
return el;
}
el = el.parentElement;
}
return null;
}
let elementByClassName = queryParentElement(someElement,".my-class")
let elementByID = queryParentElement(someElement,"#my-element")
setUserVisibleHint(boolean visible) is now deprecated So this is the correct solution
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
In ViewPager2 and ViewPager from version androidx.fragment:fragment:1.1.0
you can just use onPause()
and onResume()
to determine which fragment is currently visible for the user. onResume()
is called when the fragment became visible and onPause
when it stops to be visible.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as the second argument of the FragmentPagerAdapter
constructor.
Hope this useful for you.
$(document).click(function(e){
if ($('#news_gallery').on('clicked')) {
var article = $('#news-article .news-article');
}
});
For Django 2
and python 3
install psycopg2
using pip3
:
pip3 install psycopg2
The level of version information given out by an Apache server can be configured by the ServerTokens setting in its configuration.
I believe there is also a setting that controls whether the version appears in server error pages, although I can't remember what it is off the top of my head. If you don't have direct access to the server, and the server administrator is competent and doesn't want you to know the version they're running... I think you may be SOL.
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
android.os.Build.VERSION.SDK_INT
Here you can find the possible values: VERSION_CODES
.
I've used gFTP for that.
Another option is :
View > Quick Switch Scheme > Keymap > Eclipse
Example with no parameters:
delegate void NewEventHandler();
public event NewEventHandler OnEventHappens;
And from another class, you can subscribe to
otherClass.OnEventHappens += ExecuteThisFunctionWhenEventHappens;
And declare that function with no parameters.
No expensive forks, no pipes, no bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
But beware of globbing.
4 years later, ES6 way simpler version.
function getCookie(name) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [k,v] = el.split('=');
cookie[k.trim()] = v;
})
return cookie[name];
}
I have also created a gist to use it as a Cookie
object. e.g., Cookie.set(name,value)
and Cookie.get(name)
This read all cookies instead of scanning through. It's ok for small number of cookies.
You can create the radio buttons dynamically, ListBox
can help you do that, without converters, quite simple.
The concrete steps are below:
MyLovelyEnum
and binding the SelectedItem of the ListBox to the VeryLovelyEnum
property. <Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type system:Enum}"
x:Key="MyLovelyEnum">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyLovelyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Control Template
to populate each item inside as Radio button <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).
References: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
The problem here is that you're changing your enumerator as you remove items from the list. This isn't valid with a 'foreach' loop. But just about any other type of loop will be OK.
So you could try something like this:
for(int i=0; i < listBox1.Items.Count; )
{
string removelistitem = "OBJECT";
if(listBox1.Items[i].Contains(removelistitem))
listBox1.Items.Remove(item);
else
++i;
}
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
Open an administrator command prompt, and do this command:
fsutil fsinfo ntfsinfo [your drive]
The Bytes Per Cluster is the equivalent of the allocation unit.
You may need to handle javax.persistence.RollbackException
you don't, declare an interface that declares the methods you would like to call:
public interface MyInterface
{
void doStuff();
}
public class MyClass implements MyInterface
{
public void doStuff()
{
System.Console.Writeln("done!");
}
}
then you use
MyInterface mobj = (myInterface)obj;
mobj.doStuff();
If MyClass
is not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).
On Windows you can query the precise state of any port on any network-adapter using: GetExtendedTcpTable
You can filter it to only those related to your process, etc and do as you wish periodically monitoring as needed. This is "an alternative" approach.
You could also duplicate the socket handle and set up an IOCP/Overlapped i/o wait on the socket and monitor it that way as well.
as answered above: Object.keys(obj).length
But: as we have now a real Map class in ES6, I would suggest to use it instead of using the properties of an object.
const map = new Map();
map.set("key", "value");
map.size; // THE fastest way
Actually there is no c3 in the sample code in the original question. So the if would be more properly
if (c1 && c2) {
//sequence 1
} else if (!c1 && !c2) {
// sequence 3
}
I am on Mac OSX, so I can't answer for windows users:
I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).
One can simply modify it in the user keymap settings:
{ "key": "ctrl+left", "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }
For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then GoTo NextIteration
'Go to the next iteration
Else
End If
' This is how you make a line label in VBA - Do not use keyword or
' integer and end it in colon
NextIteration:
Next
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
There are a number of ways to do this:
onerror
in an img
, like <img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');" />
.This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.
So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
Simple as this
date('Y-m-d H:i:s', strtotime( str_replace('/', '-', $from_date ) ) );
String[] nameArray= {"John", "Paul", "Ringo", "George"};
int numberOfItems = nameArray.length;
for (int i=0; i<numberOfItems; i++)
{
String name = nameArray[i];
System.out.println("Hello " + name);
}
Have you tried putting it in your public folder? Whenever I have images or the like that I need to reference externally, I put it all there.
Use Math.Ceiling
to round up
Math.Ceiling(0.5); // 1
Use Math.Round
to just round
Math.Round(0.5, MidpointRounding.AwayFromZero); // 1
And Math.Floor
to round down
Math.Floor(0.5); // 0
As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items
returns a list, while iteritems
returns a iterator.
In python 3, items
returns a view, which is pretty much the same as an iterator.
If you are using python 2, you may want to user iteritems
if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)
Inline or inline-block elements can be aligned to the bottom of block level elements if the line-height of the parent/block element is greater than that of the inline element.*
markup:
<h1 class="alignBtm"><span>I'm at the bottom</span></h1>
css:
h1.alignBtm {
line-height: 3em;
}
h1.alignBtm span {
line-height: 1.2em;
vertical-align: bottom;
}
*make sure you're in standards mode
The Google Python Style Guide has the following convention:
module_name
,package_name
,ClassName
,method_name
,ExceptionName
,function_name
,GLOBAL_CONSTANT_NAME
,global_var_name
,instance_var_name
,function_parameter_name
,local_var_name
.
A similar naming scheme should be applied to a CLASS_CONSTANT_NAME
This works to update your angular/cli //*Global package (cmd as administrator)
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest
Please use this code for selecting date from Two Jquery calendar like Flight Booking site.
Hashtable h=new Hashtable();
h.put("January",0 );
h.put("February",1);
h.put("March",2);
h.put("April",3);
h.put("May",4);
h.put("June",5);
h.put("July",6);
h.put("August",7);
h.put("September",8);
h.put("October",9);
h.put("November",10);
h.put("December",11);
int expMonth;
int expYear;
// Calendar Month and Year
String calMonth = null;
String calYear = null;
boolean dateNotFound;
dateNotFound = true;
expMonth= 5;
expYear = 2014;
while(dateNotFound)
{
calMonth = driver.findElement(By.className("ui-datepicker-month")).getText(); // get the text of month
calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
if(((Integer)h.get(calMonth))+1 == expMonth && (expYear == Integer.parseInt(calYear)))
{
String block="//div[@class='monthBlock first']/table/tbody/tr/td"; // THIS IS FIRST CALENDAR
selectDate(expDate,block);
dateNotFound = false;
}
// parseInt - Converts String to integer and indexof( It will return the index position of String)
else if(((Integer)h.get(calMonth))+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
{
String block="//div[@class='monthBlock last']/table/tbody/tr/td"; // THIS IS SECOND CALENDAR
selectDate(expDate,block); // PASSING DATE AND CALENDAR
dateNotFound = false; // Otherwise it will rotate continuously
}
else if((Integer)h.get(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
{
System.out.println(" Please enter the date greater than Current date");
dateNotFound = false;
}
}
}
//Thread.sleep(3000);
public static void selectDate(String date,String block) throws IOException
{
String monthblock=block;
List<WebElement> dateWidget = driver.findElements(By.xpath(monthblock));
for (WebElement cell: dateWidget)
{
//Selects Date
if (cell.getText().equals(date))
{
cell.findElement(By.linkText(date)).click();
break;
}
}
//Doubt : How to verify the expected results and how to sort the program
driver.findElement(By.id("SearchBtn")).submit();
//driver.quit();
}
From http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql
To create a new database, just do sqlite_open(). To drop a database, delete the file.
Just a note of a peculiarity I faced:
Consider:
db server: 192.168.0.101
web server: 192.168.0.102
If you have a user defined in mysql.user as 'user'@'192.168.0.102'
with password1 and another 'user'@'192.168.0.%'
with password2,
then,
if you try to connect to the db server from the web server as 'user' with password2,
it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102'
authentication is used over the wildcard 'user'@'192.168.0.%'
authentication.
You can use the Eclipse Indigo EE version for Android development. It is quite good, and I haven't faced any issues so far.
To get the definition of the SQL codes, the easiest way is to use db2 cli!
at the unix or dos command prompt, just type
db2 "? SQL302"
this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)
hope this helped.
If you using Java then follow below code snippet :
GoogleCredential refreshTokenCredential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
In case anyone else is wondering, you can use is_
to generate foo IS NULL
:
>>> from sqlalchemy.sql import column >>> print column('foo').is_(None) foo IS NULL >>> print column('foo').isnot(None) foo IS NOT NULL
{
"cmd": ["gcc", "-Wall", "-ansi", "-pedantic-errors", "$file_name", "-o",
"${file_base_name}.exe", "&&", "start", "cmd", "/k" , "$file_base_name"],
"selector": "source.c",
"working_dir": "${file_path}",
"shell": true
}
It takes input and show output on a command prompt.
Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)
^
[A-Z] // Start with an uppercase Letter
( // A Group of:
[a-z] // mandatory lowercase letter
[A-Z]? // an optional Uppercase Letter at the end
// or in between lowercase letters
)+ // This group at least one time
$
Just a bit more compact and easier to read I think...
open terminal
\curl -sSL https://get.rvm.io | bash -s stable
restart terminal then
rvm install ruby-2.4.2
check ruby version it should be 2.4.2
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):
SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1),
"STRING_COLUMN")
AS OUTPUT FROM DUAL
Using the following script, based on SLaks answer, I determined that the correct answer is:
echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0
And here is my test script:
@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause
What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.
Use Google Search Operators to find it for you
search google with the below code..
inurl:domain.com filetype:xml click on this to view sitemap search example
change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
Swift version:
override func viewDidLoad() {
super.viewDidLoad()
// Assign your color to this property, for example here we assign the red color.
tableView.separatorColor = UIColor.redColor()
}
The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array
:
size_in_bytes = my_numpy_array.nbytes
Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.
I agree with Someth Victory, you need to add a specific class to some elements you want to be unselectable.
Also, you may add this class in specific cases using javascript. Example here Making content unselectable with help of CSS.
I don't believe the currently accepted answer is correct. For example, I have the following .htaccess
file in the root of a virtual server (apache 2.4):
<Files "reminder.php">
require all denied
require host localhost
require ip 127.0.0.1
require ip xxx.yyy.zzz.aaa
</Files>
This prevents external access to reminder.php
which is in a subdirectory.
I have a similar .htaccess
file on my Apache 2.2 server with the same effect:
<Files "reminder.php">
Order Deny,Allow
Deny from all
Allow from localhost
Allow from 127.0.0.1
Allow from xxx.yyy.zzz.aaa
</Files>
I don't know for sure but I suspect it's the attempt to define the subdirectory specifically in the .htaccess
file, viz <Files ./inscription/log.txt>
which is causing it to fail. It would be simpler to put the .htaccess
file in the same directory as log.txt
i.e. in the inscription
directory and it will work there.
You can make yourself a pure XAML approach by creating an attached behaviour.
Something like this:
public static class InputBindingsManager
{
public static readonly DependencyProperty UpdatePropertySourceWhenEnterPressedProperty = DependencyProperty.RegisterAttached(
"UpdatePropertySourceWhenEnterPressed", typeof(DependencyProperty), typeof(InputBindingsManager), new PropertyMetadata(null, OnUpdatePropertySourceWhenEnterPressedPropertyChanged));
static InputBindingsManager()
{
}
public static void SetUpdatePropertySourceWhenEnterPressed(DependencyObject dp, DependencyProperty value)
{
dp.SetValue(UpdatePropertySourceWhenEnterPressedProperty, value);
}
public static DependencyProperty GetUpdatePropertySourceWhenEnterPressed(DependencyObject dp)
{
return (DependencyProperty)dp.GetValue(UpdatePropertySourceWhenEnterPressedProperty);
}
private static void OnUpdatePropertySourceWhenEnterPressedPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
UIElement element = dp as UIElement;
if (element == null)
{
return;
}
if (e.OldValue != null)
{
element.PreviewKeyDown -= HandlePreviewKeyDown;
}
if (e.NewValue != null)
{
element.PreviewKeyDown += new KeyEventHandler(HandlePreviewKeyDown);
}
}
static void HandlePreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
DoUpdateSource(e.Source);
}
}
static void DoUpdateSource(object source)
{
DependencyProperty property =
GetUpdatePropertySourceWhenEnterPressed(source as DependencyObject);
if (property == null)
{
return;
}
UIElement elt = source as UIElement;
if (elt == null)
{
return;
}
BindingExpression binding = BindingOperations.GetBindingExpression(elt, property);
if (binding != null)
{
binding.UpdateSource();
}
}
}
Then in your XAML you set the InputBindingsManager.UpdatePropertySourceWhenEnterPressedProperty
property to the one you want updating when the Enter key is pressed. Like this
<TextBox Name="itemNameTextBox"
Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}"
b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"/>
(You just need to make sure to include an xmlns clr-namespace reference for "b" in the root element of your XAML file pointing to which ever namespace you put the InputBindingsManager in).
@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)
yourCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
}
});
}
Obviously you have to make your XML with the id of your checkbox :
<CheckBox
android:id="@+id/checkbox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your label"
/>
So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked()
it returns true
if the check box is checked.
I was getting the same error in chrome (and different one in Firefox, IE).
Also in error.log i was getting [error] [client cli.ent.ip.add] Invalid method in request \x16\x03
Following the instructions form this site I changed my configuration FROM:
<VirtualHost subdomain.domain.com:443>
ServerAdmin [email protected]
ServerName subdomain.domain.com
SSLEngine On
SSLCertificateFile conf/ssl/ssl.crt
SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>
TO:
<VirtualHost _default_:443>
ServerAdmin [email protected]
ServerName subdomain.domain.com
SSLEngine On
SSLCertificateFile conf/ssl/ssl.crt
SSLCertificateKeyFile conf/ssl/ssl.key
</VirtualHost>
Now it's working fine :)
You are using a function, which is marked as deleted
.
Eg:
int doSomething( int ) = delete;
The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.
If you see this error, you should check the function declaration for =delete
.
To know more about this new feature introduced in C++0x, check this out.
Just studied the topic, look for the examples in the thread and try to make my version:
from collections import defaultdict
# from pprint import pprint
import re
def gen_primes(limit=None):
"""Sieve of Eratosthenes"""
not_prime = defaultdict(list)
num = 2
while limit is None or num <= limit:
if num in not_prime:
for prime in not_prime[num]:
not_prime[prime + num].append(prime)
del not_prime[num]
else: # Prime number
yield num
not_prime[num * num] = [num]
# It's amazing to debug it this way:
# pprint([num, dict(not_prime)], width=1)
# input()
num += 1
def is_prime(num):
"""Check if number is prime based on Sieve of Eratosthenes"""
return num > 1 and list(gen_primes(limit=num)).pop() == num
def oneliner_is_prime(num):
"""Simple check if number is prime"""
return num > 1 and not any([num % x == 0 for x in range(2, num)])
def regex_is_prime(num):
return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None
def simple_is_prime(num):
"""Simple check if number is prime
More efficient than oneliner_is_prime as it breaks the loop
"""
for x in range(2, num):
if num % x == 0:
return False
return num > 1
def simple_gen_primes(limit=None):
"""Prime number generator based on simple gen"""
num = 2
while limit is None or num <= limit:
if simple_is_prime(num):
yield num
num += 1
if __name__ == "__main__":
less1000primes = list(gen_primes(limit=1000))
assert less1000primes == list(simple_gen_primes(limit=1000))
for num in range(1000):
assert (
(num in less1000primes)
== is_prime(num)
== oneliner_is_prime(num)
== regex_is_prime(num)
== simple_is_prime(num)
)
print("Primes less than 1000:")
print(less1000primes)
from timeit import timeit
print("\nTimeit:")
print(
"gen_primes:",
timeit(
"list(gen_primes(limit=1000))",
setup="from __main__ import gen_primes",
number=1000,
),
)
print(
"simple_gen_primes:",
timeit(
"list(simple_gen_primes(limit=1000))",
setup="from __main__ import simple_gen_primes",
number=1000,
),
)
print(
"is_prime:",
timeit(
"[is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import is_prime",
number=100,
),
)
print(
"oneliner_is_prime:",
timeit(
"[oneliner_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import oneliner_is_prime",
number=100,
),
)
print(
"regex_is_prime:",
timeit(
"[regex_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import regex_is_prime",
number=100,
),
)
print(
"simple_is_prime:",
timeit(
"[simple_is_prime(num) for num in range(2, 1000)]",
setup="from __main__ import simple_is_prime",
number=100,
),
)
The result of running this code show interesting results:
$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096
So I can see that we have right answers for different questions here; for a prime number generator gen_primes
looks like the right answer; but for a prime number check, the simple_is_prime
function is better suited.
This works, but I am always open to better ways to make is_prime
function.
Static variable in a header file:
say 'common.h'
has
static int zzz;
This variable 'zzz'
has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h'
has it's own unique object of name 'zzz'
.
Static variable in a class:
Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.
$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."
So let's say 'myclass.h'
has
struct myclass{
static int zzz; // this is only a declaration
};
and myclass.cpp
has
#include "myclass.h"
int myclass::zzz = 0 // this is a definition,
// should be done once and only once
and "hisclass.cpp"
has
#include "myclass.h"
void f(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
and "ourclass.cpp"
has
#include "myclass.h"
void g(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.
Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate
In android studio 3.0 they have introduced android-profiler to help you to understand how your app uses CPU, memory, network, and battery resources.
https://developer.android.com/studio/profile/android-profiler
Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).
I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.
I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.
You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.
Or else the easiest you could do is use sessions.
<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>
<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">
<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>
$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});
This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/
Try this
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):
It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.
Here are the commands again for easier copy-pasting:
openssl rsa -in $FF -out $TF
openssl rsa -aes256 -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF
and
openssl rsa -check -in $FF
openssl rsa -text -in $FF
In this approach only one statement is executed when the UPDATE is successful.
-- For each row in source
BEGIN TRAN
UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>
IF (@@ROWCOUNT = 0)
INSERT target (<target_columns>)
VALUES (<source_values>)
COMMIT
You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:
In this way you don't need to do anything special on the server side.
Of course, you can use Url
extensions methods in your Razor to specify the form action.
For browsers supporting HMTL5: simply define your submit buttons like this:
<input type='submit' value='...' formaction='@Url.Action(...)' />
For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):
$(document).on('click', '[type="submit"][data-form-action]', function (event) {
var $this = $(this);
var formAction = $this.attr('data-form-action');
$this.closest('form').attr('action', formAction);
});
NOTE: This script will handle the click for any element in the page that has type=submit
and data-form-action
attributes. When this happens, it takes the value of data-form-action
attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.
Then you simply have to add a data-form-action
attribute with the desired action URL to your button, like this:
<input type='submit' data-form-action='@Url.Action(...)' value='...'/>
Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.
As you can see, this requires no custom routing, you can use the standard Url
extension methods, and you have nothing special to do in modern browsers.
Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; }
and you'll be able to set it to null.
With the Pendulum very complete library, we have the subtract
method (and not "subStract"):
import pendulum
today = pendulum.datetime.today() # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'
We see that it handles jumping years.
The reverse equivalent is add
.
Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.
DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");
if (deUser != null)
{
... do something with your user
}
And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:
// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");
// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");
There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
Here is another answer. I hope it will help.
<a class="btn" ng-click="delete(item)">Delete</a>
$scope.delete(item){
var index = this.list.indexOf(item);
this.list.splice(index, 1);
}
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)
Full source is here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
How the hash is computed does usually not depend on the hashtable, but on the items added to it. In frameworks/base class libraries such as .net and Java, each object has a GetHashCode() (or similar) method returning a hash code for this object. The ideal hash code algorithm and the exact implementation depends on the data represented by in the object.
Well, as everyone said, use -S option. If you use -save-temps option, you can also get preprocessed file(.i), assembly file(.s) and object file(*.o). (get each of them by using -E, -S, and -c.)
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
You should use jmap -heap:format=b <process-id>
without any paths. So it creates a *.bin file which you can open with jvisualvm.exe
(same path as jmap). It's a great tool to open such dump files.
what led me to this page is that I set within a page then the inside of an included page I did the increment
and here is the problem
so to solve such a problem, simply use scope="request"
when you declare the variable or the increment
//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}" scope="request" />
hope this saves your time
In your case the "Vendor code 17002" is the equivalent of the ORA-12541 error: It's most likely that your listener is down, or has an improper port or service name. From the docs:
ORA-12541: TNS no listener
Cause: Listener for the source repository has not been started.
Action: Start the Listener on the machine where the source repository resides.