Python is very sensitive to indentation, with the code below I got the same error:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
The correct indentation is:
except IntegrityError as e:
if 'unique constraint' in e.args:
return render(request, "calender.html")
check the round function and how does the length
argument works. It controls the behaviour of the precision of the result
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
This works for me:
SELECT * FROM table_name
ORDER BY RANDOM()
LIMIT [number]
I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1
PyCharm - Preferences - Project interpreter - Cog symbol - Show All
At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.
Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.
If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.
As far as I know there is not "an IDE" for Django, but there are some IDEs that support Django right out of the box, specifically the Django syntax for templates.
The name is Komodo, and it has a lot of features, but it's not cheap. If you are not worried about source control or debugging then there is a free version called Komodo Edit.
Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.
As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).
I send you an example with swiftmailer:
recipients: [email1, email2, email3]
your_service_name:
class: your_namespace
arguments: ["%recipients%"]
protected $recipients;
public function __construct($recipients)
{
$this->recipients = $recipients;
}
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
Use this code for that,
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest {
public static void main(String[] args) {
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);
for (String e : wordList) {
System.out.println(e);
}
}
}
You can't close sockets without shutting down the process that owns those sockets. Sockets are owned by the process that opened them. So to find out the process ID (PID) for Unix/Linux. Use netstat like so:
netstat -a -n -p -l
That will print something like:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1879/sendmail: acce
tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1860/xinetd
Where -a prints all sockets, -n shows the port number, -p shows the PID, -l shows only what's listening (this is optional depending on what you're after).
The real info you want is PID. Now we can shutdown that process by doing:
kill 1879
If you are shutting down a service it's better to use:
service sendmail stop
Kill literally kills just that process and any children it owns. Using the service command runs the shutdown script registered in the init.d directory. If you use kill on a service it might not properly start back up because you didn't shut it down properly. It just depends on the service.
Unfortunately, Mac is different from Linux/Unix in this respect. You can't use netstat. Read this tutorial if you're interested in Mac:
http://www.tech-recipes.com/rx/227/find-out-which-process-is-holding-which-socket-open/
And if you're on Windows use TaskManager to kill processes, and services UI to shutdown services. You can use netstat on Windows just like Linux/Unix to identify the PID.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/netstat.mspx?mfr=true
Best practice says to implement it by your own using local boolean field: http://www.niedermann.dk/2009/06/18/BestPracticeDisposePatternC.aspx
If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOf
or a regular expression to test the strings.
For the loop, you have at least three choices:
A boring old for
loop.
On ES5-enabled environments (or with a shim), Array#filter
.
Because you're using jQuery, jQuery.map
.
Boring old for
loop example:
function search(source, name) {
var results = [];
var index;
var entry;
name = name.toUpperCase();
for (index = 0; index < source.length; ++index) {
entry = source[index];
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
results.push(entry);
}
}
return results;
}
Where you'd call that with obj.list
as source
and the desired name fragment as name
.
Or if there's any chance there are blank entries or entries without names, change the if
to:
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
Array#filter
example:
function search(source, name) {
var results;
name = name.toUpperCase();
results = source.filter(function(entry) {
return entry.name.toUpperCase().indexOf(name) !== -1;
});
return results;
}
And again, if any chance that there are blank entries (e.g., undefined
, as opposed to missing; filter
will skip missing entries), change the inner return to:
return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;
jQuery.map
example (here I'm assuming jQuery
= $
as is usually the case; change $
to jQuery
if you're using noConflict
):
function search(source, name) {
var results;
name = name.toUpperCase();
results = $.map(source, function(entry) {
var match = entry.name.toUpperCase().indexOf(name) !== -1;
return match ? entry : null;
});
return results;
}
(And again, add entry && entry.name &&
in there if necessary.)
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
TextView
comes with 4 compound drawables, one for each of left, top, right and bottom.
In your case, you do not need the LinearLayout
and ImageView
at all. Just add android:drawableLeft="@drawable/up_count_big"
to your TextView
.
See TextView#setCompoundDrawablesWithIntrinsicBounds for more info.
Will open your pdf in a new tab with pdf viewer and can download too
<a className=""
href="/project_path_to_your_pdf_asset/failename.pdf"
target="_blank"
>
View PDF
</a>
Pot the following in your ~/.emacs
(or eqiuvalent)
(defun dos2unix ()
"Replace DOS eolns CR LF with Unix eolns CR"
(interactive)
(goto-char (point-min))
(while (search-forward "\r" nil t) (replace-match "")))
and then you would be able to simply use M-x dos2unix
.
https://github.com/cognitom/paper-css seems to solve all my needs.
Front-end printing solution - previewable and live-reloadable!
random.sample implement it.
>>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement
[4, 1, 5]
Just a comment on the method of accomplishing this:
You're making your EntryForm permanently tied to the form you're calling it from. I think it's better to not have forms tied to context like that. I'd remove the requery from the Save/Close routine and instead open the EntryForm modally, using the acDialog switch:
DoCmd.OpenForm "EntryForm", , ,"[ID]=" & Me!SubForm.Form!ID, , acDialog
Me!SubForm.Form.Requery
That way, EntryForm is not tied down to use in one context. The alternative is to complicate EntryForm with something that is knowledgable of which form opened it and what needs to requeried. I think it's better to keep that kind of thing as close to the context in which it's used, and keep the called form's code as simple as possible.
Perhaps a principle here is that any time you are requerying a form using the Forms collection from another form, it's a good indication something's not right about your architecture -- that should happen seldom, in my opinion.
Responding to your question about List<T>
:
List<T>
is a class; specifying an interface allows more flexibility of implementation. A better question is "why not IList<T>
?"
To answer that question, consider what IList<T>
adds to ICollection<T>
: integer indexing, which means the items have some arbitrary order, and can be retrieved by reference to that order. This is probably not meaningful in most cases, since items probably need to be ordered differently in different contexts.
If DB is SQL Server then
select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)
Using map.keySet()
, you can get a set of keys. Then convert this set into List
by:
List<String> l = new ArrayList<String>(map.keySet());
And then use l.get(int)
method to access keys.
PS:- source- Most concise way to convert a Set<String> to a List<String>
You don't need any date-specific functions for this, it's just string manipulation:
var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
Converter:
public class NullableToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Collapsed : Visibility.Visible;
}
}
Binding:
Visibility="{Binding PropertyToBind, Converter={StaticResource nullableToVisibilityConverter}}"
Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
and access values through t.Item1
and t.Item2
, you can simply do it like that:
(string message, int count) = ("Hello", 4);
or even:
(var message, var count) = ("Hello", 4);
for OS's that support select
:
import select
# your code
select.select([], [], [])
No need for a regex here, if you just want to replace a piece of string by another: using str_replace()
should be more than enough :
$new = str_replace(' ', '%20', $your_string);
But, if you want a bit more than that, and you probably do, if you are working with URLs, you should take a look at the urlencode()
function.
printStackTrace
is a method of the Throwable
class. This method displays error message in the console; where we are getting the exception in the source code. These methods can be used with catch block and they describe:
The three methods which describe the exception on the console (in which printStackTrace is one of them) are:
printStackTrace()
toString()
getMessage()
Example:
public class BabluGope {
public static void main(String[] args) {
try {
System.out.println(10/0);
} catch (ArithmeticException e) {
e.printStackTrace();
// System.err.println(e.toString());
//System.err.println(e.getMessage());
}
}
}
Hmm, it looks to me like CURLOPT_TIMEOUT
defines the amount of time that any cURL function is allowed to take to execute. I think you should actually be looking at CURLOPT_CONNECTTIMEOUT
instead, since that tells cURL the maximum amount of time to wait for the connection to complete.
Use this function or some like that. :)
function createMatrix(line, col, defaultValue = 0){
return new Array(line).fill(defaultValue).map((x)=>{ return new Array(col).fill(defaultValue); return x; });
}
var myMatrix = createMatrix(9,9);
This is pretty easy to do using LINQ:
var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
// Element doesn't exist
}
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
Again in this issue also I found Instant Run buggy. When I disable the Instant run and run the app again App starts successfully installing in the Device without showing any error Window. I hope google will sort out these Issues with Instant run soon.
Steps to disable Instant Run from Android Studio:
File > Settings > Build,Execution,Deployment > Instant Run > Un-check (Enable Instant Run to hot swap code)
EDIT
I want to add the reason that your IF
statement seems to not work. When you do an EXISTS
on an aggregate, it's always going to be true
. It returns a value even if the ID
doesn't exist. Sure, it's NULL
, but its returning it. Instead, do this:
if exists(select 1 from table where id = 4)
and you'll get to the ELSE
portion of your IF
statement.
Now, here's a better, set-based solution:
update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid
This has the benefit of being able to run on the entire table rather than individual ids.
Note quite as clean, but:
import csv
with open("value.txt", "r") as f:
csv_reader = reader(f)
num = ' '
for row in csv_reader:
print num, '\t'.join(row)
if num == ' ':
num=0
num=num+1
Not as compact, but it does the job:
Date price factor_1 factor_2
1 2012-06-11 1600.20 1.255 1.548
2 2012-06-12 1610.02 1.258 1.554
3 2012-06-13 1618.07 1.249 1.552
4 2012-06-14 1624.40 1.253 1.556
5 2012-06-15 1626.15 1.258 1.552
6 2012-06-16 1626.15 1.263 1.558
7 2012-06-17 1626.15 1.264 1.572
Try jCounter, it has a customRange setting where you can specify the start and end number, it can count up as well including the fallback you want at the end.
just add in css
.ui-icon-closethick{
margin-top: -8px!important;
margin-left: -8px!important;
}
To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:
AllowSameSiteAttribute.cs
public class AllowSameSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
if(response != null)
{
response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
//Add more headers...
}
base.OnActionExecuting(filterContext);
}
}
HomeController.cs
[AllowSameSite] //For the whole controller
public class UserController : Controller
{
}
or
public class UserController : Controller
{
[AllowSameSite] //For the method
public ActionResult Index()
{
return View();
}
}
mysql_fetch_array()
expects parameter 1 to be resource boolean given in php error on server if you get this error : please select all privileges on your server
. u will get the answer..
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)
<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// Smooth scrolling to element IDs
$('a[href^=#]:not([href=#])').on('click', function () {
var element = $($(this).attr('href'));
$('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
return false;
});
</script>
Requirements:
1. <a>
elements must have an href attribute that begin with #
and be more than just #
2. An element on the page with a matching id
attribute
What it does:
1. The function uses the href value to create the anchorID
object
- In the example, it's $('#contact')
, /about
starts with /
2. HTML
, and BODY
are animated to the top offset of anchorID
- speed = 'normal' ('fast','slow', milliseconds, )
- easing = 'swing' ('linear',etc ... google easing)
3. return false
-- it prevents the browser from showing the hash in the URL
- the script works without it, but it's not as "smooth".
If I'm not wrong, both functions are part of your class, you should use it like this:
class MyClass():
def __init__(self, filename):
self.filename = filename
self.stat1 = None
self.stat2 = None
self.stat3 = None
self.stat4 = None
self.stat5 = None
self.parse_file()
def parse_file(self):
#do some parsing
self.stat1 = result_from_parse1
self.stat2 = result_from_parse2
self.stat3 = result_from_parse3
self.stat4 = result_from_parse4
self.stat5 = result_from_parse5
replace your line:
parse_file()
with:
self.parse_file()
I was facing the same issue while setting up ssh for gitlab. I already have ssh for github
and i could not overwrite that.
The steps that worked for me are :
ssh-add /path/to/new/id_rsa
.config
in ~/.ssh/
using. I used vi ~/.ssh/config/
.# GitLab.com server
Host gitlab.com
RSAAuthentication yes
IdentityFile /path/to/new/id_rsa
After that restart the terminal and try pushing, it should work
You can use Padding
widget in between those two widget or wrap those widgets with Padding
widget.
Update
SizedBox widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.
Ex:
Column(
children: <Widget>[
Widget1(),
SizedBox(height: 10),
Widget2(),
],
),
List of tuple and {} can be used to remove duplicates
>>> [list(tupl) for tupl in {tuple(item) for item in k }]
[[1, 2], [5, 6, 2], [3], [4]]
>>>
I think that's better to use flex boxes (compatibility) than the absolute position. Here's example from me in pure css.
.container{_x000D_
background-color:green;_x000D_
height:500px;_x000D_
_x000D_
/*FLEX BOX */_x000D_
display: -ms-flexbox;_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
-ms-flex-direction: column;_x000D_
flex-direction: column;_x000D_
-webkit-flex-wrap: nowrap;_x000D_
-ms-flex-wrap: nowrap;_x000D_
flex-wrap: nowrap;_x000D_
-webkit-justify-content: flex-start;_x000D_
-ms-flex-pack: start;_x000D_
justify-content: flex-start;_x000D_
-webkit-align-content: stretch;_x000D_
-ms-flex-line-pack: stretch;_x000D_
align-content: stretch;_x000D_
-webkit-align-items: flex-start;_x000D_
-ms-flex-align: start;_x000D_
align-items: flex-start;_x000D_
}_x000D_
_x000D_
.elem1{_x000D_
background-color:red;_x000D_
padding:20px;_x000D_
_x000D_
/*FLEX BOX CHILD */_x000D_
-webkit-order: 0;_x000D_
-ms-flex-order: 0;_x000D_
order: 0;_x000D_
-webkit-flex: 0 1 auto;_x000D_
-ms-flex: 0 1 auto;_x000D_
flex: 0 1 auto;_x000D_
-webkit-align-self: flex-end;_x000D_
-ms-flex-item-align: end;_x000D_
align-self: flex-end;_x000D_
_x000D_
}
_x000D_
<div class="container">_x000D_
TOP OF CONTAINER _x000D_
<div class="elem1">_x000D_
Nam pretium turpis et arcu. Sed a libero. Sed mollis, eros et ultrices tempus, mauris ipsum aliquam libero, non adipiscing dolor urna a orci._x000D_
_x000D_
Mauris sollicitudin fermentum libero. Pellentesque libero tortor, tincidunt et, tincidunt eget, semper nec, quam. Quisque id mi._x000D_
_x000D_
Donec venenatis vulputate lorem. Maecenas ullamcorper, dui et placerat feugiat, eros pede varius nisi, condimentum viverra felis nunc et lorem. Curabitur vestibulum aliquam leo._x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can try the border-spacing property. That should do what you want. But you may want to see this answer.
From Python 3.2 you can use the decorator @lru_cache from the functools library. It's a Last Recently Used cache, so there is no expiration time for the items in it, but as a fast hack it's very useful.
from functools import lru_cache
@lru_cache(maxsize=256)
def f(x):
return x*x
for x in range(20):
print f(x)
for x in range(20):
print f(x)
Use the annotation @Deprecated
for your method, and you should also mention it in your javadocs.
Created a bat file with the below contents, it accepts the input for port number
@ECHO ON
set /p portid=Enter the Port to be killed:
echo %portid%
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr %portid% ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine
:SkipLine
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE
Finally click "Enter" to exit.
set ansi_nulls off go select * from table t inner join otherTable o on t.statusid = o.statusid go set ansi_nulls on go
This problem happens when xcode-select
developer directory was pointing to /Library/Developer/CommandLineTools
when a full regular Xcode was required (happens when CommandLineTools are installed after Xcode)
Solution:
/Applications
directory (NOT /Users/{user}/Applications
).xcode-select
to the Xcode app Developer directory using the following command:sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
Note: Make sure your Xcode app path is correct.
/Applications/Xcode.app/Contents/Developer
/Applications/Xcode-beta.app/Contents/Developer
The backslash ("\"
) character is a special escape character used to indicate other special characters such as new lines (\n
), tabs (\t
), or quotation marks (\"
).
If you want to include a backslash character itself, you need two backslashes or use the @
verbatim string:
var s = "\\Tasks";
// or
var s = @"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the @
verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine
utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
Similar answer, but I just wanted to make it available for an easy/quick test.
var input = $("<input>")_x000D_
.attr("name", "mydata").val("go Rafa!");_x000D_
_x000D_
$('#easy_test').append(input);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<form id="easy_test">_x000D_
_x000D_
</form>
_x000D_
In ES6, it is also possible to iterate over the values of an object using the for..of
loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:
for..of
loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.Here is an example:
const obj1 = {
a: 5,
b: "hello",
[Symbol.iterator]: function() {
const thisObj = this;
let index = 0;
return {
next() {
let keys = Object.keys(thisObj);
return {
value: thisObj[keys[index++]],
done: (index > keys.length)
};
}
};
}
};
Now we can use the for..of
loop:
for (val of obj1) {
console.log(val);
} // 5 hello
You should also consider PyCha http://www.lorenzogil.com/projects/pycha/
You can iterate using the index access,
To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase
method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
I'm with, Bruce. I AM using http://system.data.sqlite.org/ with great success as well. Here's a simple class example that I created:
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace MySqlLite
{
class DataClass
{
private SQLiteConnection sqlite;
public DataClass()
{
//This part killed me in the beginning. I was specifying "DataSource"
//instead of "Data Source"
sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
}
public DataTable selectQuery(string query)
{
SQLiteDataAdapter ad;
DataTable dt = new DataTable();
try
{
SQLiteCommand cmd;
sqlite.Open(); //Initiate connection to the db
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
ad = new SQLiteDataAdapter(cmd);
ad.Fill(dt); //fill the datasource
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
sqlite.Close();
return dt;
}
}
There is also an NuGet package: System.Data.SQLite available.
ONLY CSS POPUP LOGIC! TRY DO IT . EASY! I think this mybe be hack popular in future
<a href="#openModal">OPEN</a>
<div id="openModal" class="modalDialog">
<div>
<a href="#close" class="close">X</a>
<h2>MODAL</h2>
</div>
</div>
.modalDialog {
position: fixed;
font-family: Arial, Helvetica, sans-serif;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0,0,0,0.8);
z-index: 99999;
-webkit-transition: opacity 400ms ease-in;
-moz-transition: opacity 400ms ease-in;
transition: opacity 400ms ease-in;
display: none;
pointer-events: none;
}
.modalDialog:target {
display: block;
pointer-events: auto;
}
.modalDialog > div {
width: 400px;
position: relative;
margin: 10% auto;
padding: 5px 20px 13px 20px;
border-radius: 10px;
background: #fff;
background: -moz-linear-gradient(#fff, #999);
background: -webkit-linear-gradient(#fff, #999);
background: -o-linear-gradient(#fff, #999);
}
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
In some cases, you may run into a problem of synchronization with this method.
I wrote the callback call inside a setTimeout
function, and it worked synchronously just fine =)
E.G:
function obterJson(callback) {
jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {
setTimeout(function(){
callback(data);
},0);
}
Use @ColumnDefault()
annotation. This is hibernate only though.
I prefer PyQT although it is pretty big. It has all the features that normal QT has, and that's why it's very usable. I think you can use QML with it too.
Sure. On my (pretty vanilla) Cygwin setup, bash
is in c:\cygwin\bin
so I can run a bash
script (say testit.sh
) from a Windows batch file using a command like:
C:\cygwin\bin\bash testit.sh
... which can be included in a .bat
file as easily as it can be typed at the command line, and with the same effect.
Personally I think that the way to go is to rely on Perl's internal context to make the solution bullet-proof. A good regexp could match all the valid numeric values and none of the non-numeric ones (or vice versa), but as there is a way of employing the same logic the interpreter is using it should be safer to rely on that directly.
As I tend to run my scripts with -w
, I had to combine the idea of comparing the result of "value plus zero" to the original value with the no warnings
based approach of @ysth:
do {
no warnings "numeric";
if ($x + 0 ne $x) { return "not numeric"; } else { return "numeric"; }
}
I actually needed to do something pretty similar just now
Ended up writing a function which returns a list of tuples indicating the start
and end
of each month between two sets of dates so I could write some SQL queries off the back of it for monthly totals of sales etc.
I'm sure it can be improved by someone who knows what they're doing but hope it helps...
The returned value look as follows (generating for today - 365days until today as an example)
[ (datetime.date(2013, 5, 1), datetime.date(2013, 5, 31)),
(datetime.date(2013, 6, 1), datetime.date(2013, 6, 30)),
(datetime.date(2013, 7, 1), datetime.date(2013, 7, 31)),
(datetime.date(2013, 8, 1), datetime.date(2013, 8, 31)),
(datetime.date(2013, 9, 1), datetime.date(2013, 9, 30)),
(datetime.date(2013, 10, 1), datetime.date(2013, 10, 31)),
(datetime.date(2013, 11, 1), datetime.date(2013, 11, 30)),
(datetime.date(2013, 12, 1), datetime.date(2013, 12, 31)),
(datetime.date(2014, 1, 1), datetime.date(2014, 1, 31)),
(datetime.date(2014, 2, 1), datetime.date(2014, 2, 28)),
(datetime.date(2014, 3, 1), datetime.date(2014, 3, 31)),
(datetime.date(2014, 4, 1), datetime.date(2014, 4, 30)),
(datetime.date(2014, 5, 1), datetime.date(2014, 5, 31))]
Code as follows (has some debug stuff which can be removed):
#! /usr/env/python
import datetime
def gen_month_ranges(start_date=None, end_date=None, debug=False):
today = datetime.date.today()
if not start_date: start_date = datetime.datetime.strptime(
"{0}/01/01".format(today.year),"%Y/%m/%d").date() # start of this year
if not end_date: end_date = today
if debug: print("Start: {0} | End {1}".format(start_date, end_date))
# sense-check
if end_date < start_date:
print("Error. Start Date of {0} is greater than End Date of {1}?!".format(start_date, end_date))
return None
date_ranges = [] # list of tuples (month_start, month_end)
current_year = start_date.year
current_month = start_date.month
while current_year <= end_date.year:
next_month = current_month + 1
next_year = current_year
if next_month > 12:
next_month = 1
next_year = current_year + 1
month_start = datetime.datetime.strptime(
"{0}/{1}/01".format(current_year,
current_month),"%Y/%m/%d").date() # start of month
month_end = datetime.datetime.strptime(
"{0}/{1}/01".format(next_year,
next_month),"%Y/%m/%d").date() # start of next month
month_end = month_end+datetime.timedelta(days=-1) # start of next month less one day
range_tuple = (month_start, month_end)
if debug: print("Month runs from {0} --> {1}".format(
range_tuple[0], range_tuple[1]))
date_ranges.append(range_tuple)
if current_month == 12:
current_month = 1
current_year += 1
if debug: print("End of year encountered, resetting months")
else:
current_month += 1
if debug: print("Next iteration for {0}-{1}".format(
current_year, current_month))
if current_year == end_date.year and current_month > end_date.month:
if debug: print("Final month encountered. Terminating loop")
break
return date_ranges
if __name__ == '__main__':
print("Running in standalone mode. Debug set to True")
from pprint import pprint
pprint(gen_month_ranges(debug=True), indent=4)
pprint(gen_month_ranges(start_date=datetime.date.today()+datetime.timedelta(days=-365),
debug=True), indent=4)
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
I'm using react with TypeScript and the following worked for me
wrapper.find('input').getDOMNode<HTMLInputElement>().value = 'Hello';
wrapper.find('input').simulate('change');
Setting the value directly
wrapper.find('input').instance().value = 'Hello'`
was causing me a compile warning.
This can be done in IIS: http://weblogs.asp.net/joelvarty/archive/2009/03/23/force-ie7-compatibility-mode-in-ie8-with-iis-settings.aspx
Read the comments as well: Wednesday, April 01, 2009 8:57 AM by John Moore
A quick follow-up. This worked great for my site as long as I use the IE=EmulateIE7 value. Trying to use the IE=7 resulted in my site essentially hanging when run on IE8.
No, but you could open a web server at, for example, 127.0.0.77 and use it to check if the Request URI is "/welcome.aspx"... If yes redirect to google, if not load the original site.
127.0.0.77 mysite.com
When we compare C++ with Java, we see that C++ was not designed with implicit Garbage Collection in mind, while Java was.
Having things like arbitrary pointers in C-Style is not only bad for GC-implementations, but it would also destroy backward compatibility for a large amount of C++-legacy-code.
In addition to that, C++ is a language that is intended to run as standalone executable instead of having a complex run-time environment.
All in all: Yes it might be possible to add Garbage Collection to C++, but for the sake of continuity it is better not to do so.
>>you can write your code like
if (TextUtils.isEmpty(username)) {
editTextUserName.setError("Please enter username");
editTextUserName.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Enter a password");
editTextPassword.requestFocus();
return;
}
I liked the Brian answer:
function is_array(o){
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]') {
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
} else{
// may want to change return value to something more desirable
return -1;
}
}
but you could just do like this:
return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
I had this problem because I changed the name of the class in a model, and it did not match the name of the file.
"Model class names use CamelCase. These are singular, and will map automatically to the plural database table name.
Model files go in app/models/#{singular_model_name}.rb."
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e#model
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.
PHP_EOL is a predefined constant in PHP since PHP 4.3.10 and PHP 5.0.2. See the manual posting:
Using this will save you extra coding on cross platform developments.
IE.
$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);
If you looped through this twice you would see in 'somefile':
some data
some data
Use this instead:
<input id='tea-submit' type='submit' name = 'submit' value = 'Tea'>
<input id='coffee-submit' type='submit' name = 'submit' value = 'Coffee'>
This worked for me
/**
* Convert Date type to "YYYY/MM/DD" string
* - AKA ISO format?
* - It's logical and sortable :)
* - 20200227
* @param Date eg. new Date()
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
*/
static DateToYYYYMMDD(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
return DS
}
You can certainly add HH:MM something like this...
static DateToYYYYMMDD_HHMM(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
+ ' ' + ('0' + Date.getHours()).slice(-2)
+ ':' + ('0' + Date.getMinutes()).slice(-2)
return DS
}
you can just cast it
int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible
ah.. kent beat me to it :)
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
Try this:
$("#location").change(function(){
var element = $("option:selected", this);
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
In the callback function for change()
, this
refers to the select, not to the selected option.
Against all expectation, views are way slower in some circumstances.
I discovered this recently when I had problems with data which was pulled from Oracle which needed to be massaged into another format. Maybe 20k source rows. A small table. To do this we imported the oracle data as unchanged as I could into a table and then used views to extract data. We had secondary views based on those views. Maybe 3-4 levels of views.
One of the final queries, which extracted maybe 200 rows would take upwards of 45 minutes! That query was based on a cascade of views. Maybe 3-4 levels deep.
I could take each of the views in question, insert its sql into one nested query, and execute it in a couple of seconds.
We even found that we could even write each view into a temp table and query that in place of the view and it was still way faster than simply using nested views.
What was even odder was that performance was fine until we hit some limit of source rows being pulled into the database, performs just dropped off a cliff over the space of a couple of days - a few more source rows was all it took.
So, using queries which pull from views which pull from views is much slower than a nested query - which makes no sense for me.
You simply need to add that line legend: { display: false }
The solution for me was:
<mat-form-field>
<mat-select #monedaSelect formControlName="monedaDebito" [attr.disabled]="isLoading" [placeholder]="monedaLabel | async ">
<mat-option *ngFor="let moneda of monedasList" [value]="moneda.id">{{moneda.detalle}}</mat-option>
</mat-select>
TS:
@ViewChild('monedaSelect') public monedaSelect: MatSelect;
this.genericService.getOpciones().subscribe(res => {
this.monedasList = res;
this.monedaSelect._onChange(res[0].id);
});
Using object: {id: number, detalle: string}
You could put a _ViewStart.cshtml
file inside the /Views/Public
folder which would override the default one in the /Views
folder and specify the desired layout:
@{
Layout = "~/Views/Shared/_PublicLayout.cshtml";
}
By analogy you could put another _ViewStart.cshtml
file inside the /Views/Staff
folder with:
@{
Layout = "~/Views/Shared/_StaffLayout.cshtml";
}
You could also specify which layout should be used when returning a view inside a controller action but that's per action:
return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);
Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.
UPDATE:
As requested in the comments section here's an example of an action filter which would choose a master page:
public class LayoutInjecterAttribute : ActionFilterAttribute
{
private readonly string _masterName;
public LayoutInjecterAttribute(string masterName)
{
_masterName = masterName;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ViewResult;
if (result != null)
{
result.MasterName = _masterName;
}
}
}
and then decorate a controller or an action with this custom attribute specifying the layout you want:
[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
return View();
}
to make the string upper case -- just simply type
s.upper()
simple and easy! you can do the same to make it lower too
s.lower()
etc.
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html()
call will not serialize the event.
This should also work:
AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
EmailData clsEmailData = new EmailData();
List<EmailData> lstemail = new List<EmailData>();
clsEmailData.FirstName="JOhn";
clsEmailData.LastName ="Smith";
clsEmailData.Location ="Los Angeles"
lstemail.add(clsEmailData);
And, if you want to verify that you HAVEN'T broken your relationships and introduced orphans, once you have re-armed your checks, i.e.
ALTER TABLE foo CHECK CONSTRAINT ALL
or
ALTER TABLE foo CHECK CONSTRAINT FK_something
then you can run back in and do an update against any checked columns like so:
UPDATE myUpdatedTable SET someCol = someCol, fkCol = fkCol, etc = etc
And any errors at that point will be due to failure to meet constraints.
Dim
is short for Dimension and is used in VBA and VB6 to declare local variables.
Set on the other hand, has nothing to do with variable declarations. The Set
keyword is used to assign an object variable to a new object.
Hope that clarifies the difference for you.
Files will be deleted from your app's document directory when the user uninstalls the app. Knowing this, all you have to do is check whether a file exists as the first thing that happens in application:didFinishLaunchingWithOptions:
. Afterwards, unconditionally create the file (even if it's just a dummy file).
If the file did not exist at time of check, you know this is the first run since the latest install. If you need to know later in the app, save the boolean result to your app delegate member.
I've solved it, it can be done executing:
netsh interface portproxy add v4tov4 listenport=4422 listenaddress=192.168.1.111 connectport=80 connectaddress=192.168.0.33
To remove forwarding:
netsh interface portproxy delete v4tov4 listenport=4422 listenaddress=192.168.1.111
awk '{$1=$2="";$0=$0;$1=$1}1'
Input
a b c d
Output
c d
Pure Bash, without an extra process:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
This is my case: it's run Environment: AspNet Core 2.1 Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
create table my_table (
id_part1 int not null,
id_part2 int not null,
primary key (id_part1, id_part2)
)
Your document should not contain two divs with the same id. This is invalid HTML, and as a result, the underlying DOM API does not support it.
From the HTML standard:
id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.
You can either assign different ids to each div and select them both using $('#id1, #id2)
. Or assign the same class to both elements (.cls
for example), and use $('.cls')
to select them both.
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%Name%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
Try This .....
Consider using a table
if adding multiple screenshots and want to align them using tabular data for improved accessibility as shown here:
If your markdown parser supports it you could also add the role="presentation"
WIA-ARIA attribute to the TABLE element and omit the th
tags.
I hate the PostBuild step, it allows for too much stuff to happen outside of the build tool's purview. I believe that its better to let MSBuild manage the copy process, and do the updating. You can edit the .csproj file like this:
<Target Name="AfterBuild" Inputs="$(TargetPath)\**">
<Copy SourceFiles="$(TargetPath)\**" DestinationFiles="$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\**" OverwriteReadOnlyFiles="true"></Copy>
</Target>
As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.
It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
Note that this implementation is not synchronized.
ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");
If you absolutely need to only use one regex then
/(?=.*?(string1))(?=.*?(string2))/is
i modifier = case-insensitive
.*? Lazy evaluation for any character (matches as few as possible)
?= for Positive LookAhead it has to match somewhere
s modifier = .(period) also accepts line breaks
You can convert it to char* if you don't need a modifiable string by using:
(char*) yourString.c_str();
This would be very useful when you want to publish a String variable via MQTT in arduino.
You can bring this down to one single line of code if you use numpy:
a = [1,2,3,4,5,6,7]
b = [2,4,7,8,9,10,11,12]
sorted(np.unique(a+b))
>>> [1,2,3,4,5,6,7,8,9,10,11,12]
let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)
Use del /F /Q
to force deletion of read-only files (/F
) and directories and not ask to confirm (/Q
) when deleting via wildcard.
Open .dll
file with visual studio. Or resource editor.
You can use EXCEPT
syntax, for example:
SELECT var FROM table1
EXCEPT
SELECT var FROM table2
SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:
You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.
Lastly, it comes with SyncToyCmd
for creating and synchronizing folder pairs from the CLI or a Scheduled Task.
You can also separate creating a context manager (the __init__
method) and entering the context (the __enter__
method) to increase readability. So instead of writing this code:
with Company(name, id) as company, Person(name, age, gender) as person, Vehicle(brand) as vehicle:
pass
you can write this code:
company = Company(name, id)
person = Person(name, age, gender)
vehicle = Vehicle(brand)
with company, person, vehicle:
pass
Note that creating the context manager outside of the with
statement makes an impression that the created object can also be further used outside of the statement. If this is not true for your context manager, the false impression may counterpart the readability attempt.
The documentation says:
Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.
This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used.
RatingBar mRating=(RatingBar)findViewById(R.id.rating);
LayerDrawable layerDrawable=(LayerDrawable)mRating.getProgressDrawable();
layerDrawable.getDrawable(2).setColorFilter(Color.parseColor
("#32CD32"), PorterDuff.Mode.SRC_ATOP);
for me its working....
You should use as_json
method which converts ActiveRecord objects to Ruby Hashes despite its name
tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json
# You can now add new records and return the result as json by calling `to_json`
tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.
Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).
By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.
td {_x000D_
border: 1px black solid;_x000D_
padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
text-align: center;_x000D_
white-space: nowrap;_x000D_
vertical-align: middle;_x000D_
width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
-moz-transform: rotate(-90.0deg); /* FF3.5+ */_x000D_
-o-transform: rotate(-90.0deg); /* Opera 10.5 */_x000D_
-webkit-transform: rotate(-90.0deg); /* Saf3.1+, Chrome */_x000D_
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
margin-left: -10em;_x000D_
margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Q</td>_x000D_
<td>R</td>_x000D_
<td>S</td>_x000D_
<td>T</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.
Have fun playing around with this on jsFiddle.
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY. I did like that:
Supposing that I have 2 global variables (var1 and var2). Just add to the index.html header this code:
<script>
function getVar1() {
return 123;
}
function getVar2() {
return 456;
}
function getGlobal(varName) {
switch (varName) {
case 'var1': return 123;
case 'var2': return 456;
// ...
default: return 'unknown'
}
}
</script>
It's possible to do a method for each variable or use one single method with a parameter.
This solution works between different vuejs mixins, it a really global value.
requirements.txt
allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1
[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)
For Github that means you can do (notice the omitted -e
):
git+git://github.com/mozilla/elasticutils.git#egg=elasticutils
Why the extra answer?
I got somewhat confused by the -e
flag in the other answers so here's my clarification:
The -e
or --editable
flag means that the package is installed in <venv path>/src/SomeProject
and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject
it would otherwise be placed in.2
Documentation
[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.
[Original answer]:
It is pretty clear in the documentation. depends_on
decides the dependency and the order of container creation and links
not only does these, but also
Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.
For example, assuming the following docker-compose.yml
file:
web:
image: example/my_web_app:latest
links:
- db
- cache
db:
image: postgres:latest
cache:
image: redis:latest
With links
, code inside web
will be able to access the database using db:5432
, assuming port 5432 is exposed in the db
image. If depends_on
were used, this wouldn't be possible, but the startup order of the containers would be correct.
Probably because you can't have part of an iterable. Also, floats
are imprecise.
var StudentList = dbContext.Students.SqlQuery("Select * from Students where Email like '%gmail%'").ToList<Student>();
User can use this of like query in Linq and fill the student model.
There is another way...
header('Content-Type: text/plain; charset=utf-8');
This makes the whole page served as plain text... better is htmlspecialchars...
Hope this helps...
May be it is the problem of using len()
for an integer value.
does not posses the len attribute in Python.
Error as:I will give u an example:
number= 1
print(len(num))
Instead of use ths,
data = [1,2,3,4]
print(len(data))
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
I have a generous amount of data that's stored in my repo as individual JSON fragments. There's about 75,000 files sitting under a few directories and it's not really detrimental to performance.
Checking them in the first time was, obviously, a little slow.
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
The for
attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it.
for example
<li>
<label>{translate:blindcopy}</label>
<a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a>  
<input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />
</li>
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
If you want the driving distance/route (posting it here because this is the first result for the distance between two points on google but for most people the driving distance is more useful), you can use Google Maps Distance Matrix Service:
getDrivingDistanceBetweenTwoLatLong(origin, destination) {
return new Observable(subscriber => {
let service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(origin.lat, origin.long)],
destinations: [new google.maps.LatLng(destination.lat, destination.long)],
travelMode: 'DRIVING'
}, (response, status) => {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log('Error:', status);
subscriber.error({error: status, status: status});
} else {
console.log(response);
try {
let valueInMeters = response.rows[0].elements[0].distance.value;
let valueInKms = valueInMeters / 1000;
subscriber.next(valueInKms);
subscriber.complete();
}
catch(error) {
subscriber.error({error: error, status: status});
}
}
});
});
}
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
Creating an Empty Dataframe with known Column Name:
Names = ['Col1','ActivityID','TransactionID']
df = pd.DataFrame(columns = Names)
Creating a dataframe from csv:
df = pd.DataFrame('...../file_name.csv')
Creating a dynamic filter to subset a dtaframe
:
i = 12
df[df['ActivitiID'] <= i]
Creating a dynamic filter to subset required columns of dtaframe
df[df['ActivityID'] == i][['TransactionID','ActivityID']]
The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:
Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.
Since AngularJS 1.5 we should use $onInit
which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:
$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
//default state
$scope.name = '';
//all your init controller goodness in here
this.$onInit = function () {
$scope.name = 'Superhero';
}
});
The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope
event listener $on
. By knowing, that an event $on
binded on $rootScope
will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on
listener manually. A good place to put that stuff is $onDestroy
lifecycle function of an component:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope, $rootScope) {
var registerScope = null;
this.$onInit = function () {
//register rootScope event
registerScope = $rootScope.$on('someEvent', function(event) {
console.log("fired");
});
}
this.$onDestroy = function () {
//unregister rootScope event by calling the return function
registerScope();
}
});
Write it like this:
string[] files = Directory.GetFiles(@".\Archive", "*.zip");
. is for relative to the folder where you started your exe, and @ to allow \ in the name.
When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.
In order to get the folder where your .exe actually resides, use:
var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
If it's "all smushed together" you can often give the ol' "view source code" a try. Sometimes the dumps, messages and exceptions seem like they're just one long string when it turns out that the line breaks simply don't show. Especially XML trees.
Alternatively, I've once created a small little tool called InteractiveVarDump for this very purpose. It certainly has its limits but it can also be very convenient sometimes. Even though it was designed with PHP 5 in mind.
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
<?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
////////////// QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
$pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
//$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
$pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
$pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
$pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
// This shows the user what page they are on, and the total number of pages
$paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' ';
// If we are not on page 1 we can place the Back button
if ($pn != 1) {
$previous = $pn - 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
}
// Lay in the clickable numbers display here between the Back and Next links
$paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
// If we are not on the very last page we can place the Next button
if ($pn != $lastPage) {
$nextPage = $pn + 1;
$paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
}
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){
$id = $row["id"];
$firstname = $row["firstname"];
$country = $row["country"];
$outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';
} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
<div style="margin-left:64px; margin-right:64px;">
<h2>Total Items: <?php echo $nr; ?></h2>
</div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
<div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
<div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html>
Another alternative: use {}
inside quotation marks to easily create dynamic names. This is similar to other solutions but not exactly the same, and I find it easier.
library(dplyr)
library(tibble)
iris <- as_tibble(iris)
multipetal <- function(df, n) {
df <- mutate(df, "petal.{n}" := Petal.Width * n) ## problem arises here
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
iris
I think this comes from dplyr 1.0.0
but not sure (I also have rlang 4.7.0
if it matters).
@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:
DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]
OUTPUT:
(2 row(s) affected)
Rows ROWCOUNT
----------- -----------
2 1
(1 row(s) affected)
you get Rows
value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT
command affected 1 row
if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:
--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal int
DECLARE @PeachTotal int
SELECT @AppleTotal=0,@PeachTotal=0
BEGIN TRANSACTION
INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
COMMIT
SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char[] remove(char[] symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char[] copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
If you would like to use thumbnail through pure js/jquery no api, you can use this tool to capture a frame from the video and voila! Insert url thumb in which ever source you like.
Here is a code pen :
<img src="https://i.vimeocdn.com/video/531141496_640.jpg"` alt="" />
Here is the site to get thumbnail:
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
I had that problem and Xcode failed to compile on the device, but on simulator, it worked fine.
I solved with these steps:
And after that everything works fine.
An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.
json_callback({"a" : "b", "c" : "d"});
Next, create a reusable variable with global scope in your script to hold the returned JSON. This will make the returned JSON data available to all other functions in your script instead of just the callback function.
var myJSON;
Next comes a simple function to retrieve your json by script injection. Note that we can not use jQuery here to append the script to the document head, as IE does not support the jQuery .append method. The jQuery method commented out in the code below will work on other browsers that do support the .append method. It is included as a reference to show the difference.
function getLocalJSON(json_url){
var json_script = document.createElement('script');
json_script.type = 'text/javascript';
json_script.src = json_url;
json_script.id = 'json_script';
document.getElementsByTagName('head')[0].appendChild(json_script);
// $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}
Next is a short and simple callback function (with the same name as the jsonp wrapper) to get the json results data into the global variable.
function json_callback(response){
myJSON = response; // Clone response JSON to myJSON object
$('#json_script').remove(); // Remove json_script from the document
}
The json data can now be accessed by any functions of the script using dot notation. As an example:
console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console
This method may be a bit different from what you are used to seeing, but has many advantages. First, the same jsonp file can be loaded locally or from a server using the same functions. As a bonus, jsonp is already in a cross-domain friendly format and can also be easily used with REST type API's.
Granted, there are no error handling functions, but why would you need one? If you are unable to get the json data using this method, then you can pretty much bet you have some problems within the json itself, and I would check it on a good JSON validator.
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
Just use two Listboxes, one for header and other for data
for headers - set RowSource property to top row e.g. Incidents!Q4:S4
for data - set Row Source Property to Incidents!Q5:S10
But to make sure that your new row is accessible in the new table, you need to close the table:
DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);
The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")
In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.
Do it like Andrey shows.
class1 item = lst[index];
item.foo = bar;
If an URL pattern starts with /
, then it's relative to the context root. The /Admin/*
URL pattern would only match pages on http://localhost:8080/EMS2/Admin/*
(assuming that /EMS2
is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*
, so your URL pattern never matches.
You need to prefix your URL patterns with /faces/Html
as well like so:
<url-pattern>/faces/Html/Admin/*</url-pattern>
You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html
path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml
.
Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping>
with multiple <url-pattern>
entries:
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>
You need to make use of the begin
and end
method of the vector
class, which return the iterator referring to the first and the last element respectively.
using namespace std;
vector<string> myvector; // a vector of stings.
// push some strings in the vector.
myvector.push_back("a");
myvector.push_back("b");
myvector.push_back("c");
myvector.push_back("d");
vector<string>::iterator it; // declare an iterator to a vector of strings
int n = 3; // nth element to be found.
int i = 0; // counter.
// now start at from the beginning
// and keep iterating over the element till you find
// nth element...or reach the end of vector.
for(it = myvector.begin(); it != myvector.end(); it++,i++ ) {
// found nth element..print and break.
if(i == n) {
cout<< *it << endl; // prints d.
break;
}
}
// other easier ways of doing the same.
// using operator[]
cout<<myvector[n]<<endl; // prints d.
// using the at method
cout << myvector.at(n) << endl; // prints d.
The recommended way to do this is to use LocationClient
:
First, define location update interval values. Adjust this to your needs.
private static final int MILLISECONDS_PER_SECOND = 1000;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
Have your Activity
implement GooglePlayServicesClient.ConnectionCallbacks
, GooglePlayServicesClient.OnConnectionFailedListener
, and LocationListener
.
public class LocationActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {}
Then, set up a LocationClient
in the onCreate()
method of your Activity
:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}
Add the required methods to your Activity
; onConnected()
is the method that is called when the LocationClient
connects. onLocationChanged()
is where you'll retrieve the most up-to-date location.
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.w(TAG, "Location client connection failed");
}
@Override
public void onConnected(Bundle dataBundle) {
Log.d(TAG, "Location client connected");
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
@Override
public void onDisconnected() {
Log.d(TAG, "Location client disconnected");
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d(TAG, "Updated Location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()));
} else {
Log.d(TAG, "Updated location NULL");
}
}
Be sure to connect/disconnect the LocationClient
so it's only using extra battery when absolutely necessary and so the GPS doesn't run indefinitely. The LocationClient
must be connected in order to get data from it.
public void onResume() {
super.onResume();
mLocationClient.connect();
}
public void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
}
mLocationClient.disconnect();
super.onStop();
}
Get the user's location. First try using the LocationClient
; if that fails, fall back to the LocationManager
.
public Location getLocation() {
if (mLocationClient != null && mLocationClient.isConnected()) {
return mLocationClient.getLastLocation();
} else {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocationGPS != null) {
return lastKnownLocationGPS;
} else {
return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} else {
return null;
}
}
}
which python3
simply result in a path in which the interpreter settles down.
Most simple, most fail safe version, works with any bootstrap version.
Demo: http://jsfiddle.net/guya/24mmM/
Demo 2: Not dismissing when clicking inside the popover content http://jsfiddle.net/guya/fjZja/
Demo 3: Multiple popovers: http://jsfiddle.net/guya/6YCjW/
Simply calling this line will dismiss all popovers:
$('[data-original-title]').popover('hide');
Dismiss all popovers when clicking outside with this code:
$('html').on('click', function(e) {
if (typeof $(e.target).data('original-title') == 'undefined') {
$('[data-original-title]').popover('hide');
}
});
The snippet above attach a click event on the body. When the user click on a popover, it'll behave as normal. When the user click on something that is not a popover it'll close all popovers.
It'll also work with popovers that are initiated with Javascript, as opposed to some other examples that will not work. (see the demo)
If you don't want to dismiss when clicking inside the popover content, use this code (see link to 2nd demo):
$('html').on('click', function(e) {
if (typeof $(e.target).data('original-title') == 'undefined' && !$(e.target).parents().is('.popover.in')) {
$('[data-original-title]').popover('hide');
}
});
Please Add this into your gradle file
android {
...
defaultConfig {
...
multiDexEnabled true
}
}
AND also add the below dependency in your gradle
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
OR another option would be: In your manifest file add the MultiDexApplication package from the multidex support library in the application tag.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
It's called a self-invoked function.
What you are doing when you call (function(){})
is returning a function object. When you append ()
to it, it is invoked and anything in the body is executed. The ;
denotes the end of the statement, that's why the 2nd invocation fails.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
To avoid SQL injection the insert statement with be
$type = 'testing';
$name = 'john';
$description = 'whatever';
$stmt = $con->prepare("INSERT INTO contents (type, reporter, description) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $type , $name, $description);
$stmt->execute();
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
It requires a bit of rearranging, but when
does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3
stage is now two different stages. One that runs on the master branch and one that runs on anything else.
stage ('Test 3: Master') {
when { branch 'master' }
steps {
echo 'I only execute on the master branch.'
}
}
stage ('Test 3: Dev') {
when { not { branch 'master' } }
steps {
echo 'I execute on non-master branches.'
}
}
In addition, you can simply convert byte array
to Bitmap
.
var bmp = new Bitmap(new MemoryStream(imgByte));
You can also get Bitmap
from file Path directly.
Bitmap bmp = new Bitmap(Image.FromFile(filePath));
Throwing in another solution.
In my module's init.py I have something like:
# mymodule/__init__.py
import logging
def get_module_logger(mod_name):
logger = logging.getLogger(mod_name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
Then in each module I need a logger, I do:
# mymodule/foo.py
from [modname] import get_module_logger
logger = get_module_logger(__name__)
When the logs are missed, you can differentiate their source by the module they came from.
Do you want to sort all files in a folder and subfolder overriding them?
Use this:
find . -type f -exec sort {} -o {} \;
Oracle itself uses Y/N for Boolean values. For completeness it should be noted that pl/sql has a boolean type, it is only tables that do not.
If you are using the field to indicate whether the record needs to be processed or not you might consider using Y and NULL as the values. This makes for a very small (read fast) index that takes very little space.
Seems to be some relevent info here:
Converting MS Word Documents to PDF in ASP.NET
Also, with Office 2007 having publish to PDF functionality, I guess you could use office automation to open the *.DOC file in Word 2007 and Save as PDF. I'm not too keen on office automation as it's slow and prone to hanging, but just throwing that out there...
Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
Not specifically using -replace
, but you get the same effect parsing the content using -notmatch
and regex.
(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt
if (($("#one").length > 0)){
alert('yes');
}
if (($("#two").length > 0)){
alert('yes');
}
if (($("#three").length > 0)){
alert('yes');
}
if (($("#four")).length == 0){
alert('no');
}
This is what you need :)
you can always make a bash alias to setup*.exe files in $home/.bashrc
cygwin 32bit
alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"
cygwin 64bit
alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"
now you can install packages with
cyg-get <package>
If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.
View -> Layout -> Choose one option or use shortcut
Layout Shortcut
Single Alt + Shift + 1
Columns: 2 Alt + Shift + 2
Columns: 3 Alt + Shift + 3
Columns: 4 Alt + Shift + 4
Rows: 2 Alt + Shift + 8
Rows: 3 Alt + Shift + 9
Grid: 4 Alt + Shift + 5
using Dollar is simple as typing:
@Test
public void repeatString() {
String string = "abc";
assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}
PS: repeat works also for array, List, Set, etc
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.
Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.
For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.
I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
The jQuery constructor accepts a 2nd parameter called context
which can be used to override the context of the selection.
jQuery("img", this);
Which is the same as using .find()
like this:
jQuery(this).find("img");
If the imgs you desire are only direct descendants of the clicked element, you can also use .children()
:
jQuery(this).children("img");
a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:
protected function getFirstPosition(array$array, $content, $key = true) {
$index = 0;
if ($key) {
foreach ($array as $key => $value) {
if ($key == $content) {
return $index;
}
$index++;
}
} else {
foreach ($array as $key => $value) {
if ($value == $content) {
return $index;
}
$index++;
}
}
}
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
You can use:
const sha1 = require('sha1');
const crypt = sha1('Text');
console.log(crypt);
For install:
sudo npm install -g sha1
npm install sha1 --save
That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [
and ends with ]
with a comma at the end of each line, or parse it line by line as separate dictionaries.
Use a framework like JQuery to do things like:
function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
$('#idOfTheDIV :input').attr('disabled', true);
} else {
$('#idOfTheDIV :input').removeAttr('disabled');
}
}
Disable And Enable Input Elements In A Div Block Using jQuery should help you!
As of jQuery 1.6, you should use .prop
instead of .attr
for disabling.
http://docs.python.org/2/tutorial/classes.html#method-objects
Usually, a method is called right after it is bound:
x.f()
In the MyClass example, this will return the string 'hello world'. However, it is not necessary to call a method right away: x.f is a method object, and can be stored away and called at a later time. For example:
xf = x.f while True: print xf()
will continue to print hello world until the end of time.
What exactly happens when a method is called? You may have noticed that x.f() was called without an argument above, even though the function definition for f() specified an argument. What happened to the argument? Surely Python raises an exception when a function that requires an argument is called without any — even if the argument isn’t actually used...
Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
Use a font-awesome icon as the default icon of your navbar.
<span class="navbar-toggler-icon">
<i class="fas fa-bars" style="color:#fff; font-size:28px;"></i>
</span>
Or try this on old font-awesome versions:
<span class="navbar-toggler-icon">
<i class="fa fa-navicon" style="color:#fff; font-size:28px;"></i>
</span>
RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).
While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:
Microsoft Internet Explorer (Browser)
Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.
Microsoft Edge (Browser)
The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge
Chrome
It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.
Firefox (Browser)
After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.
Safari (Browser)
At least 80,000 characters will work. Testing was not tried beyond that.
Opera (Browser)
At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable,
copyable and pasteable URL in the location bar even at 190,000 characters.
Apache (Server)
Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.
Microsoft Internet Information Server (Server)
The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.
Perl HTTP::Daemon (Server)
Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.
There are two ways to set this up. If you have an SID, use this (older) format:
jdbc:oracle:thin:@[HOST][:PORT]:SID
If you have an Oracle service name, use this (newer) format:
jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE
Source: this OraFAQ page
The call to getConnection()
is correct.
Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar
in the classpath, where the number corresponds to the Java version you're using.
To see the public tables you can do
list tables
\dt
list table, view, and access privileges
\dp or \z
or just the table names
select table_name from information_schema.tables where table_schema = 'public';
Edit: Whoops, didn't check your question tags before answering.
Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).
If so, try runnung those queries with F5
You needed to do it like this:
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
Hope it helped.
The number
type has a step
value controlling which numbers are valid (along with max
and min
), which defaults to 1
. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step
).
Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:
<input type="number" step="0.01">
(I'd also set min=0
if it can only be positive)
If you'd prefer to allow any number of decimal places, you can use step="any"
(though for currencies, I'd recommend sticking to 0.01
). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any
. (thanks to Michal Stefanow's answer for pointing out any
, and see the relevant spec here)
Here's a playground showing how various steps affect various input types:
<form>_x000D_
<input type=number step=1 /> Step 1 (default)<br />_x000D_
<input type=number step=0.01 /> Step 0.01<br />_x000D_
<input type=number step=any /> Step any<br />_x000D_
<input type=range step=20 /> Step 20<br />_x000D_
<input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
<input type=datetime-local step=1 /> Step 1<br />_x000D_
<input type=datetime-local step=any /> Step any<br />_x000D_
<input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
<input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
<input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
<input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!
<table>
<tbody>
<tr><td>{{data[0].foo}}</td></tr>
<tr ng-repeat="d in data[1]"><td>{{d.bar}}</td></tr>
<tr ng-repeat="d in data[2]"><td>{{d.lol}}</td></tr>
</tbody>
</table>
I think that this is valid :)
the simpler, the better.
index.php
<?
if (empty($_SERVER['QUERY_STRING'])) {
$name="index";
} else {
$name=basename($_SERVER['QUERY_STRING']);
}
$file="txt/".$name.".htm";
if (is_readable($file)) {
include 'header.php';
readfile($file);
} else {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
header.php
<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br>
the actual static html pages stored in the txt
folder in the page
.htm format
Uninstall the older version of SDK from IntellJ IDEA -> Appearance -> System Settings -> Android SDK -> SDK platforms.
Install the new Android SDK version whatever version you want.
While installing the new SDK, uncheck the NDK checkbox under SDK tools.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = u"6Â 918Â 417Â 712"
s = s.replace(u"Â", "")
print s
This will print out 6 918 417 712
Just make sure that you have one root div and put everything inside this root
<div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>
and so on
Have you tried @Lazy
loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource
(until the JNDI vars have been setup).
N.B. I haven't had a chance to test this code yet!
@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myDataSource");
bean.setProxyInterface(DataSource.class);
//bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource)bean.getObject();
}
You may also need to add the @Lazy
annotation wherever the DataSource is being used. e.g.
@Lazy
@Autowired
private DataSource dataSource;
For future readers!
Starting from material components android 1.2.0-alpha01, you have slider
component
ex:
<com.google.android.material.slider.Slider
android:id="@+id/slider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:valueFrom="20f"
android:valueTo="70f"
android:stepSize="10" />
Using sets:
if set(("foo", "bar")).issubset(foo):
#do stuff
Alternatively:
if set(("foo", "bar")) <= set(foo):
#do stuff
Correct expression is
"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"