import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
lb.config(visible=visible)
visiblelabel(x, False) # Hide
visiblelabel(x, True) # Show
P.S. config
can change any attribute:
x.config(text='Hello') # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold')) # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white') # Background: red, Foreground: white
It's a bypass of StringVar
, IntVar
etc.
You can use BIGINT as follows:
CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
);
A version of Cheeso solution with reverse sorting, I also removed the ternary expressions for lack of clarity (but this is personal taste).
function(prop, reverse) {
return function(a, b) {
if (typeof a[prop] === 'number') {
return (a[prop] - b[prop]);
}
if (a[prop] < b[prop]) {
return reverse ? 1 : -1;
}
if (a[prop] > b[prop]) {
return reverse ? -1 : 1;
}
return 0;
};
};
You can copy all enumerable own properties of an object to a new one by Object.assign(target, ...sources):
trivial_object = Object.assign({}, non_trivial_object);
so in your scenario, it should be enough to change
ret.push(i);
to
ret.push(Object.assign({}, i));
CREATE TABLE Employees
(
Id int,
Name varchar(50) not null,
Photo varbinary(max) not null
)
INSERT INTO Employees (Id, Name, Photo)
SELECT 10, 'John', BulkColumn
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture
To clarify why the other answers can not work:
System.gc()
(along with Runtime.getRuntime().gc()
, which does the exact same thing) hints that you want stuff destroyed. Vaguely. The JVM is free to ignore requests to run a GC cycle, if it doesn't see the need for one. Plus, unless you've nulled out all reachable references to the object, GC won't touch it anyway. So A and B are both disqualified.
Runtime.getRuntime.gc()
is bad grammar. getRuntime
is a function, not a variable; you need parentheses after it to call it. So B is double-disqualified.
Object
has no delete
method. So C is disqualified.
While Object
does have a finalize
method, it doesn't destroy anything. Only the garbage collector can actually delete an object. (And in many cases, they technically don't even bother to do that; they just don't copy it when they do the others, so it gets left behind.) All finalize
does is give an object a chance to clean up before the JVM discards it. What's more, you should never ever be calling finalize
directly. (As finalize
is protected, the JVM won't let you call it on an arbitrary object anyway.) So D is disqualified.
Besides all that, object.doAnythingAtAllEvenCommitSuicide()
requires that running code have a reference to object
. That alone makes it "alive" and thus ineligible for garbage collection. So C and D are double-disqualified.
You can resize using style and width to resize the textbox. Here is the code for it.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div align="center">_x000D_
_x000D_
<form method="post">_x000D_
<div class="w3-row w3-section">_x000D_
<div class="w3-rest" align = "center">_x000D_
<input name="lastName" type="text" id="myInput" style="width: 50%">_x000D_
</div>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Use align to center the textbox.
You can explicitly tell Eclipse where to find it. Open eclipse.ini
and add the following lines to the top of the file:
-vm
/absolute/path/to/jre6/bin
Update: I just nailed down the root cause on my own Windows machine. The GlassFish installer complained with exactly the same error message and after digging in GlassFish forums, the cause was clear: a corrupt JRE install on a Windows machine. My JRE came along with the JDK and the Java 6 JDK installer didn't install the JRE properly somehow. A DLL file was missing in JDK's JRE installation. After I reinstalled the standalone JRE from http://java.com, overwriting the old one, the GlassFish installer continued and also Eclipse was able to start flawlessly without those two lines in eclipse.ini
.
In script is usefull something like this:
if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi
it prevents before re-create "bad" looped symlink after re-run script
As said in the documentation:
Must: The clause (query) must appear in matching documents.
Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.
In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.
Since you want your results to satisfy all the queries, you should use must.
You can indeed use filters inside a boolean query.
Note: In react you can put javascript expression inside curly bracket. We can use this property in this example.
Note: give one look to below example:
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {i:1};
}
handleClick() {
this.setState(prevState => ({i : prevState.i + 1}));
console.log(this.state.j);
}
render() {
return (
<div>
<p onClick={this.handleClick.bind(this)}>Click to change image</p>
<img src={'images/back'+ this.state.i+'.jpg'}/>
</div>
);
}
}
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
label {
width:200px;
display: inline-block;
}
OR
label {
width:200px;
display: inline-flex;
}
OR
label {
width:200px;
display: inline-table;
}
You have to be very careful about the method names. In this case, the method name is just "lowercaseString
", not "lowercaseString:
" (note the absence of the colon). That's why you're getting NO
returned, because NSString
objects respond to the lowercaseString
message but not the lowercaseString:
message.
How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString
), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:
.
You can also look at the documentation and note the presence or absence of a trailing colon.
The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.
The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:
setTimeout(function () {
console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')
The flow here is:
If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:
var a = 100;
setTimeout(function () {
a = 0;
}, 0);
var b = a; // 100 or 0?
The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.
Is this a better demon to battle than the complexity of preemption? That depends.
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
You can do something like this
Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();
where you can change "firstname" with the name of the column you want.
If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.
@PostMapping(value = "/item/{id}/{method}")
public String getForm(@PathVariable("id") String itemId ,
@PathVariable("method") String methodCall , Model model){
if(methodCall.equals("create")){
//logic
}
if(methodCall.equals("update")){
//logic
}
return "path to your form";
}
There are two answers of finding files and applying chmod
to them. First one is find
the file and apply chmod
as it finds (as suggested by @WombleGoneBad).
find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
Second solution is to generate list of all files with find
command and supply this list to the chmod
command (as suggested by @lamgesh).
chmod 755 $(find /path/to/base/dir -type d)
Both of these versions work nice as long as the number of files returned by the find
command is small. The second solution looks great to eye and more readable than the first one. If there are large number of files, the second solution returns error : Argument list too long.
So my suggestion is
chmod -R 755 /opt/lampp/htdocs
if you want to change permissions of all files and directories at once.find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
if the number of files you are using is very large. The -type x
option searches for specific type of file only, where d is used for finding directory, f for file and l for link.chmod 755 $(find /path/to/base/dir -type d)
otherwiseOne thing to note:
The .FRM file has your table structure in it, and is specific to your MySQL version.
The .MYD file is NOT specific to version, at least not minor versions.
The .MYI file is specific, but can be left out and regenerated with REPAIR TABLE
like the other answers say.
The point of this answer is to let you know that if you have a schema dump of your tables, then you can use that to generate the table structure, then replace those .MYD files with your backups, delete the MYI files, and repair them all. This way you can restore your backups to another MySQL version, or move your database altogether without using mysqldump
. I've found this super helpful when moving large databases.
If the characters you want to remove are always the same characters, then consider chomp
:
'abc123'.chomp('123') # => "abc"
The advantages of chomp
are: no counting, and the code more clearly communicates what it is doing.
With no arguments, chomp
removes the DOS or Unix line ending, if either is present:
"abc\n".chomp # => "abc"
"abc\r\n".chomp # => "abc"
From the comments, there was a question of the speed of using #chomp
versus using a range. Here is a benchmark comparing the two:
require 'benchmark'
S = 'asdfghjkl'
SL = S.length
T = 10_000
A = 1_000.times.map { |n| "#{n}#{S}" }
GC.disable
Benchmark.bmbm do |x|
x.report('chomp') { T.times { A.each { |s| s.chomp(S) } } }
x.report('range') { T.times { A.each { |s| s[0...-SL] } } }
end
Benchmark Results (using CRuby 2.13p242):
Rehearsal -----------------------------------------
chomp 1.540000 0.040000 1.580000 ( 1.587908)
range 1.810000 0.200000 2.010000 ( 2.011846)
-------------------------------- total: 3.590000sec
user system total real
chomp 1.550000 0.070000 1.620000 ( 1.610362)
range 1.970000 0.170000 2.140000 ( 2.146682)
So chomp is faster than using a range, by ~22%.
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
If you're into the whole brevity thing, here it is using Lodash:
var os = require('os');
var _ = require('lodash');
var firstLocalIp = _(os.networkInterfaces()).values().flatten().where({ family: 'IPv4', internal: false }).pluck('address').first();
console.log('First local IPv4 address is ' + firstLocalIp);
_x000D_
URL url = Test.class.getResource(args[0]); // reading demo file path from
// same location where class
File input=null;
try {
input = new File(url.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
If column is not NOT NULL
(nullable).
You just put NULL
instead of value in INSERT
statement.
LocalDate date=LocalDate.now();
System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) ); //prints Thu
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.
I know this question is a bit old, but this is something simple that works for me very well to delete images off my project I'm working on.
unlink(dirname(__FILE__) . "/img/tasks/" . 'image.jpg');
The dirname(__FILE__)
section prints out the base path to your project. The /img/tasks/
are two folders down from my base path. And finally, there's my image I want to delete which you can make into anything you need to.
With this I have not had any problem getting to my files on my server and deleting them.
I created a function to do this, where you can specify the desired output character length:
CREATE FUNCTION [dbo].[udfLeadingZero]
(
@String VARCHAR(MAX)
, @Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
SET @String = RIGHT(REPLICATE('0',@Len)+@String,@Len)
RETURN @String
END
GO
I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below
{DefaultNamespace}.Properties.Resources.{ResourceName}
For a really thorough explanation and workaround, not only for indexOf but other array functions missing in IE check out the StackOverflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.)
The query will be something like:
SELECT
DATE_FORMAT(
MIN(timestamp),
'%d/%m/%Y %H:%i:00'
) AS tmstamp,
name,
COUNT(id) AS cnt
FROM
table
GROUP BY ROUND(UNIX_TIMESTAMP(timestamp) / 300), name
If anyone would like I converted this to an extension method on IEnumerable:
public static class ListExtensions
{
public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
{
StringBuilder sb = new StringBuilder();
IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
if (includeHeaderLine)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(propertyInfo.Name).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
foreach (T obj in listToExport)
{
T localObject = obj;
var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));
sb.AppendLine(line);
}
return sb.ToString();
}
private static string SanitizeValuesForCSV(object value, string delimeter)
{
string output;
if (value == null) return "";
if (value is DateTime)
{
output = ((DateTime)value).ToLongDateString();
}
else
{
output = value.ToString();
}
if (output.Contains(delimeter) || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
output = output.Replace("\n", " ");
output = output.Replace("\r", "");
return output;
}
}
I'm on macOS Catalina 10.15.3, and I had a similar error: ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH
Fixed it with:
pip3 install graphviz
AND brew install graphviz
Note the pip3 install
will only return the success message Successfully installed graphviz-0.13.2
so we still need to run brew install
to get graphviz 2.42.3 (as of 10 Mar 2020, 6PM).
Fun fact!
The 'modulus' operation is defined as:
a % n ==> a - (a/n) * n
So you could roll your own, although it will be FAR slower than the built in % operator:
public static int Mod(int a, int n)
{
return a - (int)((double)a / n) * n;
}
Edit: wow, misspoke rather badly here originally, thanks @joren for catching me
Now here I'm relying on the fact that division + cast-to-int in C# is equivalent to Math.Floor
(i.e., it drops the fraction), but a "true" implementation would instead be something like:
public static int Mod(int a, int n)
{
return a - (int)Math.Floor((double)a / n) * n;
}
In fact, you can see the differences between % and "true modulus" with the following:
var modTest =
from a in Enumerable.Range(-3, 6)
from b in Enumerable.Range(-3, 6)
where b != 0
let op = (a % b)
let mod = Mod(a,b)
let areSame = op == mod
select new
{
A = a,
B = b,
Operator = op,
Mod = mod,
Same = areSame
};
Console.WriteLine("A B A%B Mod(A,B) Equal?");
Console.WriteLine("-----------------------------------");
foreach (var result in modTest)
{
Console.WriteLine(
"{0,-3} | {1,-3} | {2,-5} | {3,-10} | {4,-6}",
result.A,
result.B,
result.Operator,
result.Mod,
result.Same);
}
Results:
A B A%B Mod(A,B) Equal?
-----------------------------------
-3 | -3 | 0 | 0 | True
-3 | -2 | -1 | -1 | True
-3 | -1 | 0 | 0 | True
-3 | 1 | 0 | 0 | True
-3 | 2 | -1 | 1 | False
-2 | -3 | -2 | -2 | True
-2 | -2 | 0 | 0 | True
-2 | -1 | 0 | 0 | True
-2 | 1 | 0 | 0 | True
-2 | 2 | 0 | 0 | True
-1 | -3 | -1 | -1 | True
-1 | -2 | -1 | -1 | True
-1 | -1 | 0 | 0 | True
-1 | 1 | 0 | 0 | True
-1 | 2 | -1 | 1 | False
0 | -3 | 0 | 0 | True
0 | -2 | 0 | 0 | True
0 | -1 | 0 | 0 | True
0 | 1 | 0 | 0 | True
0 | 2 | 0 | 0 | True
1 | -3 | 1 | -2 | False
1 | -2 | 1 | -1 | False
1 | -1 | 0 | 0 | True
1 | 1 | 0 | 0 | True
1 | 2 | 1 | 1 | True
2 | -3 | 2 | -1 | False
2 | -2 | 0 | 0 | True
2 | -1 | 0 | 0 | True
2 | 1 | 0 | 0 | True
2 | 2 | 0 | 0 | True
I solve the problem by check my local keychains.Keep login.keychain has the right certificate
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
For ASP.NET MVC if you want to make an exception for leaving the page via submitting a particular form:
Set a form id:
@using (Html.BeginForm("Create", "MgtJob", FormMethod.Post, new { id = "createjob" }))
{
// Your code
}
<script type="text/javascript">
// Without submit form
$(window).bind('beforeunload', function () {
if ($('input').val() !== '') {
return "It looks like you have input you haven't submitted."
}
});
// this will call before submit; and it will unbind beforeunload
$(function () {
$("#createjob").submit(function (event) {
$(window).unbind("beforeunload");
});
});
</script>
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
Same case here, but nothing about comments posted it's right in my case, I have only one branch (master) and only use Unix file system, this error occur randomly when I run git fetch --progress --prune origin and branch is ahead or 'origin/master'. Nobody can commit, only 1 user can do push.
NOTE: I have a submodule in acme repository, and acme have new submodule changes (new commits), I need first do a submodule update with git submodule update.
[2014-07-29 13:58:37] Payload POST received from Bitbucket
[2014-07-29 13:58:37] Exec: cd /var/www/html/acme
---------------------
[2014-07-29 13:58:37] Updating Git code for all branches
[2014-07-29 13:58:37] Exec: /usr/bin/git checkout --force master
[2014-07-29 13:58:37] Your branch is ahead of 'origin/master' by 1 commit.
[2014-07-29 13:58:37] (use "git push" to publish your local commits)
[2014-07-29 13:58:37] Command returned some errors:
[2014-07-29 13:58:37] Already on 'master'
---------------------
[2014-07-29 13:58:37] Exec: /usr/bin/git fetch --progress --prune origin
[2014-07-29 13:58:39] Command returned some errors:
[2014-07-29 13:58:39] error: Ref refs/remotes/origin/master is at 8213a9906828322a3428f921381bd87f42ec7e2f but expected c8f9c00551dcd0b9386cd9123607843179981c91
[2014-07-29 13:58:39] From bitbucket.org:acme/acme
[2014-07-29 13:58:39] ! c8f9c00..8213a99 master -> origin/master (unable to update local ref)
---------------------
[2014-07-29 13:58:39] Unable to fetch Git data
To solve this problem (in my case) simply run first git push if your branch is ahead of origin.
In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="serializers">
<array>
<bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
</array>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
was in unexplained way overwritten back to default by something.
This worked for me:
@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {
private Long value;
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
public class CustomObjectSerializer extends JsonSerializer<CustomObject> {
@Override
public void serialize(CustomObject value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("y", value.getValue());
jgen.writeEndObject();
}
@Override
public Class<CustomObject> handledType() {
return CustomObject.class;
}
}
No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>
) is needed in my solution.
Another approach using range based for loop with reference variable
string test = "Hello World";
for(auto& c : test)
{
c = tolower(c);
}
cout<<test<<endl;
If you want to change the size of plot the use arg figsize
df.groupby(['NFF', 'ABUSE']).size().unstack()
.plot(kind='bar', stacked=True, figsize=(15, 5))
Night's answer is correct
html, body {margin:0;padding:0;height:100%;}
Also check that your div or element is NOT inside another one (with height less than 100%) Hope this helps someone else.
You can use a pty ("pseudo-teletype", where a serial port is a "real teletype") for this. From one end, open /dev/ptyp5
, and then attach your program to /dev/ttyp5
; ttyp5
will act just like a serial port, but will send/receive everything it does via /dev/ptyp5.
If you really need it to talk to a file called /dev/ttys2
, then simply move your old /dev/ttys2
out of the way and make a symlink from ptyp5
to ttys2
.
Of course you can use some number other than ptyp5
. Perhaps pick one with a high number to avoid duplicates, since all your login terminals will also be using ptys.
Wikipedia has more about ptys: http://en.wikipedia.org/wiki/Pseudo_terminal
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
Try this:
$(document).ready(function() {
if ($('#leftmenu').html() === "") {
$('#menuTitleWrapper').remove();
$('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
$('#PageContent').css({'top' : '30px', 'position' : 'relative'});
}
});
It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).
Fork creates a copy of a calling process. generally follows the structure
int cpid = fork( );
if (cpid = = 0)
{
//child code
exit(0);
}
//parent code
wait(cpid);
// end
(for child process text(code),data,stack is same as calling process) child process executes code in if block.
EXEC replaces the current process with new process's code,data,stack. generally follows the structure
int cpid = fork( );
if (cpid = = 0)
{
//child code
exec(foo);
exit(0);
}
//parent code
wait(cpid);
// end
(after exec call unix kernel clears the child process text,data,stack and fills with foo process related text/data) thus child process is with different code (foo's code {not same as parent})
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
print("Hello, World!")
You are probably using Python 3.0, where print
is now a function (hence the parenthesis) instead of a statement.
For anyone reading this post: Do yourself a favor and stay away of ng-grid. Is full of bugs (really..almost every part of the lib is broken somehow), the devs has abandoned the support of 2.0.x branch in order to work in 3.0 which is very far of being ready. Fixing the problems by yourself is not an easy task, ng-grid code is not small and is not simple, unless you have a lot of time and a deep knowledge of angular and js in general, its going to be a hard task.
Bottom Line: is full of bugs, and the last stable version has been abandoned.
The github is full of PRs, but they are being ignored. And if you report a bug in the 2.x branch, it's get closed.
I know is an open source proyect and the complains may sound a little bit out of place, but from the perspective of a developer looking for a library, that's my opinion. I spent many hours working with ng-grid in a large proyect and the headcaches are never ending
Class.forName("ClassName") will solve your purpose.
Class class1 = Class.forName(ClassName);
Object object1 = class1.newInstance();
Update: capability appears to have been removed by Apple on or around iOS 4
Just to expand on an earlier answer, something like this does it for me:
NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];
Note: This retrieves the "Phone number" that was entered during the iPhone's iTunes activation and can be null or an incorrect value. It's NOT read from the SIM card.
At least that does in 2.1. There are a couple of other interesting keys in NSUserDefaults that may also not last. (This is in my app which uses a UIWebView)
WebKitJavaScriptCanOpenWindowsAutomatically
NSInterfaceStyle
TVOutStatus
WebKitDeveloperExtrasEnabledPreferenceKey
and so on.
Not sure what, if anything, the others do.
There is a newer, less mature curl wrapper being developed called C++ Requests. Here's a simple GET request:
#include <iostream>
#include <cpr.h>
int main(int argc, char** argv) {
auto response = cpr::Get(cpr::Url{"http://httpbin.org/get"});
std::cout << response.text << std::endl;
}
It supports a wide variety of HTTP verbs and curl options. There's more usage documentation here.
Disclaimer: I'm the maintainer of this library.
I typically abbreviate so that I can use several places in my code. Near the top, do something like this:
string nl = System.Environment.NewLine;
Then I can just use "nl" instead of the full qualification everywhere when constructing strings.
Multiple columns in a key are going to, in general, perform more poorly than a surrogate key. I prefer to have a surrogate key and then a unique index on a multicolumn key. That way you can have better performance and the uniqueness needed is maintained. And even better, when one of the values in that key changes, you don't also have to update a million child entries in 215 child tables.
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
You don't have the mcrypt library installed.
See http://www.php.net/manual/en/mcrypt.setup.php for more information.
If you are on shared hosting, you can ask your provider to install it.
In OSX you can easily install mcrypt via homebrew
brew install php54-mcrypt --without-homebrew-php
Then add this line to /etc/php.ini.
extension="/usr/local/Cellar/php54-mcrypt/5.4.24/mcrypt.so"
I added this helper method to handle my POST requests that return an object I care about.
For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.
Helper Method:
public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
{
//Note: Ideally the RestClient isn't created for each request.
var restClient = new RestClient("http://localhost:999");
var restRequest = new RestRequest(relativeUri, Method.POST)
{
RequestFormat = DataFormat.Json
};
restRequest.AddBody(postBody);
var result = restClient.Post<TResponse>(restRequest);
if (!result.IsSuccessful)
{
throw new HttpException($"Item not found: {result.ErrorMessage}");
}
return result.Data;
}
Usage:
public List<WhateverReturnType> GetFromApi()
{
var idsForLookup = new List<int> {1, 2, 3, 4, 5};
var relativeUri = "/api/idLookup";
var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);
return restResponse;
}
I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor. Example below
public class MyClass
{
public static async Task<MyClass> Create()
{
var myClass = new MyClass();
await myClass.Initialize();
return myClass;
}
private MyClass()
{
}
private async Task Initialize()
{
await Task.Delay(1000); // Do whatever asynchronous work you need to do
}
}
Basicly what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that noone could "accidently" create an instance of this class without calling the proper initialization methods. All the logic around the creation of the object is still contained within the class (just within a static method).
var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass
Implemented on the current scenario it would look something like:
public partial class Page2 : PhoneApplicationPage
{
public static async Task<Page2> Create()
{
var page = new Page2();
await page.getWritings();
return page;
}
List<Writing> writings;
private Page2()
{
InitializeComponent();
}
private async Task getWritings()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
writings.Add(writing);
}
myLongList.ItemsSource = writings;
}
}
And instead of doing
var page = new Page2();
You would be doing
var page = await Page2.Create();
I received this error when I copied a class object using JSON.parse and JSON.stringify() which removed the function like:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log('area of square: ', square.calcArea());
const squareCopy = JSON.parse(JSON.stringify(square));
// Will throw an exception since calcArea() is no longer function
console.log('area of square copy: ', squareCopy.calcArea());
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
curl
's -w
option and the sub variable url_effective
is what you are
looking for.
Something like
curl -Ls -o /dev/null -w %{url_effective} http://google.com
More info
-L Follow redirects -s Silent mode. Don't output anything -o FILE Write output to <file> instead of stdout -w FORMAT What to output after completion
More
You might want to add -I
(that is an uppercase i
) as well, which will make the command not download any "body", but it then also uses the HEAD method, which is not what the question included and risk changing what the server does. Sometimes servers don't respond well to HEAD even when they respond fine to GET.
I would just use the request.remote_ip
that's simple and it works. Any reason you need another method?
See: Get real IP address in local Rails development environment for some other things you can do with client server ip's.
When you click on hide me
, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()
You can see this for more clarification
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
To view database roles assigned to users, you can use sys.database_role_members
The following query returns the members of the database roles.
SELECT DP1.name AS DatabaseRoleName,
isnull (DP2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DP1
ON DRM.role_principal_id = DP1.principal_id
LEFT OUTER JOIN sys.database_principals AS DP2
ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;
You have to give height and width to that image.
eg. height : 200px
and width : 200px
also give border-radius:50%;
to create circle you have to give equal height and width
if you are using bootstrap then give height and width and img-circle
class to img
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
There is another alternative solution, that seems to be more attractive.
Now with all the above setup, you have a few options for the client:
Update: I did go this route, and it has been working nicely. Just wanted to add to this.
Reference links:
Add <b>
tag
<p> <b> I am in Bold </b></p>
For more text formatting tags click here
I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:
UPDATE FUNCTIONS A
INNER JOIN (
SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
FROM TAX BB, FUNCTIONS AA
WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
GROUP BY AA.Func_ID
) B
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code
Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:
UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
However, this still doesn't work.
I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:
UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
"MinOfTax_Code",
"FUNCTIONS_TAX",
"Func_ID = '" & Func_ID & "'"
)
Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).
Good luck!
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
I've encountered this kind of problem before. I was using the Windows x64 operating system, so I was getting an error in openssl. Later I realized that the path to the OpenSSL installation file was "C: \ OpenSSL win32". Finally, I deleted the OpenSSL program and installed it to "C: \ Program Files (x86)" and used it smoothly.
I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.
Good example:
int result = Check() ? 1 : 0;
Bad example:
int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
Maybe you want a hash instead (or in addition). Arrays are an ordered set of elements; if you create $foo[23]
, you implicitly create $foo[0]
through $foo[22]
.
From Swift 5.3
, you do not have to unwrap self
in closure if you pass [self]
before in
in closure.
Refer someFunctionWithEscapingClosure { [self] in x = 100 }
in this swift doc
impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
The profile choices need to be setup as a ManyToManyField for this to work correctly.
So... your model should be like this:
class Choices(models.Model):
description = models.CharField(max_length=300)
class Profile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
choices = models.ManyToManyField(Choices)
Then, sync the database and load up Choices with the various options you want available.
Now, the ModelForm will build itself...
class ProfileForm(forms.ModelForm):
Meta:
model = Profile
exclude = ['user']
And finally, the view:
if request.method=='POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
else:
form = ProfileForm()
return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.
Good luck.
I faced this issue:
(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.
It was my mistake, I was replacing res
object in then(function(res)
, so changed res
to result and now it is working.
module.exports.update = function(req, res){
return Services.User.update(req.body)
.then(function(res){//issue was here, res overwrite
return res.json(res);
}, function(error){
return res.json({error:error.message});
}).catch(function () {
console.log("Promise Rejected");
});
module.exports.update = function(req, res){
return Services.User.update(req.body)
.then(function(result){//res replaced with result
return res.json(result);
}, function(error){
return res.json({error:error.message});
}).catch(function () {
console.log("Promise Rejected");
});
Service code:
function update(data){
var id = new require('mongodb').ObjectID(data._id);
userData = {
name:data.name,
email:data.email,
phone: data.phone
};
return collection.findAndModify(
{_id:id}, // query
[['_id','asc']], // sort order
{$set: userData}, // replacement
{ "new": true }
).then(function(doc) {
if(!doc)
throw new Error('Record not updated.');
return doc.value;
});
}
module.exports = {
update:update
}
For static files like pdfs, Word docs, etc. just use Express's static function in your config:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
And then just put all your files inside that 'public' folder, for example:
/public/docs/my_word_doc.docx
And then a regular old link will allow the user to download it:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
To quote the article below, ""then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only."
I usually look to this page for any basic promise questions, let me know if I am wrong
If you want to set styles of all elements in body you should use next code^
body{
color: green;
}
If you're looking to generate a single error message string that contains the ModelState
error messages you can use SelectMany
to flatten the errors into a single list:
if (!ModelState.IsValid)
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
You're doing only one mistake.
use replaceAll()
function over there.
e.g.
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );
Git keeps all of its files in the .git
directory. Just remove that one and init again.
If you can't find it, it's because it is hidden.
In Windows 7, you need to go to your folder, click on Organize on the top left, then click on Folder and search options, then click on the View tab and click on the Show hidden files, folders and drives radio button.
On a Mac OS:
Open a Terminal (via Spotlight: press CMD + SPACE, type terminal
and press Enter) and run:
defaults write com.apple.finder AppleShowAllFiles 1 && killall Finder
Note: The keyboard shortcut to show hidden files in Finder is CMD + SHIFT + . so it is no longer necessary to modify the finder config this way
You could also type cd
(the space is important), drag and drop your git repo folder from Finder to the terminal window, press return, then type rm -fr .git
, then return again.
On Ubuntu, use shortcut Ctrl + H.
The tail
program can do this:
ls -lart | tail -n +2
The -n +2
means “start passing through on the second line of output”.
You have to mock the module and set the spy by yourself:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
doSomething: jest.fn()
}))
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
I resolved this problem this way:
In onCreateOptionsMenu
:
this.menu = menu;
this.menu.add("calendar");
ImageView imageView = new ImageView(getActivity());
imageView.setMinimumHeight(128);
imageView.setMinimumWidth(128);
imageView.setImageDrawable(yourDrawable);
MenuItem item = this.menu.getItem(0);
item.setActionView(imageView);
in onOptionsItemSelected
:
if (item.getOrder() == 0) {
//TODO
return true;
}
If you are not targeting 2.x versions you can set your minimum sdk version of 4.x and then create project. Appcompat V7 lib wont be created.
This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.
Example:
SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)
(docs).
The dplyr
select
function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by
function. For example:
library(dplyr)
# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))
# Return the distinct values of x
dat %>%
group_by(x) %>%
summarise()
x
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
If you want to change the column name you can add the following:
dat %>%
group_by(x) %>%
summarise() %>%
select(unique.x=x)
This both selects column x
from among all the columns in the data frame that dplyr
returns (and of course there's only one column in this case) and changes its name to unique.x
.
You can also get the unique values directly in base R
with unique(dat$x)
.
If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE),
y=sample(letters[1:5], 100, replace=TRUE))
dat %>%
group_by(x,y) %>%
summarise() %>%
select(unique.x=x, unique.y=y)
For Android studio 3.4.2 go to View -> Tool Windows -> Logcat.
I think that your problem was emerged from typescript and module version mismatch.This issue is very similar to your question and answers are very satisfying.
We need to add host security certificate to php.ini file. For local developement enviroment we can add cacert.pem in your local php.ini.
do phpinfo(); and file your php.ini path open and add uncomment ;curl.capath
curl.capath=path_of_your_cacert.pem
This is the required source code :
public static void openKeypad(final Context context, final View v)
{
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
Log.e("openKeypad", "Inside Handler");
}
},300);}
For details , Please go through this link. This helped me. https://github.com/Nikhillosalka/Keyboard/blob/master/README.md
If you want to use the toDF
method, you have to convert your RDD
of Array[String]
into a RDD
of a case class. For example, you have to do:
case class Test(id:String,filed2:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
Since you asked for a C++ solution...
#include <algorithm>
#include <iterator>
const int arr_size = 10;
some_type src[arr_size];
// ...
some_type dest[arr_size];
std::copy(std::begin(src), std::end(src), std::begin(dest));
Use generic types !
class DataExtraction<T>
{
DateRangeReport dateRange;
List<Predicate> predicates;
List<string> cids;
public DataExtraction( DateRangeReport dateRange,
List<Predicate> predicates,
List<string> cids)
{
this.dateRange = dateRange;
this.predicates = predicates;
this.cids = cids;
}
}
And call it like this :
DataExtraction<AdPerformanceRow> extractor = new DataExtraction<AdPerformanceRow>(dates, predicates , cids);
Try to use a for each
for ( Direction direction : Direction.values()){
System.out.println(direction.toString());
}
You can install nano in powershell via choco - It's a low friction way to get text editing capabilities into powershell:
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco install nano
nano myfile.txt
Best part is it becomes part of the path, and stays working across reboots etc :)
Here is complete example using NLog
using NLog;
using System;
using System.Windows;
namespace MyApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public App()
{
var currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = (Exception)e.ExceptionObject;
logger.Error("UnhandledException caught : " + ex.Message);
logger.Error("UnhandledException StackTrace : " + ex.StackTrace);
logger.Fatal("Runtime terminating: {0}", e.IsTerminating);
}
}
}
There is a much simpler solution for that.
Actually treating the items of JArray
as JObject
works.
Here is an example:
Let's say we have such array of JSON objects:
JArray jArray = JArray.Parse(@"[
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
}]");
To get access each item we just do the following:
foreach (JObject item in jArray)
{
string name = item.GetValue("name").ToString();
string url = item.GetValue("url").ToString();
// ...
}
You can use Math:
int x = Math.abs(-5);
You must have the definition of class B
before you use the class. How else would the compiler otherwise know that there exists such a function as B::add
?
Either define class B
before class A
, or move the body of A::doSomething
to after class B
have been defined, like
class B;
class A
{
B* b;
void doSomething();
};
class B
{
A* a;
void add() {}
};
void A::doSomething()
{
b->add();
}
// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
Should use ToUniversalTime() for the DateTime object.
KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.
UPDATE:
The keypress event is fired when a key is pressed down and that key normally produces a character value
I use a jQuery script to create "shadow" forms for my POSTable links.
Instead of <a href="/some/action?foo=bar">
, I write <a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">
. The script makes a hidden form with hidden inputs, and submits it when the link is clicked.
$("a[data-post]")
.each(function() {
let href = $(this).data("post"); if (!href) return;
let $form = $("<form></form>").attr({ method:"POST",action:href }).css("display","none")
let data = $(this).data()
for (let dat in data) {
if (dat.startsWith("postVar")) {
let varname = dat.substring(7).toLowerCase() // postVarId -> id
let varval = data[dat]
$form.append($("<input/>").attr({ type:"hidden",name:varname,value:varval }))
}
}
$("body").append($form)
$(this).data("postform",$form)
})
.click(function(ev) {
ev.preventDefault()
if ($(this).data("postform")) $(this).data("postform").submit(); else console.error("No .postform set in <a data-post>")
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">click me</a>
_x000D_
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
Use IFERROR(value, value_if_error)
GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev
command. View definitions will show in your configured editor.
julian@assange=# \ev {your_view_names}
Bonus. Some useful command to interact with query buffer.
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
Use People implements Comparable<People>
instead; this defines the natural ordering for People
.
A Comparator<People>
can also be defined in addition, but People implements Comparator<People>
is not the right way of doing things.
The two overloads for Collections.sort
are different:
<T extends Comparable<? super T>> void sort(List<T> list)
Comparable
objects using their natural ordering<T> void sort(List<T> list, Comparator<? super T> c)
Comparator
You're confusing the two by trying to sort a Comparator
(which is again why it doesn't make sense that Person implements Comparator<Person>
). Again, to use Collections.sort
, you need one of these to be true:
Comparable
(use the 1-arg sort
)Comparator
for the type must be provided (use the 2-args sort
)Also, do not use raw types in new code. Raw types are unsafe, and it's provided only for compatibility.
That is, instead of this:
ArrayList peps = new ArrayList(); // BAD!!! No generic safety!
you should've used the typesafe generic declaration like this:
List<People> peps = new ArrayList<People>(); // GOOD!!!
You will then find that your code doesn't even compile!! That would be a good thing, because there IS something wrong with the code (Person
does not implements Comparable<Person>
), but because you used raw type, the compiler didn't check for this, and instead you get a ClassCastException
at run-time!!!
This should convince you to always use typesafe generic types in new code. Always.
You can use
npm run env NODE_ENV=production
It is probably the best way to do it, because it's compatible on both Windows and Unix.
From the npm run-script documentation:
The env script is a special built-in command that can be used to list environment variables that will be available to the script at runtime. If an "env" command is defined in your package it will take precedence over the built-in.
This will get the 'floor' of a datetime
object stored in tm rounded to the 10 minute mark before tm
.
tm = tm - datetime.timedelta(minutes=tm.minute % 10,
seconds=tm.second,
microseconds=tm.microsecond)
If you want classic rounding to the nearest 10 minute mark, do this:
discard = datetime.timedelta(minutes=tm.minute % 10,
seconds=tm.second,
microseconds=tm.microsecond)
tm -= discard
if discard >= datetime.timedelta(minutes=5):
tm += datetime.timedelta(minutes=10)
or this:
tm += datetime.timedelta(minutes=5)
tm -= datetime.timedelta(minutes=tm.minute % 10,
seconds=tm.second,
microseconds=tm.microsecond)
"What is a “
static
” function in C?"
Let's start at the beginning.
It´s all based upon a thing called "linkage":
"An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. 29)There are three kinds of linkage: external, internal, and none."
Source: C18, 6.2.2/1
"In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity."
Source: C18, 6.2.2/2
If a function is defined without a storage-class specifier, the function has extern
al linkage by default:
"If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern."
Source: C18, 6.2.2/5
That means that - if your program is contained of several translation units/source files (.c
or .cpp
) - the function is visible in all translation units/source files your program has.
This can be a problem in some cases. What if you want to use f.e. two different function (definitions), but with the same function name in two different contexts (actually the file-context).
In C and C++, the static
storage-class qualifier applied to a function at file scope (not a static member function of a class in C++ or a function within another block) now comes to help and signifies that the respective function is only visible inside of the translation unit/source file it was defined in and not in the other TLUs/files.
"If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage. 30)"
- A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.
Source: C18, 6.2.2/3
Thus, A static
function only makes sense, iff:
.c
or .cpp
).and
If not both of these requirements match, you don't need to wrap your head around about qualifying a function as static
.
Side Notes:
static
function has absolutely no difference at all between C and C++, as this is a feature C++ inherited from C.It does not matter that in the C++ community, there is a heartbreaking debate about the depreciation of qualifying functions as static
in comparison to the use of unnamed namespaces instead, first initialized by a misplaced paragraph in the C++03 standard, declaring the use of static functions as deprecated which soon was revised by the committee itself and removed in C++11.
This was subject to various SO questions:
Unnamed/anonymous namespaces vs. static functions
Superiority of unnamed namespace over static?
Why an unnamed namespace is a "superior" alternative to static?
Deprecation of the static keyword... no more?
In fact, it is not deprecated per C++ standard yet. Thus, the use of static
functions is still legit. Even if unnamed namespaces have advantages, the discussion about using or not using static functions in C++ is subject to one´s one mind (opinion-based) and with that not suitable for this website.
slight improvement on @LukeH, there is no need to repeat the "INSERT INTO": and @realPT's answer - no need to have the SELECT:
DECLARE @MyList TABLE (Value INT)
INSERT INTO @MyList VALUES (1),(2),(3),(4)
SELECT * FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)
This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:
public <T extends Animal> void addFriend(String name, Class<T> type, T animal);
public <T extends Animal> T callFriend(String name, Class<T> type);
Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.
ResponseEntity
is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody
is a marker for the HTTP response body and @ResponseStatus
declares the status code of the HTTP response.
@ResponseStatus
isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse
or a HttpHeaders
parameter.
Basically, ResponseEntity
lets you do more.
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values
i have tried the best way and less code but may be it is little bit difficult to understand how i wrote my code but if you good at maths it is so easy
import java.util.Scanner;
class hours {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s;
System.out.println("how many second you have ");
s =input.nextInt();
double h=s/3600;
int h2=(int)h;
double h_h2=h-h2;
double m=h_h2*60;
int m1=(int)m;
double m_m1=m-m1;
double m_m1s=m_m1*60;
System.out.println(h2+" hours:"+m1+" Minutes:"+Math.round(m_m1s)+" seconds");
}
}
more over it is accurate !
I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l
the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a
.
Improving on the answer of @Adiii - It Will Cleanup The Phone Number and Remove All Duplicates
Declare a Global Variable
// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();
Then Use The Function Below
private void getPhoneNumbers() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// Loop Through All The Numbers
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Cleanup the phone number
phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");
// Enter Into Hash Map
namePhoneMap.put(phoneNumber, name);
}
// Get The Contents of Hash Map in Log
for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
String key = entry.getKey();
Log.d(TAG, "Phone :" + key);
String value = entry.getValue();
Log.d(TAG, "Name :" + value);
}
phones.close();
}
Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282
I use launch4j
ANT Command:
<target name="jar" depends="compile, buildDLLs, copy">
<jar basedir="${java.bin.dir}" destfile="${build.dir}/Project.jar" manifest="META-INF/MANIFEST.MF" />
</target>
<target name="exe" depends="jar">
<exec executable="cmd" dir="${launch4j.home}">
<arg line="/c launch4jc.exe ${basedir}/${launch4j.dir}/L4J_ProjectConfig.xml" />
</exec>
</target>
Lets assume that you want an UIAlertAction with main title, two actions (save and discard) and cancel button:
let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
//Add Cancel-Action
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
//Add Save-Action
actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Save action...")
}))
//Add Discard-Action
actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
print("handle Discard action ...")
}))
//present actionSheetController
presentViewController(actionSheetController, animated: true, completion: nil)
This works for swift 2 (Xcode Version 7.0 beta 3)
I usually use
#define INFINITY (1e999)
or
const double INFINITY = 1e999
which works at least in IEEE 754 contexts because the highest representable double value is roughly 1e308
. 1e309
would work just as well, as would 1e99999
, but three nines is sufficient and memorable. Since this is either a double literal (in the #define
case) or an actual Inf
value, it will remain infinite even if you're using 128-bit (“long double”) floats.
var myObject = new Object();_x000D_
myObject["firstname"] = "Gareth";_x000D_
myObject["lastname"] = "Simpson";_x000D_
myObject["age"] = 21;_x000D_
_x000D_
var size = JSON.stringify(myObject).length;_x000D_
_x000D_
document.write(size);
_x000D_
JSON.stringify(myObject)
_x000D_
You need to use the Disposable Pattern like this:
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose any managed objects
// ...
}
// Now disposed of any unmanaged objects
// ...
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Destructor
~YourClassName()
{
Dispose(false);
}
Answer above is missing an example which might not be obvious (it wasn't to me).
Url could be broken down into parts
https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
\_____/\________/ \_______________________________________/
| | |
Account name | Hash of revision
Project name
Hash can be found here (you can click it and will get the url from browser).
Hope this saves you some time.
ahaliav fox 's answer is correct, however there's a small coding problem.
Change
<%=Button1.UniqueId%>
to
<%=Button1.UniqueID%>
it is case sensitive. Control.UniqueID Property
Error 14 'System.Web.UI.WebControls.Button' does not contain a definition for 'UniqueId' and no extension method 'UniqueId' accepting a first argument of type 'System.Web.UI.WebControls.Button' could be found (are you missing a using directive or an assembly reference?)
N.b. I tried the TextChanged
event myself on AutoPostBack
before searching for the answer, and although it is almost right it doesn't give the desired result I wanted nor for the question asked. It fires on losing focus on the Textbox
and not when pressing the return key.
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
Because you probably did not identify the remote git repository to your terminal first.
git remote set-url origin https://github.com/MyRepo/project.git
and then,
git add .
git commit -m "force push"
git push origin master --force
declare @OrderByCmd nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd
Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor]
attribute to the constructor that you want Json.Net to call.
[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
...
}
It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]
) to populate the object after constructing it.
If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:
class ResultConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Result));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load the JSON for the Result into a JObject
JObject jo = JObject.Load(reader);
// Read the properties which will be used as constructor parameters
int? code = (int?)jo["Code"];
string format = (string)jo["Format"];
// Construct the Result object using the non-default constructor
Result result = new Result(code, format);
// (If anything else needs to be populated on the result object, do that here)
// Return the result
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, add the converter to your serializer settings, and use the settings when you deserialize:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);
109 - mon dd yyyy (In SQL conversion)
The required format is April 1 2009
so
SELECT DATENAME(MONTH, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 109), 9)
Result is:
var number = parseInt($(this).find('.number').text());
var current = 600;
if (current > number)
{
// do something
}
select distinct title, (
select count(title)
from kmovies as sub
where sub.title=kmovies.title) as cnt
from kmovies
group by title
order by cnt desc
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
One approach that works from pretty much anywhere, including from places where you don't have an Activity
or View
, is to grab a Handler
to the main thread and show the toast:
public void toast(final Context context, final String text) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
});
}
The advantage of this approach is that it works with any Context
, including Service
and Application
.
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
In TensorFlow Core v2.3.0, the following code should work.
import tensorflow as tf
visible_devices = tf.config.get_visible_devices()
for devices in visible_devices:
print(devices)
Depending on your environment, this code will produce flowing results.
PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU') PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')
An overlay is, simply put, a div
that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.
This will be your CSS for cross browser opacity of 0.5:
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
z-index: 10000;
}
This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.
var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)
For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.
Hope it helps!
Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..
static void Main()
{
for (int i=0; i<GetNames().Length; i++)
{
Console.WriteLine (GetNames()[i]);
}
}
static string[] GetNames()
{
string[] ret = {"Answer", "by", "Anonymous", "Pakistani"};
return ret;
}
A picture's worth a thousand words:
>>> class c:
pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
I realize this is an older question, but it comes up first in a Google search, and among the excellent answers provided, I didn't see anything fully comprehensive, so I did a little more digging and I ended up writing an enum class that not only allowed me to assign multiple custom values to the enum constants, I even added a method that allows me to assign values to them on the fly during code execution.
This enum class is for a "server" program that I run on a Raspberry Pi. The program receives commands from a client then it executes terminal commands that make adjustments to a webcam that is affixed to my 3D printer.
Using the Linux program 'v4l2-ctl' on the Pi, you can extract all of the possible adjustment commands for a given attached webcam, which also provides the setting datatype, the min and max values, the number of value steps in a given value range etc., so I took all of those and put them in an enum and created an enum interface that makes it easy to both set and get values for each command as well as a simple method to get the actual terminal command that is executed (using the Process and Runtime classes) in order to adjust the setting.
It is a rather large class and I apologize for that, but for me, it's always easier to learn something when I can see it working in full context, so I decided not to scale it down. However, even though it's large, it is definitely simple and it should be obvious what's happening in the class with minimal effort.
package constants;
import java.util.HashMap;
import java.util.Map;
public enum PICam {
BRIGHTNESS ("brightness", 0, "int", 0, 100, 1, 50),
CONTRAST ("contrast", 1, "int", 100, 100, 1, 0),
SATURATION ("saturation", 2, "int", 100, 100, 1, 0),
RED_BALANCE ("red_balance", 3, "intmenu", 1, 7999, 1, 1000),
BLUE_BALANCE ("blue_balance", 4, "int", 1, 7999, 1, 1000),
HORIZONTAL_FLIP ("horizontal_flip", 5, "bool", 0, 1, 1, 0),
VERTICAL_FLIP ("vertical_flip", 6, "bool", 0, 1, 1, 0),
POWER_LINE_FREQUENCY ("power_line_frequency", 7, "menu", 0, 3, 1, 1),
SHARPNESS ("sharpness", 8, "int", 100, 100, 1, 0),
COLOR_EFFECTS ("color_effects", 9, "menu", 0, 15, 1, 0),
ROTATE ("rotate", 10, "int", 0, 360, 90, 0),
COLOR_EFFECTS_CBCR ("color_effects_cbcr", 11, "int", 0, 65535, 1, 32896),
VIDEO_BITRATE_MODE ("video_bitrate_mode", 12, "menu", 0, 1, 1, 0),
VIDEO_BITRATE ("video_bitrate", 13, "int", 25000, 25000000, 25000, 10000000),
REPEAT_SEQUENCE_HEADER ("repeat_sequence_header", 14, "bool", 0, 1, 1, 0),
H264_I_FRAME_PERIOD ("h_264_i_frame_period", 15, "int", 0, 2147483647,1, 60),
H264_LEVEL ("h_264_level", 16, "menu", 0, 11, 1, 11),
H264_PROFILE ("h_264_profile", 17, "menu", 0, 4, 1, 4),
AUTO_EXPOSURE ("auto_exposure", 18, "menu", 0, 3, 1, 0),
EXPOSURE_TIME_ABSOLUTE ("exposure_time_absolute", 19, "int", 1, 10000, 1, 1000),
EXPOSURE_DYNAMIC_FRAMERATE ("exposure_dynamic_framerate", 20, "bool", 0, 1, 1, 0),
AUTO_EXPOSURE_BIAS ("auto_exposure_bias", 21, "intmenu", 0, 24, 1, 12),
WHITE_BALANCE_AUTO_PRESET ("white_balance_auto_preset", 22, "menu", 0, 9, 1, 1),
IMAGE_STABILIZATION ("image_stabilization", 23, "bool", 0, 1, 1, 0),
ISO_SENSITIVITY ("iso_sensitivity", 24, "intmenu", 0, 4, 1, 0),
ISO_SENSITIVITY_AUTO ("iso_sensitivity_auto", 25, "menu", 0, 1, 1, 1),
EXPOSURE_METERING_MODE ("exposure_metering_mode", 26, "menu", 0, 2, 1, 0),
SCENE_MODE ("scene_mode", 27, "menu", 0, 13, 1, 0),
COMPRESSION_QUALITY ("compression_quality", 28, "int", 1, 100, 1, 30);
private static final Map<String, PICam> LABEL_MAP = new HashMap<>();
private static final Map<Integer, PICam> INDEX_MAP = new HashMap<>();
private static final Map<String, PICam> TYPE_MAP = new HashMap<>();
private static final Map<Integer, PICam> MIN_MAP = new HashMap<>();
private static final Map<Integer, PICam> MAX_MAP = new HashMap<>();
private static final Map<Integer, PICam> STEP_MAP = new HashMap<>();
private static final Map<Integer, PICam> DEFAULT_MAP = new HashMap<>();
private static final Map<Integer, Integer> THIS_VALUE_MAP = new HashMap<>();
private static final String baseCommandLine = "/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=";
static {
for (PICam e: values()) {
LABEL_MAP.put(e.label, e);
INDEX_MAP.put(e.index, e);
TYPE_MAP.put(e.type, e);
MIN_MAP.put(e.min, e);
MAX_MAP.put(e.max, e);
STEP_MAP.put(e.step, e);
DEFAULT_MAP.put(e.defaultValue, e);
}
}
public final String label;
public final int index;
public final String type;
public final int min;
public final int max;
public final int step;
public final int defaultValue;
private PICam(String label, int index, String type, int min, int max, int step, int defaultValue) {
this.label = label;
this.index = index;
this.type = type;
this.min = min;
this.max = max;
this.step = step;
this.defaultValue = defaultValue;
}
public static void setValue(Integer index, Integer value) {
if (THIS_VALUE_MAP.containsKey(index)) THIS_VALUE_MAP.replace(index, value);
else THIS_VALUE_MAP.put(index, value);
}
public Integer getValue (Integer index) {
return THIS_VALUE_MAP.getOrDefault(index, null);
}
public static PICam getLabel(String label) {
return LABEL_MAP.get(label);
}
public static PICam getType(String type) {
return TYPE_MAP.get(type);
}
public static PICam getMin(int min) {
return MIN_MAP.get(min);
}
public static PICam getMax(int max) {
return MAX_MAP.get(max);
}
public static PICam getStep(int step) {
return STEP_MAP.get(step);
}
public static PICam getDefault(int defaultValue) {
return DEFAULT_MAP.get(defaultValue);
}
public static String getCommandFor(int index, int newValue) {
PICam picam = INDEX_MAP.get(index);
String commandValue = "";
if ("bool".equals(picam.type)) {
commandValue = (newValue == 0) ? "false" : "true";
}
else {
commandValue = String.valueOf(newValue);
}
return baseCommandLine + INDEX_MAP.get(index).label + "=" + commandValue;
}
public static String getCommandFor(PICam picam, Integer newValue) {
String commandValue = "";
if ("bool".equals(picam.type)) {
commandValue = (newValue == 0) ? "false" : "true";
}
else {
commandValue = String.valueOf(newValue);
}
return baseCommandLine + INDEX_MAP.get(picam.index).label + "=" + commandValue;
}
public static String getCommandFor(PICam piCam) {
int newValue = piCam.defaultValue;
String commandValue = "";
if ("bool".equals(piCam.type)) {
commandValue = (newValue == 0) ? "false" : "true";
}
else {
commandValue = String.valueOf(newValue);
}
return baseCommandLine + piCam.label + "=" + commandValue;
}
public static String getCommandFor(Integer index) {
PICam piCam = INDEX_MAP.get(index);
int newValue = piCam.defaultValue;
String commandValue = "";
if ("bool".equals(piCam.type)) {
commandValue = (newValue == 0) ? "false" : "true";
}
else {
commandValue = String.valueOf(newValue);
}
return baseCommandLine + piCam.label + "=" + commandValue;
}
}
Here are some ways that the class can be interacted with:
This code:
public static void test() {
PICam.setValue(0,127); //Set brightness to 125
PICam.setValue(PICam.SHARPNESS,143); //Set sharpness to 125
String command1 = PICam.getSetCommandStringFor(PICam.BRIGHTNESS); //Get command line string to include the brightness value that we previously set referencing it by enum constant.
String command2 = PICam.getSetCommandStringFor(0); //Get command line string to include the brightness value that we previously set referencing it by index number.
String command3 = PICam.getDefaultCamString(PICam.BRIGHTNESS); //Get command line string with the default value
String command4 = PICam.getSetCommandStringFor(PICam.SHARPNESS); //Get command line string with the sharpness value that we previously set.
String command5 = PICam.getDefaultCamString(PICam.SHARPNESS); //Get command line string with the default sharpness value.
System.out.println(command1);
System.out.println(command2);
System.out.println(command3);
System.out.println(command4);
System.out.println(command5);
}
Produces these results:
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=50
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=143
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=0
protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region Dynamically Show gridView header From data base
getAllheaderName();/*To get all Allowences master headerName*/
TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
txt_Days.Text = hidMonthsDays.Value;
#endregion
}
}
I'm aware this is late, but I agree with AlexKuznetsov's suggestion to script the database, rather than going through the hassle of purging the data from the tables. If the TRUNCATE
solution will not work, and you happen to have a large amount of data, issuing (logged) DELETE
statements might take a long time, and you'll be left with identifiers that have not been reseeded (i.e. an INSERT
statement into a table with an IDENTITY
column would get you an ID of 50000 instead of an ID of 1).
To script a whole database, in SSMS, right-click the database, then select TASKS
-> Generate scripts
:
Click Next
to skip the Wizard opening screen, and then select which objects you want to script:
In the Set scripting options
screen, you can pick settings for the scripting, like whether to generate 1 script for all the objects, or separate scripts for the individual objects, and whether to save the file in Unicode or ANSI:
The wizard will show a summary, which you can use to verify everything is as desired, and close by clicking on 'Finish'.
This is possible with window.localStorage
or window.sessionStorage
. The difference is that sessionStorage
lasts for as long as the browser stays open, localStorage
survives past browser restarts. The persistence applies to the entire web site not just a single page of it.
When you need to set a variable that should be reflected in the next page(s), use:
var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);
And in any page (like when the page has loaded), get it like:
var someVarName = localStorage.getItem("someVarKey");
.getItem()
will return null
if no value stored, or the value stored.
Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify
and JSON.parse
. Technically, whenever you call .setItem()
, it will call .toString()
on the value and store that.
MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage
isn't available.
It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).
References:
Storage
- https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/StoragelocalStorage
- https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorageJSON
- https://developer.mozilla.org/en-US/docs/JSONIf your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
The negative margin trick:
http://pastehtml.com/view/1dujbt3.html
Not elegant, I suppose, but it works in some cases.
You should use strftime
static method from datetime
class from datetime
module. Try:
import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")
$(OutDir) turned out to be a relative path in VS2013, so I had to combine it with $(ProjectDir) to achieve the desired effect:
xcopy /y /d "$(ProjectDir)External\*.dll" "$(ProjectDir)$(OutDir)"
BTW, you can easily debug the scripts by adding 'echo ' at the beginning and observe the expanded text in the build output window.
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
If you are using JPQL, use JOIN FETCH is the easiest way: http://www.objectdb.com/java/jpa/query/jpql/from#LEFT_OUTER_INNER_JOIN_FETCH_
SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
SearchView.OnQueryTextListener
has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
This is how you can implement abstract methods of the listener.
@Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView
.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
In an object oriented language the methods, and their access modifiers, declare the interface for that object. Between the constructor and the accessor and mutator methods it is possible for the developer to control access to the internal state of an object. If the variables are simply declared public then there is no way to regulate that access. And when we are using setters we can restrict the user for the input we need. Mean the feed for that very variable will come through a proper channel and the channel is predefined by us. So it's safer to use setters.
UIViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboardId"];
[self.navigationController pushViewController:vc animated:YES];
For exporting html to csv try following this example. More details and examples are available at the author's website.
Create a html2csv.js file and put the following code in it.
jQuery.fn.table2CSV = function(options) {
var options = jQuery.extend({
separator: ',',
header: [],
delivery: 'popup' // popup, value
},
options);
var csvData = [];
var headerArr = [];
var el = this;
//header
var numCols = options.header.length;
var tmpRow = []; // construct header avalible array
if (numCols > 0) {
for (var i = 0; i < numCols; i++) {
tmpRow[tmpRow.length] = formatData(options.header[i]);
}
} else {
$(el).filter(':visible').find('th').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
}
row2CSV(tmpRow);
// actual data
$(el).find('tr').each(function() {
var tmpRow = [];
$(this).filter(':visible').find('td').each(function() {
if ($(this).css('display') != 'none') tmpRow[tmpRow.length] = formatData($(this).html());
});
row2CSV(tmpRow);
});
if (options.delivery == 'popup') {
var mydata = csvData.join('\n');
return popup(mydata);
} else {
var mydata = csvData.join('\n');
return mydata;
}
function row2CSV(tmpRow) {
var tmp = tmpRow.join('') // to remove any blank rows
// alert(tmp);
if (tmpRow.length > 0 && tmp != '') {
var mystr = tmpRow.join(options.separator);
csvData[csvData.length] = mystr;
}
}
function formatData(input) {
// replace " with “
var regexp = new RegExp(/["]/g);
var output = input.replace(regexp, "“");
//HTML
var regexp = new RegExp(/\<[^\<]+\>/g);
var output = output.replace(regexp, "");
if (output == "") return '';
return '"' + output + '"';
}
function popup(data) {
var generator = window.open('', 'csv', 'height=400,width=600');
generator.document.write('<html><head><title>CSV</title>');
generator.document.write('</head><body >');
generator.document.write('<textArea cols=70 rows=15 wrap="off" >');
generator.document.write(data);
generator.document.write('</textArea>');
generator.document.write('</body></html>');
generator.document.close();
return true;
}
};
include the js files into the html page like this:
<script type="text/javascript" src="jquery-1.3.2.js" ></script>
<script type="text/javascript" src="html2CSV.js" ></script>
TABLE:
<table id="example1" border="1" style="background-color:#FFFFCC" width="0%" cellpadding="3" cellspacing="3">
<tr>
<th>Title</th>
<th>Name</th>
<th>Phone</th>
</tr>
<tr>
<td>Mr.</td>
<td>John</td>
<td>07868785831</td>
</tr>
<tr>
<td>Miss</td>
<td><i>Linda</i></td>
<td>0141-2244-5566</td>
</tr>
<tr>
<td>Master</td>
<td>Jack</td>
<td>0142-1212-1234</td>
</tr>
<tr>
<td>Mr.</td>
<td>Bush</td>
<td>911-911-911</td>
</tr>
</table>
EXPORT BUTTON:
<input value="Export as CSV 2" type="button" onclick="$('#example1').table2CSV({header:['prefix','Employee Name','Contact']})">
There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):
Run man tcpdump | less -Ip examples
to see some examples
Here’s a tcpdump filter for HTTP GET (GET
= 0x47
, 0x45
, 0x54
, 0x20
):
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
Here’s a tcpdump filter for HTTP POST (POST
= 0x50
, 0x4f
, 0x53
, 0x54
):
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
Monitor HTTP traffic including request and response headers and message body (source):
tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).
If you just want to see your DB & Tables then the esiest way is to use Stetho
. Pretty cool tool for every Android developer who uses SQLite
buit by Facobook developed
.
Steps to use the tool
'compile 'com.facebook.stetho:stetho:1.4.2'
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Stetho.initializeWithDefaults(this); setContentView(R.layout.activity_main); }
Now, build your application & When the app is running, you can browse your app database, by opening chrome in the url:
chrome://inspect/#devices
Screenshots of the same are as below_
ChromeInspact
Your DB
Hope this will help to all! :)
for (let i = 1; i <= 5; i++) {_x000D_
for (let j = 1; j <= i; j++) {_x000D_
document.write('*');_x000D_
}_x000D_
document.write('<br />');_x000D_
}
_x000D_
Try this:
new String(bytebuffer.array(), "ASCII");
NB. you can't correctly convert a byte array to a String without knowing its encoding.
I hope this helps
Yes, but you'll need to run it at the database level.
Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.
For Kotlin:
In your adapter, simply call
(context as Your_Activity_Name).yourMethod()
I think the current right way to do this is by pip
like Pramod comments
pip install beautifulsoup4
because of last changes in Python, see discussion here. This was not so in the past.
Hope this would help you:
public static object GetProperty(object o, string member)
{
if(o == null) throw new ArgumentNullException("o");
if(member == null) throw new ArgumentNullException("member");
Type scope = o.GetType();
IDynamicMetaObjectProvider provider = o as IDynamicMetaObjectProvider;
if(provider != null)
{
ParameterExpression param = Expression.Parameter(typeof(object));
DynamicMetaObject mobj = provider.GetMetaObject(param);
GetMemberBinder binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new CSharpArgumentInfo[]{CSharpArgumentInfo.Create(0, null)});
DynamicMetaObject ret = mobj.BindGetMember(binder);
BlockExpression final = Expression.Block(
Expression.Label(CallSiteBinder.UpdateLabel),
ret.Expression
);
LambdaExpression lambda = Expression.Lambda(final, param);
Delegate del = lambda.Compile();
return del.DynamicInvoke(o);
}else{
return o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
}
}
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
I concurr with @marc_s and @Adam_Poward -- DateTime2 is the preferred method moving forward. It has a wider range of dates, higher precision, and uses equal or less storage (depending on precision).
One thing the discussion missed, however...
@Marc_s states: Both types map to System.DateTime in .NET - no difference there
. This is correct, however, the inverse is not true...and it matters when doing date range searches (e.g. "find me all records modified on 5/5/2010").
.NET's version of Datetime
has similar range and precision to DateTime2
. When mapping a .net Datetime
down to the old SQL DateTime
an implicit rounding occurs. The old SQL DateTime
is accurate to 3 milliseconds. This means that 11:59:59.997
is as close as you can get to the end of the day. Anything higher is rounded up to the following day.
Try this :
declare @d1 datetime = '5/5/2010 23:59:59.999'
declare @d2 datetime2 = '5/5/2010 23:59:59.999'
declare @d3 datetime = '5/5/2010 23:59:59.997'
select @d1 as 'IAmMay6BecauseOfRounding', @d2 'May5', @d3 'StillMay5Because2msEarlier'
Avoiding this implicit rounding is a significant reason to move to DateTime2. Implicit rounding of dates clearly causes confusion:
You want to set style
margin: auto;
And remove the positioning styles (top, left, position)
I know this will center horrizontaly but I'm not sure about vertical!
For the particular case of Windows 10 October 2018 Update or later activedirectory
module is not available unless the optional feature RSAT: Active Directory Domain Services and Lightweight Directory Services Tools
is installed (instructions here + uncollapse install instructions).
Reopen Windows Powershell and import-module activedirectory
will work as expected.
In compact edition will take size automatically for datetime data type i.e. (8) so no need to set size of field and generate error for this operation...
To serialize usin NEWTONSOFTJSON when you have loop issue, in my case I did not need modify global.asax or either apiconfig. I just use JsonSerializesSettings ignoring Looping handling.
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
When searching folders where you might get an error based on security (e.g. C:\Users
), use the following command:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
$test = "{'employees':[{'firstName':'John', 'lastName':'Doe'},{'firstName':'John', 'lastName':'Doe'}]}" ;
$test = str_replace("'", '"', $test);
echo $test;
$jtest = json_decode($test,true);
var_dump($jtest);
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS
I would try to call
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
after you call setAdapter(). Also try out calling before the adapter.
You always have the solution to go with subclassing, where you can wrap a boolean flag to your overriden setAdapter method to skip the event.
You can use indexOf
:
var imageList = [100,200,300,400,500];
var index = imageList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file
You can simply Create a logout button and add this link to it and it will utimately log you out from the app and will redirect to your desired site:
https://appengine.google.com/_ah/logout?continue=http://www.YOURSITE.com
just toggle YOURSITE with your website
You can get the value $value
as :
$value = $_POST['subject'];
or:
$value = $_GET['subject'];
,depending upon the form method used.
session_start();
$_SESSION['subject'] = $value;
the value is assigned to session variable subject.
.push()
is a method of the Built-in Array Object
It is not related to jQuery in any way.
You are defining a literal Object with
// Object
var stuff = {};
You can define a literal Array like this
// Array
var stuff = [];
then
stuff.push(element);
Arrays actually get their bracket syntax stuff[index]
inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.
This is often used for effortless reflection for dynamically accessing properties
stuff = {}; // Object
stuff['prop'] = 'value'; // assign property of an
// Object via bracket syntax
stuff.prop === stuff['prop']; // true
Similarly:
"".contains(""); // Returns true.
Therefore, it appears that an empty string is contained in any String
.
I think this would be best explained by the following picture:
To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
Use the timestamp you get by calling valueOf
on the date object:
var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h>
functions like strcat
or sprintf
.
I implemented a small library that is quite useful. It provides a ClientHttpRequestFactory
that can receive some context. By doing so, it allows to go through all client layers such as checking that query parameters are valued, headers set, and check that deserialization works well.
This might be a late response but in order to avoid using a loop you can also call the method recursively. It looks and feels slightly cleaner to me.
class ModelName < ActiveRecord::Base
before_create :generate_token
protected
def generate_token
self.token = SecureRandom.urlsafe_base64
generate_token if ModelName.exists?(token: self.token)
end
end
Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.
When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator
that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.
So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.
Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.
Logging has different levels such as :
Trace – A fine-grained debug message, typically capturing the flow through the application.
Debug- A general debugging event should be logged under this.
ALL – All events could be logged.
INFO- An informational purpose, information written in plain english.
Warn- An event that might possible lead to an error.
Error- An error in the application, possibly recoverable.
Logging captured with debug level is information helpful to developers as well as other personnel, so it captures in broad range. If your code doesn't have exception or errors then you should be alright to use DEBUG level of logging, otherwise you should carefully choose options.
def ruota_orario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento)[::-1] for elemento in ruota][::-1]
If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.
From the Package Explorer in Eclipse, you can right click the project, choose Build Path, Configure Build Path to get the build path dialog. From there you can remove the JRE reference for the 1.5 JRE and 'Add Library' to add a reference to your installed JRE.
Was missing the use of calc
in the answers, which is a cleaner solution.
#logo {
position: absolute;
left: calc(50% - 25px);
height: 50px;
width: 50px;
background: red;
}
Works in most modern browsers: http://caniuse.com/calc
Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.