Have you tried git push? gitref.org has a nice section dealing with remote repositories.
You can also get help from the command line using the --help
option. For example:
% git push --help
GIT-PUSH(1) Git Manual GIT-PUSH(1)
NAME
git-push - Update remote refs along with associated objects
SYNOPSIS
git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
[--repo=<repository>] [-f | --force] [-v | --verbose] [-u | --set-upstream]
[<repository> [<refspec>...]]
...
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
form: NgForm;
form.reset()
This didn't work for me. It cleared the values but the controls raised an error.
But what worked for me was creating a hidden reset button and clicking the button when we want to clear the form.
<button class="d-none" type="reset" #btnReset>Reset</button>
And on the component, define the ViewChild and reference it in code.
@ViewChild('btnReset') btnReset: ElementRef<HTMLElement>;
Use this to reset the form.
this.btnReset.nativeElement.click();
Notice that the class d-none
sets display: none;
on the button.
You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart
is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize
is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1
and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET
item.
if you are using jQuery 1.6 and up, you want to use .prop() rather than .attr():
$('#abc_frame').prop('src', url)
See this question for an explanation of the differences.
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
I've used them as static variables for a function. For example, given the following C code:
int fn(int i)
{
static f = 1;
f += i;
return f;
}
I can implement the function similarly in Python:
def fn(i):
fn.f += i
return fn.f
fn.f = 1
This would definitely fall into the "abuses" end of the spectrum.
ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go
This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/
I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.
This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279
If you want to consider null values equality too, try the following
select column1, column2,
case
when column1 is NULL and column2 is NULL then 'true'
when column1=column2 then 'true'
else 'false'
end
from table;
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'
>> id(1)
1923344848 # identity of the location in memory where 1 is stored
>> id(1)
1923344848 # always the same
>> a = 1
>> b = a # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b) # equal to id(a)
1923344848
As you can see a
and b
are just two different names that reference to the same immutable object (int) 1
. If later you write a = 2
, you reassign the name a
to a different object (int) 2
, but the b
continues referencing to 1
:
>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880 # equal to id(2)
>> b
1 # b hasn't changed
>> id(b)
1923344848 # equal to id(1)
What would happen if you had a mutable object instead, such as a list [1]
?
>> id([1])
328817608
>> id([1])
328664968 # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800 # same as id(a)
Again, we are referencing to the same object (list) [1]
by two different names a
and b
. However now we can mutate this list while it remains the same object, and a
, b
will both continue referencing to it
>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800 # same as before
>> id(b)
328817800 # same as before
https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For <a>
elements, omit data-target, and use href="#modalID"
instead.
If you want to take just two numbers after comma you can use the Math Class that give you the round function for example :
float value = 92.197354542F;
value = (float)System.Math.Round(value,2); // value = 92.2;
Hope this Help
Cheers
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
The proper way to set the root logging level is using the property logging.level.root
. See documentation, which has been updated since this question was originally asked.
Example:
logging.level.root=WARN
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.
tl;dr; apply the a
and b
styles to the parent <div>
, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
System.IO.Path.GetRandomFileName()
Use a docstring:
A string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the
__doc__
special attribute of that object.All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the
__init__
constructor) should also have docstrings. A package may be documented in the module docstring of the__init__.py
file in the package directory.String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to
__doc__
), but two types of extra docstrings may be extracted by software tools:
- String literals occurring immediately after a simple assignment at the top level of a module, class, or
__init__
method are called "attribute docstrings".- String literals occurring immediately after another docstring are called "additional docstrings".
Please see PEP 258 , "Docutils Design Specification" [2] , for a detailed description of attribute and additional docstrings...
try
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
in terminal
Usually if I have to check which are the commits that differ from the master I do:
git rebase -i origin/master
In this way I can see the commits and decide to drop it or pick...
here is how to convert a listof dates to date
import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)
set STATICBUILD=true && pip install lxml
run this command instead, must have VS C++ compiler installed first
https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/
It works for me with Python 3.5.2 and Windows 7
Try this, seems the uniq function needs a sorted list to work properly.
use strict;
# Helper function to remove duplicates in a list.
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @teststrings = ("one", "two", "three", "one");
my @filtered = uniq @teststrings;
print "uniq: @filtered\n";
my @sorted = sort @teststrings;
print "sort: @sorted\n";
my @sortedfiltered = uniq sort @teststrings;
print "uniq sort : @sortedfiltered\n";
you just need to change the line color and you can apply it without problem
For me, the only way to reset the failed cherry-pick-attempt was
git reset --hard HEAD
foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}
same work you also can do with Contains
secondly Where
is give you new list of values.
thirdly using Exist
is not a good practice, you can achieve your target from Any
and contains
like
EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();
Hope this will clear your confusion.
Each thread in a process creates a directory under /proc/<pid>/task
. Count the number of directories, and you have the number of threads.
Use this style
<div class="form-control"
style="height:100px;
width:55%;
overflow:hidden;
cursor:pointer">
</div>
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse
class to show/hide divs and Bootstrap's "Collapse Event".
What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div>
based on, lets say, menu buttons on a navbar
. Below is a simple solution to this. The anchor tags (<a>
) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-
All that the JavaScript does is makes all the other <div>
hide using
$(".main-container.collapse").not($(this)).collapse('hide');
when the loaded <div>
is displayed by checking the Collapse event shown.bs.collapse
. Here's the Bootstrap documentation on Collapse Event.
Note: main-container
is just a custom class.
Here it goes-
$(".main-container.collapse").on('shown.bs.collapse', function () { _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
$(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
Thanks to @cwhisperer. I had the same issue with Doctrine in a Symfony app. I just added the option to my config.yml:
doctrine:
dbal:
driver: pdo_mysql
options:
# PDO::MYSQL_ATTR_INIT_COMMAND
1002: "SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))"
This worked fine for me.
Oracle has a page for this issue with SQL and trouble shooting suggestions.
"Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352
Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.
Macport packages tend to be maintained by a single person.
Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.
Both package managers will ask to be regularly updated. This can take some time.
Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.
Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
Have you tried overflow-y:auto
? It is not exactly what you want, as the scrollbar will appear only when needed.
Try out this,
My installation is at D:\xampp\htdocs\advanced
\Yii::$app->basePath
will give like D:\xampp\htdocs\advanced\backend
.
\Yii::$app->request->BaseUrl
will give like localhost\advanced\backend\web\
You may store the image using \Yii::$app->basePath
and show it using \Yii::$app->request->BaseUrl
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
For me, I have fixed the problem using android:layout_centerVertical="true"
in a parent RelativeLayout
:
<RelativeLayout ... >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerVertical="true">
</RelativeLayout>
Android Query can handle that for you and much more (like cache and loading progress).
Take a look at here.
I think is the best approach.
Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.
POINTERS
I had this problem and solved it by using pointer. I see that this wasn't your issue but I thought I'd mention it because I sure wish it had been here when I saw this an hour ago. My issue was about declaring a static member variable without defining it (the definition needed to come after some other set ups) and of course a pointer doesn't need a definition. Equally elementary mistake :P
In Rails I am using this gem : https://github.com/merchii/rack-iframe Bawically it sets a set of abbreviations without a reference file: https://github.com/merchii/rack-iframe/blob/master/lib/rack/iframe.rb#L8
It is easy to install when you dont care at all about the meaning of the p3p stuff.
In case you'd like to paste windows path from other source (say, File Explorer) - you can do so via input()
call in python console:
>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'
Then just copy the result
we can use different types of system fonts like below
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize:UIFont.smallSystemFontSize)
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize)
and your custom font like below
myButton.titleLabel?.font = UIFont(name: "Helvetica", size:12)
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
Use
require
when the file is required by your application, e.g. an important message template or a file containing configuration variables without which the app would break.
require_once
when the file contains content that would produce an error on subsequent inclusion, e.g.
function important() { /* important code */}
is definitely needed in your application but since functions cannot be redeclared should not be included again.
include
when the file is not required and application flow should continue when not found, e.g.
great for templates referencing variables from the current scope or something
include_once
optional dependencies that would produce errors on subsequent loading or maybe remote file inclusion that you do not want to happen twice due to the HTTP overhead
But basically, it's up to you when to use which.
You can enable java 1.8 support for android project.
Open Project Structure
Either by pressing Ctrl + Shift + Alt + S
Or File > Project Structure
Update the Source Compatibility and Target Compatibility to 1.8 in the Project Structure dialog as shown (click File > Project Structure).
Or you can use gradle
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Sync project. And that's it!
Note: Java 1.8 support can be enabled for Android Studio 3.0.0 or higher. See Documentation for further reading.
Alternatively you can use an implicit wait:
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange
event:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim clickRng As Range
Dim lastRow As Long
lastRow = Range("A1").End(xlDown).Row
Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A
If Not Intersect(Target, clickRng) Is Nothing Then
MyUserForm.Show //Launch custom userform
End If
End Sub
Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
import socket
def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: # not a valid address
return False
return True
def is_valid_ipv6_address(address):
try:
socket.inet_pton(socket.AF_INET6, address)
except socket.error: # not a valid address
return False
return True
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.Often data on webpages is in the form of an XML table. You can read an XML table into R using the package XML.
In this package, the function
readHTMLTable(<url>)
will look through a page for XML tables and return a list of data frames (one for each table found).
The question was what @_
means in Perl. The answer to that question is that, insofar as $_
means it in Perl, @_
similarly means they.
No one seems to have mentioned this critical aspect of its meaning — as well as theirs.
They’re consequently both used as pronouns, or sometimes as topicalizers.
They typically have nominal antecedents, although not always.
Here's a solution without Spring.
Constants are taken from org.hibernate.cfg.AvailableSettings
:
entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
archiverPersistenceUnitInfo(),
ImmutableMap.<String, Object>builder()
.put(JPA_JDBC_DRIVER, JDBC_DRIVER)
.put(JPA_JDBC_URL, JDBC_URL)
.put(DIALECT, Oracle12cDialect.class)
.put(HBM2DDL_AUTO, CREATE)
.put(SHOW_SQL, false)
.put(QUERY_STARTUP_CHECKING, false)
.put(GENERATE_STATISTICS, false)
.put(USE_REFLECTION_OPTIMIZER, false)
.put(USE_SECOND_LEVEL_CACHE, false)
.put(USE_QUERY_CACHE, false)
.put(USE_STRUCTURED_CACHE, false)
.put(STATEMENT_BATCH_SIZE, 20)
.build());
entityManager = entityManagerFactory.createEntityManager();
And the infamous PersistenceUnitInfo
private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
return new PersistenceUnitInfo() {
@Override
public String getPersistenceUnitName() {
return "ApplicationPersistenceUnit";
}
@Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
@Override
public DataSource getJtaDataSource() {
return null;
}
@Override
public DataSource getNonJtaDataSource() {
return null;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
return new Properties();
}
@Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public void addTransformer(ClassTransformer transformer) {
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
If it is a c-string (null-terminated array of type char), you can do something like:
#include <stdlib.h>
char str[] = "3.14159";
double num = atof(str);
If it is a C++ string, just use the c_str() method:
double num = atof( cppstr.c_str() );
atof() will convert the string to a double, returning 0 on failure. The function is documented here: http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html
You can do this way:
scp hostname@serverNameOrServerIp:/path/to/files/\\{file1,file2,file3\\}.fileExtension ./
This will download all the listed filenames to whatever local directory you're on.
Make sure not to put spaces between each filename only use a comma ,
.
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
Depending on your regex variant, you might be able to do simply this:
([\w-]+)
Also, you probably don't need the parentheses unless this is part of a larger expression.
As of February 2018, installing brew
on Ubuntu (mine is 17.10) machine is as simple as:
sudo apt install linuxbrew-wrapper
Then, on first brew
execution (just type brew --help
) you will be asked for two installation options:
me@computer:~/$ brew --help
==> Select the Linuxbrew installation directory
- Enter your password to install to /home/linuxbrew/.linuxbrew (recommended)
- Press Control-D to install to /home/me/.linuxbrew
- Press Control-C to cancel installation
[sudo] password for me:
For recommended option type your password (if your current user is in sudo
group), or, if you prefer installing all the dependencies in your own home folder, hit Ctrl+D. Enjoy.
Also, you can just call this for multi-value
$(<your select picker>).selectpicker("val", ["value1", "value2"])
You can find more here https://developer.snapappointments.com/bootstrap-select/methods/
It points to your top level output directory (which by default is target
):
EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:
If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.
project.build.sourceDirectory project.build.scriptSourceDirectory project.build.testSourceDirectory project.build.outputDirectory project.build.testOutputDirectory project.build.directory
sourceDirectory
,scriptSourceDirectory
, andtestSourceDirectory
provide access to the source directories for the project.outputDirectory
andtestOutputDirectory
provide access to the directories where Maven is going to put bytecode or other build output.directory
refers to the directory which contains all of these output directories.
I had similar problem. If no errors from pyinstaller try to change name of .exe file. It works for me
If you are running it locally and want to be able to step through the code:
python -m pdb script.py
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
# database Intraction
$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName;
User ID= YourUserID; Password= YourPassword"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
#End :database Intraction
clear
If you just need a shortcut, then it is Ctrl + Q on Linux (and Windows). Just hover the mouse on the method and press Ctrl + Q to see the doc.
This is your code
$q = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users');
Try this
$id = $q->result()[0]->id;
or this one, it's simpler
$id = $q->row()->id;
Add textColorHint property to your edit text
android:textColorHint="#F6F6F6"
or whichever color you want
Clone()
is used to copy only structure of data/array it doesn't copy the actual data.
CopyTo()
copies the structure as well as actual data.
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
Using Scipy's zscore function:
df = pd.DataFrame(np.random.randint(100, 200, size=(5, 3)), columns=['A', 'B', 'C'])
df
| | A | B | C |
|---:|----:|----:|----:|
| 0 | 163 | 163 | 159 |
| 1 | 120 | 153 | 181 |
| 2 | 130 | 199 | 108 |
| 3 | 108 | 188 | 157 |
| 4 | 109 | 171 | 119 |
from scipy.stats import zscore
df.apply(zscore)
| | A | B | C |
|---:|----------:|----------:|----------:|
| 0 | 1.83447 | -0.708023 | 0.523362 |
| 1 | -0.297482 | -1.30804 | 1.3342 |
| 2 | 0.198321 | 1.45205 | -1.35632 |
| 3 | -0.892446 | 0.792025 | 0.449649 |
| 4 | -0.842866 | -0.228007 | -0.950897 |
If not all the columns of your data frame are numeric, then you can apply the Z-score function only to the numeric columns using the select_dtypes
function:
# Note that `select_dtypes` returns a data frame. We are selecting only the columns
numeric_cols = df.select_dtypes(include=[np.number]).columns
df[numeric_cols].apply(zscore)
| | A | B | C |
|---:|----------:|----------:|----------:|
| 0 | 1.83447 | -0.708023 | 0.523362 |
| 1 | -0.297482 | -1.30804 | 1.3342 |
| 2 | 0.198321 | 1.45205 | -1.35632 |
| 3 | -0.892446 | 0.792025 | 0.449649 |
| 4 | -0.842866 | -0.228007 | -0.950897 |
Typescript projects (I have typescript in SFC vue components), need to set resolveJsonModule
compiler option to true
.
In tsconfig.json:
{
"compilerOptions": {
...
"resolveJsonModule": true,
...
},
...
}
Happy coding :)
(Source https://www.typescriptlang.org/docs/handbook/compiler-options.html)
You don't have to convert the object to a MyClass object because it already is. Wnat you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
String timestamp="";
Date temp=null;
try {
temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDateCurrentTimeZone(Long.parseLong(timestamp)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int dayMonth=temp.getDate();
int dayWeek=temp.getDay();
int hour=temp.getHours();
int minute=temp.getMinutes();
int month=temp.getMonth()+1;
int year=temp.getYear()+1900;
A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.
When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.
Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.
The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.
Again: draw the graph!.
I am using this:
loading = ProgressDialog.show(example.this,"",null, true, true);
Changing the casing to all lowercases worked for me.
It's already a string? Remove the getText() call.
int myNum = 0;
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
// Handle parse error.
}
You can use @TestPropertySource
to load different properties/yaml file
@TestPropertySource(locations="classpath:test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class MyIntTest{
}
OR if you want to override only specific properties/yaml you can use
@TestPropertySource(
properties = {
"spring.jpa.hibernate.ddl-auto=validate",
"liquibase.enabled=false"
}
)
Using
mapper.configure(
JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(),
true
);
See javadoc:
/**
* Feature that determines whether parser will allow
* JSON Strings to contain unescaped control characters
* (ASCII characters with value less than 32, including
* tab and line feed characters) or not.
* If feature is set false, an exception is thrown if such a
* character is encountered.
*<p>
* Since JSON specification requires quoting for all control characters,
* this is a non-standard feature, and as such disabled by default.
*/
Old option JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS
was deprecated since 2.10.
Please see also github thread.
I tried solutions mentioned here but It didn't help me. I mind the solution is layout_width
have to use wrap_content
as value.
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1" >
More or less same as above but concurrent using gevent :)
"""Gevent based crontab implementation"""
from datetime import datetime, timedelta
import gevent
# Some utility classes / functions first
def conv_to_set(obj):
"""Converts to set allowing single integer to be provided"""
if isinstance(obj, (int, long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item):
return True
allMatch = AllMatch()
class Event(object):
"""The Actual Event Class"""
def __init__(self, action, minute=allMatch, hour=allMatch,
day=allMatch, month=allMatch, daysofweek=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(minute)
self.hours = conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.daysofweek = conv_to_set(daysofweek)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t1):
"""Return True if this event should trigger at the specified datetime"""
return ((t1.minute in self.mins) and
(t1.hour in self.hours) and
(t1.day in self.days) and
(t1.month in self.months) and
(t1.weekday() in self.daysofweek))
def check(self, t):
"""Check and run action if needed"""
if self.matchtime(t):
self.action(*self.args, **self.kwargs)
class CronTab(object):
"""The crontab implementation"""
def __init__(self, *events):
self.events = events
def _check(self):
"""Check all events in separate greenlets"""
t1 = datetime(*datetime.now().timetuple()[:5])
for event in self.events:
gevent.spawn(event.check, t1)
t1 += timedelta(minutes=1)
s1 = (t1 - datetime.now()).seconds + 1
print "Checking again in %s seconds" % s1
job = gevent.spawn_later(s1, self._check)
def run(self):
"""Run the cron forever"""
self._check()
while True:
gevent.sleep(60)
import os
def test_task():
"""Just an example that sends a bell and asd to all terminals"""
os.system('echo asd | wall')
cron = CronTab(
Event(test_task, 22, 1 ),
Event(test_task, 0, range(9,18,2), daysofweek=range(0,5)),
)
cron.run()
You can add @PrimaryKey(autoGenerate = true)
like this:
@Entity
data class Food(
var foodName: String,
var foodDesc: String,
var protein: Double,
var carbs: Double,
var fat: Double
){
@PrimaryKey(autoGenerate = true)
var foodId: Int = 0 // or foodId: Int? = null
var calories: Double = 0.toDouble()
}
The If
style component is dangerous because the code block is always executed regardless of the condition. For example, this would cause a null exception if banner
is null
:
//dangerous
render: function () {
return (
<div id="page">
<If test={this.state.banner}>
<img src={this.state.banner.src} />
</If>
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
Another option is to use an inline function (especially useful with else statements):
render: function () {
return (
<div id="page">
{function(){
if (this.state.banner) {
return <div id="banner">{this.state.banner}</div>
}
}.call(this)}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
Another option from react issues:
render: function () {
return (
<div id="page">
{ this.state.banner &&
<div id="banner">{this.state.banner}</div>
}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:
$ rm -f abc.log.* # Remove them all
$ rm -f abc.log.2012* # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012
Regular expressions are more powerful than wildcards; you can feed the output of grep
to rm -f
. For example, if some of the file names start with "abc.log"
and some with "ABC.log"
, grep
lets you do a case-insensitive match:
$ rm -f $(ls | grep -i '^abc\.log\.')
This will cause problems if any of the file names contain funny characters, including spaces. Be careful.
When I do this, I run the ls | grep ...
command first and check that it produces the output I want -- especially if I'm using rm -f
:
$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)
where !!
expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f
command.
This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...)
syntax. You can use the equivalent backtick syntax:
$ rm -f `ls | grep -i '^abc\.log\.'`
The $(...)
syntax is easier to read, and if you're really ambitious it can be nested.
Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:
$ ls > list
$ vi list # Use your favorite text editor
I can then edit the list
file manually, leaving only the files I want to remove, and then:
$ rm -f $(<list)
or
$ rm -f `cat list`
(Again, this assumes none of the file names contain funny characters, particularly spaces.)
Or, when editing the list
file, I can add rm -f
to the beginning of each line and then:
$ . ./list
or
$ source ./list
Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar
to rm -f 'foo bar'
.
in some case you can use annotation @Primary.
@Primary
class USA implements Country {}
This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.
for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?
Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.
So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:
int *gnabber(){
static int foo[] = {1,2,3}
return foo;
}
Try download the zip files from http://www.nltk.org/nltk_data/ and then unzip, save in your Python folder, such as C:\ProgramData\Anaconda3\nltk_data
Use this link inside Ajax.BeginForm
@Html.ActionLink(
"Save",
"SaveAction",
null,
null,
onclick = "$(this).parents('form').attr('action', $(this).attr('href'));$(this).parents('form').submit();return false;" })
;)
It provides human readable version of output rather "Object": Example:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def Norm(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns
<__main__.Pet object at 0x029E2F90>
while code with "str" return something different
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns:
jax is a human
You can use this <View>
element just after the First TextView.
<View
android:layout_marginTop="@dimen/d10dp"
android:id="@+id/view1"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"/>
It's a modulo operation, except when it's an old-fashioned C-style string formatting operator, not a modulo operation. See here for details. You'll see a lot of this in existing code.
An old question, with a lot of answers, here's the steps I've recently followed reading the answers above, but in my case the problem was due to cifs resource sharing. This case is not reported previously, so hope it helps someone.
Try to force the lock mode on the connection opening with
final SQLiteConfig config = new SQLiteConfig();
config.setReadOnly(false);
config.setLockingMode(LockingMode.NORMAL);
connection = DriverManager.getConnection(url, config.toProperties());
If your using your SQLite db file over a NFS shared folder, check this point of the SQLite faq, and review your mounting configuration options to make sure your avoiding locks, as described here:
//myserver /mymount cifs username=*****,password=*****,iocharset=utf8,sec=ntlm,file,nolock,file_mode=0700,dir_mode=0700,uid=0500,gid=0500 0 0
I need to click the link who's href has substring "long" in it. How can I do this?
With the beauty of CSS selectors.
your statement would be...
driver.findElement(By.cssSelector("a[href*='long']")).click();
This means, in english,
Find me any 'a' elements, that have the
href
attribute, and that attributecontains
'long'
You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains
, starts with
, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html
In case you don't want/need to post:
@Html.ActionLink("link caption", "actionName", new { Model.Page }) // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);
[HttpGet]
public ActionResult actionName(int reportID)
{
Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)
Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
There are two ways to add one dictionary to another.
Update (modifies orig
in place)
orig.update(extra) # Python 2.7+
orig |= extra # Python 3.9+
Merge (creates a new dictionary)
# Python 2.7+
dest = collections.ChainMap(orig, extra)
dest = {k: v for d in (orig, extra) for (k, v) in d.items()}
# Python 3
dest = {**orig, **extra}
dest = {**orig, 'D': 4, 'E': 5}
# Python 3.9+
dest = orig | extra
Note that these operations are noncommutative. In all cases, the latter is the winner. E.g.
orig = {'A': 1, 'B': 2} extra = {'A': 3, 'C': 3} dest = orig | extra # dest = {'A': 3, 'B': 2, 'C': 3} dest = extra | orig # dest = {'A': 1, 'B': 2, 'C': 3}
It is also important to note that only from Python 3.7 (and CPython 3.6)
dict
s are ordered. So, in previous versions, the order of the items in the dictionary may vary.
Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.
To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse
function, parsing only namespace start events (start-ns):
>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
... xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
... xmlns:owl="http://www.w3.org/2002/07/owl#"
... xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
... xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
... xmlns="http://dbpedia.org/ontology/">
...
... <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
... <rdfs:label xml:lang="en">basketball league</rdfs:label>
... <rdfs:comment xml:lang="en">
... a group of sports teams that compete against each other
... in Basketball
... </rdfs:comment>
... </owl:Class>
...
... </rdf:RDF>'''
>>> my_namespaces = dict([
... node for _, node in ElementTree.iterparse(
... StringIO(my_schema), events=['start-ns']
... )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
'owl': 'http://www.w3.org/2002/07/owl#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'xsd': 'http://www.w3.org/2001/XMLSchema#'}
Then the dictionary can be passed as argument to the search functions:
root.findall('owl:Class', my_namespaces)
@Chris Noe
Note that the space in front of the & becomes part of the previous command. That has bitten me with SET, which happily puts trailing blanks into the value.
To get around the trailing-space being added to an environment variable, wrap the set command in parens.
E.g. FOR /F %%I IN ('DIR "*.*" /B /O:D') DO (SET NewestFile=%%I)
In new jQuery 1.5 you can use:
$.ajax({
type: "GET",
url: "http://localhost:99000/Services.svc/ReturnPersons",
dataType: "jsonp",
success: readData(data),
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
Its a common error which happens when we try to access a database which doesn't exist. So create the database using
CREATE DATABASE blog_development;
The error commonly occours when we have dropped the database using
DROP DATABASE blog_development;
and then try to access the database.
Just like any other environment variable, with SET
:
SET PATH=%PATH%;c:\whatever\else
If you want to have a little safety check built in first, check to see if the new path exists first:
IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else
If you want that to be local to that batch file, use setlocal
:
setlocal
set PATH=...
set OTHERTHING=...
@REM Rest of your script
Read the docs carefully for setlocal
/endlocal
, and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.
The Syntax page should get you started with the basics.
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent()
and fixedEncodeURI()
. Long-story...
You should not be using encodeURIComponent()
or encodeURI()
. You should use fixedEncodeURIComponent()
and fixedEncodeURI()
, according to the MDN Documentation.
Regarding encodeURI()
...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
Regarding encodeURIComponent()
...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
So, what is the difference? fixedEncodeURI()
and fixedEncodeURIComponent()
convert the same set of values, but fixedEncodeURIComponent()
also converts this set: +@?=:*#;,$&
. This set is used in GET
parameters (&
, +
, etc.), anchor tags (#
), wildcard tags (*
), email/username parts (@
), etc..
For example -- If you use encodeURI()
, [email protected]/?email=me@home
will not properly send the second @
to the server, except for your browser handling the compatibility (as Chrome naturally does often).
If it were me, I would avoid any risky revision editing and do the following instead:
Create a new branch on the SHA where 222 was committed, basically as a bookmark.
Switch back to the main branch. In it, revert commit 222.
Push all the commits that have been made, which will push commit 111 only, because 222 was reverted.
Work on the branch from step #1 if needed. Merge from the trunk to it as needed to keep it up to date. I wouldn't bother with stash.
When it's time for the changes in commit 222 to go in, that branch can be merged to trunk.
No, as of Notepad++ 5.6.2, this doesn't seem to be possible. Although column selection (Alt+Selection) is possible, multiple selections are obviously not implemented and thus also not supported by the search function.
This is a guess :)
Is it because the ID is a string? What happens if you change it to int?
I mean:
public int Id { get; set; }
If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited
into /etc/init.d/httpd
. This does not require a server reboot.
You can refresh the events after adding new ones by applying the following code: -Release the Events -set Event Source -Re-render Events
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', YoureventSource);
$('#calendar').fullCalendar('rerenderEvents' );
That will solve the problem
Django does not support free group by queries. I learned it in the very bad way. ORM is not designed to support stuff like what you want to do, without using custom SQL. You are limited to:
cr.execute
sentences (and a hand-made parsing of the result)..annotate()
(the group by sentences are performed in the child model for .annotate(), in examples like aggregating lines_count=Count('lines'))).Over a queryset qs
you can call qs.query.group_by = ['field1', 'field2', ...]
but it is risky if you don't know what query are you editing and have no guarantee that it will work and not break internals of the QuerySet object. Besides, it is an internal (undocumented) API you should not access directly without risking the code not being anymore compatible with future Django versions.
Download and install packages and dependencies
Usage:
go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]
Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.
The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.
The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.
The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.
The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.
The -t flag instructs get to also download the packages required to build the tests for the specified packages.
The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.
The -v flag enables verbose progress and debug output.
Get also accepts build flags to control the installation. See 'go help build'.
When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.
When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.
When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.
Get never checks out or updates code stored in vendor directories.
For more about specifying packages, see 'go help packages'.
For more about how 'go get' finds source code to download, see 'go help importpath'.
This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.
See also: go build, go install, go clean.
For example, showing verbose output,
$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$
fsutil
Usage:
fsutil file createnew [filename].[extension] [# of bytes]
Source: https://www.windows-commandline.com/how-to-create-large-dummy-file/
fallocate
Usage:
fallocate -l 10G [filename].[extension]
We can easily create and export/download the excel file with any separator (in this answer I am using the comma separator) using javascript. I am not using any external package for creating the excel file.
var Head = [[_x000D_
'Heading 1',_x000D_
'Heading 2', _x000D_
'Heading 3', _x000D_
'Heading 4'_x000D_
]];_x000D_
_x000D_
var row = [_x000D_
{key1:1,key2:2, key3:3, key4:4},_x000D_
{key1:2,key2:5, key3:6, key4:7},_x000D_
{key1:3,key2:2, key3:3, key4:4},_x000D_
{key1:4,key2:2, key3:3, key4:4},_x000D_
{key1:5,key2:2, key3:3, key4:4}_x000D_
];_x000D_
_x000D_
for (var item = 0; item < row.length; ++item) {_x000D_
Head.push([_x000D_
row[item].key1,_x000D_
row[item].key2,_x000D_
row[item].key3,_x000D_
row[item].key4_x000D_
]);_x000D_
}_x000D_
_x000D_
var csvRows = [];_x000D_
for (var cell = 0; cell < Head.length; ++cell) {_x000D_
csvRows.push(Head[cell].join(','));_x000D_
}_x000D_
_x000D_
var csvString = csvRows.join("\n");_x000D_
let csvFile = new Blob([csvString], { type: "text/csv" });_x000D_
let downloadLink = document.createElement("a");_x000D_
downloadLink.download = 'MYCSVFILE.csv';_x000D_
downloadLink.href = window.URL.createObjectURL(csvFile);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.click();
_x000D_
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.
Example from the documentation for charset unicode:
utf8_general_ci
also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should useutf8_general_ci
because it is faster. Otherwise, useutf8_unicode_ci
because it is more accurate.
So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci
should suffice, for other languages, like Swedish, special collations have been created.
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;
Here's a function to pretty up your json: pretty_json
You only need BOOST_ROOT
, but you're going to want to disable searching the system for your local Boost if you have multiple installations or cross-compiling for iOS or Android. In which case add Boost_NO_SYSTEM_PATHS
is set to false.
set( BOOST_ROOT "" CACHE PATH "Boost library path" )
set( Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost" )
Normally this is passed on the CMake command-line using the syntax -D<VAR>=value
.
Officially speaking the FindBoost page states these variables should be used to 'hint' the location of Boost.
This module reads hints about search locations from variables:
BOOST_ROOT - Preferred installation prefix
(or BOOSTROOT)
BOOST_INCLUDEDIR - Preferred include directory e.g. <prefix>/include
BOOST_LIBRARYDIR - Preferred library directory e.g. <prefix>/lib
Boost_NO_SYSTEM_PATHS - Set to ON to disable searching in locations not
specified by these hint variables. Default is OFF.
Boost_ADDITIONAL_VERSIONS
- List of Boost versions not known to this module
(Boost install locations may contain the version)
This makes a theoretically correct incantation:
cmake -DBoost_NO_SYSTEM_PATHS=TRUE \
-DBOOST_ROOT=/path/to/boost-dir
include( ExternalProject )
set( boost_URL "http://sourceforge.net/projects/boost/files/boost/1.63.0/boost_1_63_0.tar.bz2" )
set( boost_SHA1 "9f1dd4fa364a3e3156a77dc17aa562ef06404ff6" )
set( boost_INSTALL ${CMAKE_CURRENT_BINARY_DIR}/third_party/boost )
set( boost_INCLUDE_DIR ${boost_INSTALL}/include )
set( boost_LIB_DIR ${boost_INSTALL}/lib )
ExternalProject_Add( boost
PREFIX boost
URL ${boost_URL}
URL_HASH SHA1=${boost_SHA1}
BUILD_IN_SOURCE 1
CONFIGURE_COMMAND
./bootstrap.sh
--with-libraries=filesystem
--with-libraries=system
--with-libraries=date_time
--prefix=<INSTALL_DIR>
BUILD_COMMAND
./b2 install link=static variant=release threading=multi runtime-link=static
INSTALL_COMMAND ""
INSTALL_DIR ${boost_INSTALL} )
set( Boost_LIBRARIES
${boost_LIB_DIR}/libboost_filesystem.a
${boost_LIB_DIR}/libboost_system.a
${boost_LIB_DIR}/libboost_date_time.a )
message( STATUS "Boost static libs: " ${Boost_LIBRARIES} )
Then when you call this script you'll need to include the boost.cmake script (mine is in the a subdirectory), include the headers, indicate the dependency, and link the libraries.
include( boost )
include_directories( ${boost_INCLUDE_DIR} )
add_dependencies( MyProject boost )
target_link_libraries( MyProject
${Boost_LIBRARIES} )
If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :
To clear the SQL window you can use:
clear screen;
which can also be shortened to
cl scr;
You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.
If you are processing numbers in arbitrary order anyway, you may as well loop through all items:
for key, value in inputdict.items():
# do something with value
inputdict[key] = newvalue
otherwise I'd go with the reverse index:
from collections import defaultdict
reverse = defaultdict(list)
for key, value in inputdict.items():
reverse[value].append(key)
Now you can look up keys by value:
for key in reverse[value]:
inputdict[key] = newvalue
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
Also check out the open financial exchange (ofx) http://www.ofx.net/
This is what apps like quicken, ms money etc use.
Try -
$("#column_select").change(function () {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -
$(document).ready(function() {
$("#layout_select").children('option:gt(0)').hide();
$("#column_select").change(function() {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
})
Demo - http://jsfiddle.net/Mxkfr/2
EDIT
I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -
$(document).ready(function() {
var optarray = $("#layout_select").children('option').map(function() {
return {
"value": this.value,
"option": "<option value='" + this.value + "'>" + this.text + "</option>"
}
})
$("#column_select").change(function() {
$("#layout_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#layout_select").html(addoptarr.join(''))
}).change();
})
Demo - http://jsfiddle.net/N7Xpb/1/
moment.js
is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'
The slice(0, -1)
gets rid of the trailing Z
which represents Zulu timezone and can be replaced by your own.
scanf("%2000s %2000[^\n]", a, b);
If it is a Windows DLL file and your OS is Linux then use winedump:
$ winedump -j export pcre.dll
Contents of pcre.dll: 229888 bytes
Exports table:
Name: pcre.dll
Characteristics: 00000000
TimeDateStamp: 53BBA519 Tue Jul 8 10:00:25 2014
Version: 0.00
Ordinal base: 1
# of functions: 31
# of Names: 31
Addresses of functions: 000375C8
Addresses of name ordinals: 000376C0
Addresses of names: 00037644
Entry Pt Ordn Name
0001FDA0 1 pcre_assign_jit_stack
000380B8 2 pcre_callout
00009030 3 pcre_compile
...
Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.
let me start by stating the facts:
Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()
What it does?
The slice()
method extracts parts of a string and returns the extracted parts in a new string.
The substr()
method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring()
method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()
Changes the Original String?
slice()
Doesn't
substr()
Doesn't
substring()
Doesn't
Note #3:slice()==substring()
Using Negative Numbers as an Argument:
slice()
selects characters starting from the end of the string
substr()
selects characters starting from the end of the string
substring()
Doesn't Perform
Note #3:slice()==substr()
if the First Argument is Greater than the Second:
slice()
Doesn't Perform
substr()
since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring()
will swap the two arguments, and perform as usual
the First Argument:
slice()
Required, indicates: Starting Index
substr()
Required, indicates: Starting Index
substring()
Required, indicates: Starting Index
Note #4:slice()==substr()==substring()
the Second Argument:
slice()
Optional, The position (up to, but not including) where to end the extraction
substr()
Optional, The number of characters to extract
substring()
Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()
What if the Second Argument is Omitted?
slice()
selects all characters from the start-position to the end of the string
substr()
selects all characters from the start-position to the end of the string
substring()
selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()
so, you can say that there's a difference between slice()
and substr()
, while substring()
is basically a copy of slice()
.
in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr()
.
if (!document.getElementById("given-id")) {
//It does not exist
}
The statement document.getElementById("given-id")
returns null
if an element with given-id
doesn't exist, and null
is falsy meaning that it translates to false when evaluated in an if-statement. (other falsy values)
>>> a = "123"
>>> int(a)
123
Here's some freebie code:
def getTwoNumbers():
numberA = raw_input("Enter your first number: ")
numberB = raw_input("Enter your second number: ")
return int(numberA), int(numberB)
I use the following approach by combining this and this answer without using exception based programming and also supports pre-API 21 intent flag.
@SuppressWarnings("deprecation")
private Intent getRateIntent()
{
String url = isMarketAppInstalled() ? "market://details" : "https://play.google.com/store/apps/details";
Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
int intentFlags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
intentFlags |= Build.VERSION.SDK_INT >= 21 ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
rateIntent.addFlags(intentFlags);
return rateIntent;
}
private boolean isMarketAppInstalled()
{
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=anyText"));
return getPackageManager().queryIntentActivities(marketIntent, 0).size() > 0;
}
// use
startActivity(getRateIntent());
Since the intent flag FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
is deprecated from API 21 I use the @SuppressWarnings("deprecation")
tag on the getRateIntent method because my app target SDK is below API 21.
I also tried the official Google way suggested on their website (Dec. 6th 2019). To what I see it doesn't handle the case if the Play Store app isn't installed:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
"https://play.google.com/store/apps/details?id=com.example.android"));
intent.setPackage("com.android.vending");
startActivity(intent);
INSERT INTO preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,
uploader_id,is_deleted,last_updated)
SELECT '4827499',pre_image_status,file_extension,reviewer_id,
uploader_id,'0',last_updated FROM preliminary_image WHERE style_id=4827488
Analysis
We can use above query if we want to copy data from one table to another table in mysql
Execution results
1 queries executed, 1 success, 0 errors, 0 warnings
Query: insert into preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,uploader_id,is_deleted,last_updated) select ...
5 row(s) affected
Execution Time : 0.385 sec Transfer Time : 0 sec Total Time : 0.386 sec
You should define the style on the td
element like so:
<html>
<head>
<style type="text/css">
.bb
{
border-bottom: solid 1px black;
}
</style>
</head>
<body>
<table>
<tr>
<td>
Test 1
</td>
</tr>
<tr>
<td class="bb">
Test 2
</td>
</tr>
</table>
</body>
</html>
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
writer.WriteLine("whatever you text is");
}
The second "true" parameter tells it to append.
df[df.columns[i]]
where i
is the position/number of the column(starting from 0).
So, i = 0
is for the first column.
You can also get the last column using i = -1
You can try this methods
window.open(location, '_self').close();
This is what i do and it's in my opinion simplest way to do this. define an object manager for your new customized model then define your model.
from django.db import models
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
class User_manager(BaseUserManager):
def create_user(self, username, email, gender, nickname, password):
email = self.normalize_email(email)
user = self.model(username=username, email=email, gender=gender, nickname=nickname)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, username, email, gender, password, nickname=None):
user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(PermissionsMixin, AbstractBaseUser):
username = models.CharField(max_length=32, unique=True, )
email = models.EmailField(max_length=32)
gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
gender = models.CharField(choices=gender_choices, default="M", max_length=1)
nickname = models.CharField(max_length=32, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
REQUIRED_FIELDS = ["email", "gender"]
USERNAME_FIELD = "username"
objects = User_manager()
def __str__(self):
return self.username
Dont forget to add this line of code in your settings.py
:
AUTH_USER_MODEL = 'YourApp.User'
This is what i do and it always works.
Set the property RetainSameConnection
on the Connection Manager
to True
so that temporary table created in one Control Flow task can be retained in another task.
Here is a sample SSIS package written in SSIS 2008 R2
that illustrates using temporary tables.
Create a stored procedure that will create a temporary table named ##tmpStateProvince
and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora
Use the below create stored procedure script.
USE Sora;
GO
CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
DROP TABLE ##tmpStateProvince;
CREATE TABLE ##tmpStateProvince
(
CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
);
INSERT INTO ##tmpStateProvince
(CountryCode, StateCode, Name)
VALUES
('CA', 'AB', 'Alberta'),
('US', 'CA', 'California'),
('DE', 'HH', 'Hamburg'),
('FR', '86', 'Vienne'),
('AU', 'SA', 'South Australia'),
('VI', 'VI', 'Virgin Islands');
END
GO
Create a table named dbo.StateProvince
that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.
USE Sora;
GO
CREATE TABLE dbo.StateProvince
(
StateProvinceID int IDENTITY(1,1) NOT NULL
, CountryCode nvarchar(3) NOT NULL
, StateCode nvarchar(3) NOT NULL
, Name nvarchar(30) NOT NULL
CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
([StateProvinceID] ASC)
) ON [PRIMARY];
GO
Create an SSIS package using Business Intelligence Development Studio (BIDS)
. Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection...
to create a new connection to access SQL Server 2008 R2 database.
Click New...
on Configure OLE DB Connection Manager.
Perform the following actions on the Connection Manager dialog.
Native OLE DB\SQL Server Native Client 10.0
from Provider since the package will connect to SQL Server 2008 R2 databaseMACHINENAME\INSTANCE
Use Windows Authentication
from Log on to the server section or whichever you prefer.Select or enter a database name
, the sample uses the database name Sora
.Test Connection
OK
on the Test connection succeeded message.OK
on Connection ManagerThe newly created data connection will appear on Configure OLE DB Connection Manager. Click OK
.
OLE DB connection manager KIWI\SQLSERVER2008R2.Sora
will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties
Set the property RetainSameConnection
on the connection KIWI\SQLSERVER2008R2.Sora
to the value True
.
Right-click anywhere inside the package and then click Variables
to view the variables pane. Create the following variables.
A new variable named PopulateTempTable
of data type String
in the package scope SO_5631010
and set the variable with the value EXEC dbo.PopulateTempTable
.
A new variable named FetchTempData
of data type String
in the package scope SO_5631010
and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince
Drag and drop an Execute SQL Task
on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.
On the General
page of the Execute SQL Task Editor, perform the following actions.
Create and populate temp table
OLE DB
KIWI\SQLSERVER2008R2.Sora
Variable
from SQLSourceTypeUser::PopulateTempTable
from SourceVariableOK
Drag and drop a Data Flow Task
onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table
. Connect the green arrow from the Execute SQL Task to the Data Flow Task.
Double-click the Data Flow Task
to switch to Data Flow tab. Drag and drop an OLE DB Source
onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.
On the Connection Manager
page of the OLE DB Source Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerSQL command from variable
from Data access modeUser::FetchTempData
from Variable nameColumns
pageClicking Columns
page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince
specified in the source command variable does not exist and SSIS is unable to read the column definition.
To fix the error, execute the statement EXEC dbo.PopulateTempTable
using SQL Server Management Studio (SSMS) on the database Sora
so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns
page on OLE DB Source Editor, you will see the column information. Click OK
.
Drag and drop OLE DB Destination
onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination
to open OLE DB Destination Editor.
On the Connection Manager
page of the OLE DB Destination Editor, perform the following actions.
KIWI\SQLSERVER2008R2.Sora
from OLE DB Connection ManagerTable or view - fast load
from Data access mode[dbo].[StateProvince]
from Name of the table or the viewMappings
pageClick Mappings
page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK
. Column StateProvinceID
does not have a matching input column and it is defined as an IDENTITY
column in database. Hence, no mapping is required.
Data Flow tab should look something like this after configuring all the components.
Click the OLE DB Source
on Data Flow tab and press F4 to view Properties
. Set the property ValidateExternalMetadata
to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.
Execute the package. Control Flow shows successful execution.
In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.
Execute the query select * from dbo.StateProvince
in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.
The above example illustrated how to create and use temporary table within a package.
I think this is what you want:
/grand/parent/child[@id="#grand"]
You should use Console.ReadLine() if you want to read some input from the console.
To see your code running in Console:
In Solution Explorer (View - Solution Explorer from the menu), right click on your project, select Open Folder in File Explorer, to find where your project path is.
Supposedly the path is C:\code\myProj .
Open the Command Prompt app in Windows.
Change to your folder path. cd C:\code\myProj
Change to the debug folder, where you should find your program executable. cd bin\debug
Run your program executable, it should end in .exe extension.
Example:
myproj.exe
You should see what you output in Console.Out.WriteLine() .
The Apache module PHP version might for some odd reason not be picking up the php.ini file as the CLI version I'd suggest having a good look at:
.ini
files that differ between php -i
and phpinfo()
via a web page*mysql.so
and the .ini
files but I think that Apache parses these as the root
userTo be really clear here, don't go searching for php.ini
files on the file system, have a look at what PHP says that it's looking at
From TinyMCE, jQuery and Ajax forms:
TinyMCE Form Submission
When a textarea is replaced by TinyMCE, it's actually hidden and TinyMCE editor (an iframe) is displayed instead.
However, it's this textarea's contents which is sent when the form is submitted. Consequently its contents has to be updated before the form submission.
For a standard form submission , it's handled by TinyMCE . For an Ajax form submission, you have to do it manually, by calling (before the form is submitted):
tinyMCE.triggerSave();
$('form').bind('form-pre-serialize', function(e) {
tinyMCE.triggerSave();
});
If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.
jpanel1.setVisible(false);
There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback
property of a UIWebView). By default on iPhone this is set to NO
, but on iPad it's set to YES
.
Fortunately for you, you can also adjust this behaviour in HTML as follows:
<video id="myVideo" width="280" height="140" webkit-playsinline>
...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.
Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):
There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.
Note that Apache recommends using apachectl -k
as the command, and for systemd, the command is replaced by httpd -k
apachectl -k graceful
or httpd -k graceful
Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.
apachectl -k restart
or httpd -k restart
This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.
I would use a for
loop to iterate over the lines in the text file:
for line in my_text:
outputfile.writelines(data_parser(line, reps))
If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:
inputfile = open('test.dat')
outputfile = open('test.csv', 'w')
# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'
# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }
for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
outputfile.writelines(data_parser(line, reps))
inputfile.close()
outputfile.close()
to access the last element in array using c# we can use GetUpperBound(0)
(0) in case if this one dimention array
my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array
If none of the above seem to help, in my environment was broken from a system upgrade and I could not upgrade pip. While it won't give you an accurate list you can get an idea of which libraries were installed simply by looking inside your env>lib>python(version here)>site-packages> . Here you will get a good indication of modules installed.
pip
/ conda
After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:
NEVER disable all SSL verification!
This creates a bad security culture. Don't be that person.
pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify
# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt
But where do we get ca-bundle.crt
?
cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox
https://curl.haxx.se/docs/caextract.html
I recommend you open up this cacert.pem
file in a text editor as we will need to add our self-signed CA to this file.
Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:
----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----
Below are a few options on how to get our self signed certificate:
echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem
Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.
Copy the contents of this exported file and paste it at the end of your cacerts.pem
file.
For consistency rename this file cacerts.pem
--> ca-bundle.crt
and place it somewhere easy like:
# Windows
%USERPROFILE%\certs\ca-bundle.crt
# or *nix
$HOME/certs/cabundle.crt
Thanks to all the brilliant answers in:
How to get response SSL certificate from requests in python?
I have put together the following to attempt to take it a step further.
https://github.com/neozenith/get-ca-py
Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.
pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt
OR
pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt
THEN
pip config list
conda config --show ssl_verify
# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'
Why it is hard
Popular font formats like TrueType and OpenType are vector outline formats: they use Bezier curves to define the boundary of the letter.
Transforming those formats into arrays of pixels (rasterization) is too specific and out of OpenGL's scope, specially because OpenGl does not have non-straight primitives (e.g. see Why is there no circle or ellipse primitive in OpenGL?)
The easiest approach is to first raster fonts ourselves on the CPU, and then give the array of pixels to OpenGL as a texture.
OpenGL then knows how to deal with arrays of pixels through textures very well.
Texture atlas
We could raster characters for every frame and re-create the textures, but that is not very efficient, specially if characters have a fixed size.
The more efficient approach is to raster all characters you plan on using and cram them on a single texture.
And then transfer that to the GPU once, and use it texture with custom uv coordinates to choose the right character.
This approach is called a texture atlas and it can be used not only for textures but also other repeatedly used textures, like tiles in a 2D game or web UI icons.
The Wikipedia picture of the full texture, which is itself taken from freetype-gl, illustrates this well:
I suspect that optimizing character placement to the smallest texture problem is an NP-hard problem, see: What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?
The same technique is used in web development to transmit several small images (like icons) at once, but there it is called "CSS Sprites": https://css-tricks.com/css-sprites/ and are used to hide the latency of the network instead of that of the CPU / GPU communication.
Non-CPU raster methods
There also exist methods which don't use the CPU raster to textures.
CPU rastering is simple because it uses the GPU as little as possible, but we also start thinking if it would be possible to use the GPU efficiency further.
This FOSDEM 2014 video explains other existing techniques:
Fonts inside of the 3D geometry with perspective
Rendering fonts inside of the 3D geometry with perspective (compared to an orthogonal HUD) is much more complicated, because perspective could make one part of the character much closer to the screen and larger than the other, making an uniform CPU discretization (e.g. raster, tesselation) look bad on the close part. This is actually an active research topic:
Distance fields are one of the popular techniques now.
The examples that follow were all tested on Ubuntu 15.10.
Because this is a complex problem as discussed previously, most examples are large, and would blow up the 30k char limit of this answer, so just clone the respective Git repositories to compile.
They are all fully open source however, so you can just RTFS.
FreeType solutions
FreeType looks like the dominant open source font rasterization library, so it would allow us to use TrueType and OpenType fonts, making it the most elegant solution.
https://github.com/rougier/freetype-gl
Was a set of examples OpenGL and freetype, but is more or less evolving into a library that does it and exposes a decent API.
In any case, it should already be possible to integrate it on your project by copy pasting some source code.
It provides both texture atlas and distance field techniques out of the box.
Demos under: https://github.com/rougier/freetype-gl/tree/master/demos
Does not have a Debian package, and it a pain to compile on Ubuntu 15.10: https://github.com/rougier/freetype-gl/issues/82#issuecomment-216025527 (packaging issues, some upstream), but it got better as of 16.10.
Does not have a nice installation method: https://github.com/rougier/freetype-gl/issues/115
Generates beautiful outputs like this demo:
libdgx https://github.com/libgdx/libgdx/tree/1.9.2/extensions/gdx-freetype
Examples / tutorials:
Other font rasterizers
Those seem less good than FreeType, but may be more lightweight:
Anton's OpenGL 4 Tutorials example 26 "Bitmap fonts"
The font was created by the author manually and stored in a single .png
file. Letters are stored in an array form inside the image.
This method is of course not very general, and you would have difficulties with internationalization.
Build with:
make -f Makefile.linux64
Output preview:
opengl-tutorial chapter 11 "2D fonts"
Textures are generated from DDS files.
The tutorial explains how the DDS files were created, using CBFG and Paint.Net.
Output preview:
For some reason Suzanne is missing for me, but the time counter works fine: https://github.com/opengl-tutorials/ogl/issues/15
FreeGLUT
GLUT has glutStrokeCharacter
and FreeGLUT is open source...
https://github.com/dcnieho/FreeGLUT/blob/FG_3_0_0/src/fg_font.c#L255
OpenGLText
https://github.com/tlorach/OpenGLText
TrueType raster. By NVIDIA employee. Aims for reusability. Haven't tried it yet.
ARM Mali GLES SDK Sample
http://malideveloper.arm.com/resources/sample-code/simple-text-rendering/ seems to encode all characters on a PNG, and cut them from there.
SDL_ttf
Source: https://github.com/cirosantilli/cpp-cheat/blob/d36527fe4977bb9ef4b885b1ec92bd0cd3444a98/sdl/ttf.c
Lives in a separate tree to SDL, and integrates easily.
Does not provide a texture atlas implementation however, so performance will be limited: How to render fonts and text with SDL2 efficiently?
Related threads
All of the provided answers are more complicated than necessary. Assuming you are building a jar file, all you need to do is add a <jar.finalName>
tag to your <properties>
section:
<properties>
<jar.finalName>${project.name}</jar.finalName>
</properties>
This will generate a jar:
project/target/${project.name}.jar
This is in the documentation - note the User Property
:
finalName:
Name of the generated JAR.
Type: java.lang.String
Required: No
User Property: jar.finalName
Default: ${project.build.finalName}
You should also be able to use this option on the command line with:
mvn -Djar.finalName=myCustomName ...
You should get myCustomName.jar, although I haven't tested this.
Use the DOM's getElementByid
method:
document.getElementById("DATE").value = "your date";
A date can be made with the Date
class:
d = new Date();
(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)
var formatedDate = DateTime.Now.ToString("yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);
To ensure the user's local settings don't affect it
If you are using OpenLDAP (i.e. slapd) which is common on Linux servers, then you must enable the memberof overlay to be able to match against a filter using the (memberOf=XXX) attribute.
Also, once you enable the overlay, it does not update the memberOf attributes for existing groups (you will need to delete out the existing groups and add them back in again). If you enabled the overlay to start with, when the database was empty then you should be OK.
Floats, by nature, are imprecise and always have neat rounding "issues". If precision is important then you might consider refactoring your application to use Decimal or BigDecimal.
Yes, floats are computationally faster than decimals because of the on processor support. However, do you want fast or accurate?
A full .Net solution is to use the classes from the System.DirectoryServices namespace. They allow to query an AD server directly. Here is a small sample that would do this:
using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Username = "here goes the username you want to validate";
entry.Password = "here goes the password";
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(objectclass=user)";
try
{
searcher.FindOne();
}
catch (COMException ex)
{
if (ex.ErrorCode == -2147023570)
{
// Login or password is incorrect
}
}
}
// FindOne() didn't throw, the credentials are correct
This code directly connects to the AD server, using the credentials provided. If the credentials are invalid, searcher.FindOne() will throw an exception. The ErrorCode is the one corresponding to the "invalid username/password" COM error.
You don't need to run the code as an AD user. In fact, I succesfully use it to query informations on an AD server, from a client outside the domain !
Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.
Yes.
Field f = Test.class.getDeclaredField("str");
f.setAccessible(true);//Very important, this allows the setting to work.
String value = (String) f.get(object);
Then you use the field object to get the value on an instance of the class.
Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get
method
Another method of deleting using a sub select that is better than using IN
would be WHERE
EXISTS
DELETE FROM posts
WHERE EXISTS ( SELECT 1
FROM projects
WHERE projects.client_id = posts.client_id);
One reason to use this instead of the join is that a DELETE
with JOIN
forbids the use of LIMIT
. If you wish to delete in blocks so as not to produce full table locks, you can add LIMIT
use this DELETE WHERE EXISTS
method.
In response to the post starting:
If you want to use this with command line or function arguments...
with the code:
size=${#1}
There might be the case where you just want to check for a zero length argument and have no need to store a variable. I believe you can use this sort of syntax:
if [ -z "$1" ]; then
#zero length argument
else
#non-zero length
fi
See GNU and wooledge for a more complete list of Bash conditional expressions.
I faced similar issue, and what I understand from Grega's answer is
object NOTworking extends App {
new testing().doIT
}
//adding extends Serializable wont help
class testing {
val list = List(1,2,3)
val rddList = Spark.ctx.parallelize(list)
def doIT = {
//again calling the fucntion someFunc
val after = rddList.map(someFunc(_))
//this will crash (spark lazy)
after.collect().map(println(_))
}
def someFunc(a:Int) = a+1
}
your doIT method is trying to serialize someFunc(_) method, but as method are not serializable, it tries to serialize class testing which is again not serializable.
So make your code work, you should define someFunc inside doIT method. For example:
def doIT = {
def someFunc(a:Int) = a+1
//function definition
}
val after = rddList.map(someFunc(_))
after.collect().map(println(_))
}
And if there are multiple functions coming into picture, then all those functions should be available to the parent context.
If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?
E:\>mysql -u root -p
Enter password: *******
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1026
Server version: 5.6.34-log MySQL Community Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select @@version;
+------------+
| @@version |
+------------+
| 5.6.34-log |
+------------+
1 row in set (0.00 sec)
The following solution works for ASP.NET 5 (vNext) and it uses QueryHelpers class to build a URI with parameters.
public Uri GetUri()
{
var location = _config.Get("http://iberia.com");
Dictionary<string, string> values = GetDictionaryParameters();
var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
return new Uri(uri);
}
private Dictionary<string,string> GetDictionaryParameters()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "param1", "value1" },
{ "param2", "value2"},
{ "param3", "value3"}
};
return values;
}
The result URI would have http://iberia.com?param1=value1¶m2=value2¶m3=value3
Another way to do it is to splice two parsed sections of the numerical value together:
Cells(RowNum, ColumnNum).Value = Mid(varNumber,1,1) & Mid(varNumber,2,Len(varNumber))
I have found better success with this than CStr()
because CStr()
doesn't seem to convert decimal numbers that came from variants in my experience.
After some changing to above Henry's answer, I got a tick with in a circle, I came here looking for that, so adding my code here.
.snackbar_circle {
background-color: #f0f0f0;
border-radius: 13px;
padding: 0 5px;
}
.checkmark {
font-family: arial;
font-weight: bold;
-ms-transform: scaleX(-1) rotate(-35deg);
-webkit-transform: scaleX(-1) rotate(-35deg);
transform: scaleX(-1) rotate(-35deg);
color: #63BA3D;
display: inline-block;
}
_x000D_
<span class="snackbar_circle">
<span class="checkmark">L</span>
</span>
_x000D_
It's easy, You need to find index of [ and ] then substring. (Here [ is always at start and ] is at end) ,
String loginToken = "[wdsd34svdf]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );
When working with Angular the recent update to Angular 8 introduced that a static
property inside @ViewChild()
is required as stated here and here. Then your code would require this small change:
@ViewChild('one') d1:ElementRef;
into
// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;
OR
// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;
This post describes it very nicely.
In short: utf8_unicode_ci
uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci
is a more simple sort order which results in "less accurate" sorting results.
The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:
...
...
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
android:id="@+id/icon_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</TabHost>
in Java:
final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;
FrameLayout frameLayout = (FrameLayout) materialDialog
.findViewById(R.id.icon_frame_container);
frameLayout.setOnTouchListener(
new OnSwipeTouchListener(ShowCardActivity.this) {
You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:
$FileName = preg_replace('/[^\w]/', '', $UserInput);
You might want to do this to ensure maximum compatibility for filenames across different operating systems.
Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.
Use the subplots_adjust()
function to move the bottom of the subplot up:
fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.
Then play with the offset in the legend bbox_to_anchor
part of the legend command, to get the legend box where you want it. Some combination of setting the figsize
and using the subplots_adjust(bottom=...)
should produce a quality plot for you.
Alternative: I simply changed the line:
fig = plt.figure(1)
to:
fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')
and changed
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
to
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))
and it shows up fine on my screen (a 24-inch CRT monitor).
Here figsize=(M,N)
sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport
option when including graphics.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
var gent = /I like your Apartment. Could we schedule a viewing\?/g;
The reason you are getting this error is that JavaScript is not waiting for the script to be loaded, so when you run
jQuery(document).ready(function(){...
there is not guarantee that the script is ready (and never will be).
This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.
var jQueryIsReady = function(){
//Your JQuery code here
}
var checkJquery = function(){
if(typeof jQuery === "undefined"){
return false;
}else{
clearTimeout(interval);
jQueryIsReady();
}
}
var interval = setInterval(checkJquery,1000);
This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:
Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)
kudos to https://php.quicoto.com/create-loop-inside-react-jsx/
Updated March 31st, 2016:
We have announced that Visual Studio now includes Xamarin at no extra cost, including Community Edition, which is free for individual developers, open source projects, academic research, education, and small professional teams. There is no size restriction on the Community Edition and offers the same features as the Pro & Enterprise editions. Read more about the update here: https://blog.xamarin.com/xamarin-for-all/
Be sure to browse the store on how to download and get started: https://visualstudio.microsoft.com/vs/pricing/ and there is a nice FAQ section: https://visualstudio.microsoft.com/vs/support/
The Content-Security-Policy
meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.
I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.
For brevity I won’t write the full tag in each sample. Instead I'll only show the content
property, so a sample that says content="default-src 'self'"
means this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
1. How can I allow multiple sources?
You can simply list your sources after a directive as a space-separated list:
content="default-src 'self' https://example.com/js/"
Note that there are no quotes around parameters other than the special ones, like 'self'
. Also, there's no colon (:
) after the directive. Just the directive, then a space-separated list of parameters.
Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:
https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js
These, however, would not be valid:
http://example.com/js/file.js
^^^^ wrong protocol
https://example.com/file.js
^^ above the specified path
2. How can I use different directives? What do they each do?
The most common directives are:
default-src
the default policy for loading javascript, images, CSS, fonts, AJAX requests, etcscript-src
defines valid sources for javascript filesstyle-src
defines valid sources for css filesimg-src
defines valid sources for imagesconnect-src
defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400
errorThere are others, but these are the ones you're most likely to need.
3. How can I use multiple directives?
You define all your directives inside one meta-tag by terminating them with a semicolon (;
):
content="default-src 'self' https://example.com/js/; style-src 'self'"
4. How can I handle ports?
Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:
content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"
The above would result in:
https://ajax.googleapis.com:123
^^^^ Not ok, wrong port
https://ajax.googleapis.com - OK
http://example.com/free/stuff/file.js
^^ Not ok, only the port 123 is allowed
http://example.com:123/free/stuff/file.js - OK
As I mentioned, you can also use an asterisk to explicitly allow all ports:
content="default-src example.com:*"
5. How can I handle different protocols?
By default, only standard protocols are allowed. For example to allow WebSockets ws://
you will have to allow it explicitly:
content="default-src 'self'; connect-src ws:; style-src 'self'"
^^^ web Sockets are now allowed on all domains and ports.
6. How can I allow the file protocol file://
?
If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem
parameter:
content="default-src filesystem"
7. How can I use inline scripts and style definitions?
Unless explicitly allowed, you can't use inline style definitions, code inside <script>
tags or in tag properties like onclick
. You allow them like so:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
You'll also have to explicitly allow inline, base64 encoded images:
content="img-src data:"
8. How can I allow eval()
?
I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:
content="script-src 'unsafe-eval'"
9. What exactly does 'self'
mean?
You might take 'self'
to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.
I've used 'self'
in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.
But hang on a minute! Can't I just use content="default-src *"
and be done with it?
No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
... but I trust you won’t.
Further reading:
Our DMS Software Reengineering Toolkit has static control/dataflow/points-to/call graph analysis that has been applied to huge systems (~~25 million lines) of C code, and produced such call graphs, including functions called via function pointers.
Move:
var k = Math.pow(10, i);
above
var j = k / 10;
In the servlet code, with the instruction request.setAttribute("servletName", categoryList)
, you save your list in the request object, and use the name "servletName" for refering it.
By the way, using then name "servletName" for a list is quite confusing, maybe it's better call it "list" or something similar: request.setAttribute("list", categoryList)
Anyway, suppose you don't change your serlvet code, and store the list using the name "servletName". When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute(...)
method.
<%
// retrieve your list from the request, with casting
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");
// print the information about every category of the list
for(Category category : list) {
out.println(category.getId());
out.println(category.getName());
out.println(category.getMainCategoryId());
}
%>
After Docker Installation on Centos. While running below command I got below error.
[centos@aiops-dev-cassandra3 ~]$ docker run hello-world
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.soc k/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
Change Group and Permission for docker.socket
[centos@aiops-dev-cassandra3 ~]$ ls -l /lib/systemd/system/docker.socket
-rw-r--r--. 1 root root 197 Nov 13 07:25 /lib/systemd/system/docker.socket
[centos@aiops-dev-cassandra3 ~]$ sudo chgrp docker /lib/systemd/system/docker.socket
[centos@aiops-dev-cassandra3 ~]$ sudo chmod 666 /var/run/docker.sock
[centos@aiops-dev-cassandra3 ~]$ ls -lrth /var/run/docker.sock
srw-rw-rw-. 1 root docker 0 Nov 20 11:59 /var/run/docker.sock
[centos@aiops-dev-cassandra3 ~]$
Verify by using below docker command
[centos@aiops-dev-cassandra3 ~]$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:c3b4ada4687bbaa170745b3e4dd8ac3f194ca95b2d0518b417fb47e5879d9b5f
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
[centos@aiops-dev-cassandra3 ~]$
Check for session is new.
HttpSession session = request.getSession(false);
if (!session.isNew()) {
// Session is valid
}
else {
//Session has expired - redirect to login.jsp
}
The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault()
. However as the OP alluded to, if you always call it preventDefault()
you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.
Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.
// Bind keydown event to this function. Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){
// Use jquery's constants rather than an unintuitive magic number.
// $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
if (e.keyCode == $.ui.keyCode.BACKSPACE) {
// Filters out events coming from any of the following tags so Backspace
// will work when typing text, but not take the page back otherwise.
var rx = /INPUT|SELECT|TEXTAREA/i;
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
// Add your code here.
}
});
Once logged in to cqlsh or cassandra-cli. run below commands
desc keyspaces;
or
describe keyspaces;
or
select * from system_schema.keyspaces;
show keyspaces;
The maximum length until "it gets sluggish" is totally dependent on your target machine and your actual code, so you'll need to test on that (those) platform(s) to see what is acceptable.
However, the maximum length of an array according to the ECMA-262 5th Edition specification is bound by an unsigned 32-bit integer due to the ToUint32 abstract operation, so the longest possible array could have 232-1 = 4,294,967,295 = 4.29 billion elements.
@tvanfosson rocks with his answer.
However, I would suggest an improvement within js and a small controller check.
When we use @Url
helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html
) not the actual element (.replaceWith
).
More about at: What's the difference between jQuery's replaceWith() and html()?
$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
$('#detailsDiv').html(data);
});
This is specially useful in trees, where the content can be changed several times.
At the controller we can reuse the action depending on requester:
public ActionResult Details( int id )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
This error was generated for me by having an incorrectly formatted NLog.config file.
I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;
It works and it's cross browser compatible.
Check out the code below, you probably get a better explanation:
jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
jQuery('#message').fadeOut();_x000D_
return false;_x000D_
});
_x000D_
html, body {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#message {_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .container {_x000D_
height: 60%;_x000D_
left: 50%;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
z-index: 10;_x000D_
width: 60%;_x000D_
}_x000D_
_x000D_
#message .container .text {_x000D_
background: #fff;_x000D_
height: 100%;_x000D_
left: -50%;_x000D_
position: absolute;_x000D_
top: -50%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#message .bg {_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
height: 100%;_x000D_
left: 0;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
width: 100%;_x000D_
z-index: 9;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
<div class="container">_x000D_
<div class="text">_x000D_
<h2>Warning</h2>_x000D_
<p>The message</p>_x000D_
<p class="close"><a href="#">Close Window</a></p>_x000D_
</div>_x000D_
</div>_x000D_
<div class="bg"></div>_x000D_
</div>
_x000D_