You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use new and wonderful ask-for-permission model:
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
Sniplet found here: https://developer.android.com/training/permissions/requesting.html
Solutions 2: If it does not work try this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
return;
}
and then in callback
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
that is from comments. thanks
@Synxmax's answer is correct when using a Service
and the MediaPlayer
class, however you also need to declare the Service
in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
A modern stdlib way is using sysconfig
module, available in version 2.7 and 3.2+. Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.
Note: sysconfig
(source) is not to be confused with the distutils.sysconfig
submodule (source) mentioned in several other answers here. The latter is an entirely different module and it's lacking the get_paths
function discussed below.
Python currently uses eight paths (docs):
- stdlib: directory containing the standard Python library files that are not platform-specific.
- platstdlib: directory containing the standard Python library files that are platform-specific.
- platlib: directory for site-specific, platform-specific files.
- purelib: directory for site-specific, non-platform-specific files.
- include: directory for non-platform-specific header files.
- platinclude: directory for platform-specific header files.
- scripts: directory for script files.
- data: directory for data files.
In most cases, users finding this question would be interested in the 'purelib' path (in some cases, you might be interested in 'platlib' too). The purelib path is where ordinary Python packages will be installed by tools like pip
.
At system level, you'll see something like this:
# Linux
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/lib/python3.8/site-packages
# macOS (brew installed python3.8)
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/Cellar/[email protected]/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
# Windows
C:\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"
C:\Users\wim\AppData\Local\Programs\Python\Python38\Lib\site-packages
With a venv, you'll get something like this
# Linux
/tmp/.venv/lib/python3.8/site-packages
# macOS
/private/tmp/.venv/lib/python3.8/site-packages
# Windows
C:\Users\wim\AppData\Local\Temp\.venv\Lib\site-packages
The function sysconfig.get_paths()
returns a dict of all of the relevant installation paths, example on Linux:
>>> import sysconfig
>>> sysconfig.get_paths()
{'stdlib': '/usr/local/lib/python3.8',
'platstdlib': '/usr/local/lib/python3.8',
'purelib': '/usr/local/lib/python3.8/site-packages',
'platlib': '/usr/local/lib/python3.8/site-packages',
'include': '/usr/local/include/python3.8',
'platinclude': '/usr/local/include/python3.8',
'scripts': '/usr/local/bin',
'data': '/usr/local'}
A shell script is also available to display these details, which you can invoke by executing sysconfig
as a module:
python -m sysconfig
Swift 4 Version
extension UIImage {
func resizeImage(_ newSize: CGSize) -> UIImage? {
func isSameSize(_ newSize: CGSize) -> Bool {
return size == newSize
}
func scaleImage(_ newSize: CGSize) -> UIImage? {
func getScaledRect(_ newSize: CGSize) -> CGRect {
let ratio = max(newSize.width / size.width, newSize.height / size.height)
let width = size.width * ratio
let height = size.height * ratio
return CGRect(x: 0, y: 0, width: width, height: height)
}
func _scaleImage(_ scaledRect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
draw(in: scaledRect)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
return _scaleImage(getScaledRect(newSize))
}
return isSameSize(newSize) ? self : scaleImage(newSize)!
}
}
The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.
@Aidos had the right answer just wanted to make it clear since it is hidden inside a comment on his post made by @CodingWithSpike.
@Ajax.ActionLink("Delete", "Delete", new { id = item.ApkModelId }, new AjaxOptions { HttpMethod = "POST" })
to save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
to retreive :
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
default value is : Values to return if this preference does not exist.
you can change "this" with getActivity() or getApplicationContext() in some cases
Limiting output to two lines of text is possible with CSS, if you set the line-height
and height
of the element, and set overflow:hidden;
:
#someDiv {
line-height: 1.5em;
height: 3em; /* height is 2x line-height, so two lines will display */
overflow: hidden; /* prevents extra lines from being visible */
}
Alternatively, you can use the CSS text-overflow
and white-space
properties to add ellipses, but this only appears to work for a single line.
#someDiv {
line-height: 1.5em;
height: 3em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 100%;
}
And a demo:
Achieving both multiple lines of text and ellipses appears to be the realm of javascript.
Best way in my opinion.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
The other features of CodeLens like: Show Bugs, Show Test Status, etc (other than Show Reference) might be useful.
However, if the only way to disable Show References is to disable CodeLens altogether.
Then, I guess I could do just that.
Furthermore, I would do like I always have, 'right-click on a member and choose Find all References or Ctrl+K, R'
If I wanted to know what references the member -- I too like not having any extra information crammed into my code, like extra white-space.
In short, uncheck Codelens...
Intenta con:
__GET($k){
return $this->$k;
}
_SET($k,$v){
return $this->$k = $v;
}
Import gives you access to other modules in your program. You can't decide to import a text file. If you want to read from a file that's in the same directory, you can look at this. Here's another StackOverflow post about it.
What would you like these support libraries to do? Just using OpenGL from C# is simple enough and does not require any additional libraries afaik.
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
If you are not very offended by the GOTO
keyword, it can be used to simulate a DO
/ WHILE
in T-SQL. Consider the following rather nonsensical example written in pseudocode:
SET I=1
DO
PRINT I
SET I=I+1
WHILE I<=10
Here is the equivalent T-SQL code using goto:
DECLARE @I INT=1;
START: -- DO
PRINT @I;
SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10
Notice the one to one mapping between the GOTO
enabled solution and the original DO
/ WHILE
pseudocode. A similar implementation using a WHILE
loop would look like:
DECLARE @I INT=1;
WHILE (1=1) -- DO
BEGIN
PRINT @I;
SET @I+=1;
IF NOT (@I<=10) BREAK; -- WHILE @I<=10
END
Now, you could of course rewrite this particular example as a simple WHILE
loop, since this is not such a good candidate for a DO
/ WHILE
construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO
/ WHILE
are rare.
REPEAT / UNTIL, anyone (does NOT work in T-SQL)?
SET I=1
REPEAT
PRINT I
SET I=I+1
UNTIL I>10
... and the GOTO
based solution in T-SQL:
DECLARE @I INT=1;
START: -- REPEAT
PRINT @I;
SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10
Through creative use of GOTO
and logic inversion via the NOT
keyword, there is a very close relationship between the original pseudocode and the GOTO
based solution. A similar solution using a WHILE
loop looks like:
DECLARE @I INT=1;
WHILE (1=1) -- REPEAT
BEGIN
PRINT @I;
SET @I+=1;
IF @I>10 BREAK; -- UNTIL @I>10
END
An argument can be made that for the case of the REPEAT
/ UNTIL
, the WHILE
based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.
If it wasn't for all of the disdain around the use of GOTO
, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.
Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO
.
Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,
rdd = df.rdd.flatMap(list)
or
rdd = df.rdd.flatmap(lambda x: list(x))
At https://github.com/golang/go/issues/44196 randall77 suggested
time.Now().Sub(time.Unix(0,0)).Milliseconds()
which exploits the fact that Go's time.Duration
already have Milliseconds
method.
You have to ask for the permission at run time:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
dialog.dismiss();
return;
}
And in the callback below you can access the storage without a problem.
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
Since the main
method is static
and the fxn()
method is not, you can't call the method without first creating a Two
object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main
to:
Two two = new Two();
x = two.fxn(x);
Read more on static
here in the Java Tutorials.
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
It could happen if your classpath is not correct
Let us posit a serializable class and deserializable class under same projectname. You run the serializable class, creating a serializable object in specific folder. Now you need the desearialized data. In the meantime, if you change the name of the project it will not work. You have to run the serializable class first and then deserialize the file.
int
is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer
and then you can return null, and existing code that returns int will get autoboxed.
Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.
Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.
New answer to an old question:
Visual Studio Database Projects handle the drop and recreate process when you deploy changes. It will drop stored procs that use UDDTs and then recreate them after dropping and recreating the data type.
You can indeed not define the filter execution order using @WebFilter
annotation. However, to minimize the web.xml
usage, it's sufficient to annotate all filters with just a filterName
so that you don't need the <filter>
definition, but just a <filter-mapping>
definition in the desired order.
For example,
@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}
with in web.xml
just this:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/url2/*</url-pattern>
</filter-mapping>
If you'd like to keep the URL pattern in @WebFilter
, then you can just do like so,
@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}
but you should still keep the <url-pattern>
in web.xml
, because it's required as per XSD, although it can be empty:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern />
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern />
</filter-mapping>
Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping>
without <filter>
. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
The best solution for any browser that lack a console is:
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
Answer is to escape the dash!
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
First you need to determine the revision ID of the last known commit. You can use HEAD^
or HEAD~{1}
if you know you need to reverse exactly one commit.
git reset --hard <revision_id_of_last_known_good_commit>
git push --force
Since the question is How to generate random colors in matplotlib?
and as I was searching for an answer concerning pie plots
, I think it is worth to put an answer here (for pies
)
import numpy as np
from random import sample
import matplotlib.pyplot as plt
import matplotlib.colors as pltc
all_colors = [k for k,v in pltc.cnames.items()]
fracs = np.array([600, 179, 154, 139, 126, 1185])
labels = ["label1", "label2", "label3", "label4", "label5", "label6"]
explode = ((fracs == max(fracs)).astype(int) / 20).tolist()
for val in range(2):
colors = sample(all_colors, len(fracs))
plt.figure(figsize=(8,8))
plt.pie(fracs, labels=labels, autopct='%1.1f%%',
shadow=True, explode=explode, colors=colors)
plt.legend(labels, loc=(1.05, 0.7), shadow=True)
plt.show()
Output
If you require your keys to be any object rather than just strings, then you could use my jshashtable.
Follow these steps:
1.clean your file -> open your datafile in csv
format and see that there is "?" in place of empty places and delete all of them.
2.drop the rows containing missing values e.g.:
df.dropna(subset=["normalized-losses"], axis = 0 , inplace= True)
3.use astype now for conversion
df["normalized-losses"]=df["normalized-losses"].astype(int)
Note: If still finding erros in your program then again inspect your csv
file, open it in excel to find whether is there an "?" in your required column, then delete it and save file and go back and run your program.
comment success! if it works. :)
When you click the text or link the image will be changed to another image so you can use the below script helps to you to change image on click the link:
<script>
$(document).ready(function(){
$('li').click(function(){
var imgpath = $(this).attr('dir');
$('#image').html('<img src='+imgpath+'>');
});
$('.btn').click(function(){
$('#thumbs').fadeIn(500);
$('#image').animate({marginTop:'10px'},200);
$(this).hide();
$('#hide').fadeIn('slow');
});
$('#hide').click(function(){
$('#thumbs').fadeOut(500,function (){
$('#image').animate({marginTop:'50px'},200);
});
$(this).hide();
$('#show').fadeIn('slow');
});
});
</script>
<div class="sandiv">
<h1 style="text-align:center;">The Human Body Parts :</h1>
<div id="thumbs">
<div class="sanl">
<ul>
<li dir="5.png">Human-body-organ-diag-1</li>
<li dir="4.png">Human-body-organ-diag-2</li>
<li dir="3.png">Human-body-organ-diag-3</li>
<li dir="2.png">Human-body-organ-diag-4</li>
<li dir="1.png">Human-body-organ-diag-5</li>
</ul>
</div>
</div>
<div class="man">
<div id="image">
<img src="2.png" width="348" height="375"></div>
</div>
<div id="thumbs">
<div class="sanr" >
<ul>
<li dir="5.png">Human-body-organ-diag-6</li>
<li dir="4.png">Human-body-organ-diag-7</li>
<li dir="3.png">Human-body-organ-diag-8</li>
<li dir="2.png">Human-body-organ-diag-9</li>
<li dir="1.png">Human-body-organ-diag-10</li>
</ul>
</div>
</div>
</div>
css:
<style>
body{ font-family:Tahoma, Geneva, sans-serif; color:#ccc; font-size:11px; margin:0; padding:0; background-color:#111111}
.sandiv{ width:980px;height:570px;margin:0 auto;margin-top:20px; padding:10px; background-color:#000;-webkit-box-shadow: 0 1px 2px #666;box-shadow: 0 1px 2px #666;}
#image{width:348px; height:375px; border-radius:100%;margin:0 auto; margin-top:50px; margin-bottom:20px;}
#thumb{width:400px;margin:0 auto; display:none;}
ul{list-style:none; padding:0; margin:0;}
li{ width:auto ; height:50px; border-radius:100%; margin:5px; cursor:pointer; }
.sanl
{
margin-top:50px;
float:left;
width:210px;
margin-left:30px;
margin-right:30px;
}
.sanr
{
margin-top:50px;
float:left;
width:210px;
margin-left:60px;
margin-right:30px;
}
.man
{
float:left;
width:350px;
margin-left:30px;
margin-right:30px;
}
</style>
I think the above code is very useful to you. This code i get from here or demo here for your reference
A warning about the Jquery Caret plugin.
It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end
"Without using count to find you want character in string" method.
import re
def count(s, ch):
pass
def main():
s = raw_input ("Enter strings what you like, for example, 'welcome': ")
ch = raw_input ("Enter you want count characters, but best result to find one character: " )
print ( len (re.findall ( ch, s ) ) )
main()
Just give your desired path if file does not exist earlier;
from os.path import abspath
with open ('C:\\Users\\Admin\\Desktop\\results.txt', mode = 'w') as final1:
print(final1.write('This is my new file.'))
print(f'Text has been processed and saved at {abspath(final1.name)}')
Output will be:
Text has been processed and saved at C:\Users\Admin\Desktop\results.txt
Tested on both spark-shell
version 1.6.3
and spark2-shell
version 2.3.0.2.6.5.179-4
, you can directly pipe to the shell's stdin like
spark-shell <<< "1+1"
or in your use case,
spark-shell < file.spark
You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
I would expect either:
// Makes sure item is at newIndex after the operation
T item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
... or:
// Makes sure relative ordering of newIndex is preserved after the operation,
// meaning that the item may actually be inserted at newIndex - 1
T item = list[oldIndex];
list.RemoveAt(oldIndex);
newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
list.Insert(newIndex, item);
... would do the trick, but I don't have VS on this machine to check.
An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".
as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....
Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.
public class MultipleInner {
static class Inner {
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Inner();
}
}
}
this is a code posted in this website...
for the question---> Can a Static Nested Class be Instantiated Multiple Times?
answer was--->
Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.
But in general, yes, a static nested type can be instantiated multiple times.
Note that technically, a static nested type is not an "inner" type.
If you're looking to get promise in resource call, you should use
Regions.query().$q.then(function(){ .... })
Update : the promise syntax is changed in current versions which reads
Regions.query().$promise.then(function(){ ..... })
Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.
To delete records from a table that have a datetime value in Date_column older than 30 days use this query:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < GETDATE() - 30
...or this:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(dd,-30,GETDATE())
To delete records from a table that have a datetime value in Date_column older than 12 hours:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(hh,-12,GETDATE())
To delete records from a table that have a datetime value in Date_column older than 15 minutes:
USE Database_name;
DELETE FROM Table_name
WHERE Date_column < DATEADD(mi,-15,GETDATE())
From: http://zarez.net/?p=542
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
In order to make a pull request you need to do the following steps:
It took me a while to figure this, hope this will help someone.
DDL is Data Definition Language: Just think you are defining the DB.
So we use CREATE,ALTER TRUNCATE commands.
DML is after defining we are Manipulating the data. So we use SELECT,INSERT, UPDATE, DELETE command.
Remember DDL commands are auto-committed. You don't need to use COMMIT statements.
DML (Data Manipulation Language) commands need to be commited/rolled back.
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.
I'm a beginner but...Up to my knowledge,the best way is
strncpy(dest_string,"",strlen(dest_string));
I tried most of these answers and they were all failing for TextViews that had autolink enabled but also had to use long press in the same place!
I made a custom class that works.
public class TextViewLinkLongPressUrl extends TextView {
private boolean isLongClick = false;
public TextViewLinkLongPressUrl(Context context) {
super(context);
}
public TextViewLinkLongPressUrl(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewLinkLongPressUrl(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && isLongClick) {
isLongClick = false;
return false;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
isLongClick = false;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isLongClick = false;
}
return super.onTouchEvent(event);
}
@Override
public boolean performLongClick() {
isLongClick = true;
return super.performLongClick();
}
}
This is a slight touch up to Glen Maynard's solution, which I think is the right way to do it. It just adds the padding element.
def hextobin(self, hexval):
'''
Takes a string representation of hex data with
arbitrary length and converts to string representation
of binary. Includes padding 0s
'''
thelen = len(hexval)*4
binval = bin(int(hexval, 16))[2:]
while ((len(binval)) < thelen):
binval = '0' + binval
return binval
Pulled it out of a class. Just take out self,
if you're working in a stand-alone script.
dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.
When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.
one of the good example:
SELECT *
FROM table1 tb1
LEFT JOIN (
SELECT *
FROM dblink('dbname=db2','SELECT id, code FROM table2')
AS tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;
Note: I am giving this information for future reference. Refrence
If you are using Firefox, alert(object.toSource())
should suffice for simple debugging purposes.
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
Well, for one thing your epression can be simplified:
$("#pDetails").attr("style")
since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.
If you just want to return the display value or something, use css():
$("#pDetails").css("display")
If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:
$("[style*='display: none']")
but if you just want to find things that are hidden, use this:
$(":hidden")
Thank you all who contributed to this thread and helped me figure out how to test for numeric values. I wanted to post my results for how to handle negative numbers, for those who may also find this thread when searching...
Note: My function requires a string to be passed, due to using Trim().
function IsNumeric($value) {
# This function will test if a string value is numeric
#
# Parameters::
#
# $value - String to test
#
return ($($value.Trim()) -match "^[-]?[0-9.]+$")
}
You don't have to use Calendar. You can just play with timestamps :
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days
UPDATE DO NOT FORGET TO ADD "l" for long by the end of 1000.
Please consider the below WARNING:
Adding 1000*60*60*24
milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
Using only substring()
and recursion:
public String rev(String rest) {
if (rest.equals(""))
return "";
return rev(rest.substring(1)) + rest.substring(0,1);
}
You might find this link helpful:
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
To replace the first match of $substring with $replacement:
${string/substring/replacement}
To replace all matches of $substring with $replacement:
${string//substring/replacement}
EDIT: Note that this applies to a variable named $string.
In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data
Simple change to syntax is all that is needed:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();
I don't think there is anything you can do to avoid what you are already doing, however, if you are building the table on the client with javascript, you can always add the style rules dynamically, so you can allow for any number of columns without cluttering up your css file with all those rules. See http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript if you don't know how to do this.
Edit: For your "sticky" toggle, you should just append class names rather than replacing them. For instance, you can give it a class name of "hide2 hide3" etc. I don't think you really need the "show" classes, since that would be the default. Libraries like jQuery make this easy, but in the absence, a function like this might help:
var modifyClassName = function (elem, add, string) {
var s = (elem.className) ? elem.className : "";
var a = s.split(" ");
if (add) {
for (var i=0; i<a.length; i++) {
if (a[i] == string) {
return;
}
}
s += " " + string;
}
else {
s = "";
for (var i=0; i<a.length; i++) {
if (a[i] != string)
s += a[i] + " ";
}
}
elem.className = s;
}
If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is
a(a==0) = [];
This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to
a(find(a==0)) = [];
And, when you set some array elements to [] in MATLAB, the convention is to delete them.
If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably
b = a(a ~= 0);
Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of
b = a(find(a ~= 0));
but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.
As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this
b = a(abs(a) >= tol);
This retains only those elements of a that are at least as large as your tolerance.
There are probably less than 20 entries in your xml.
change the code to this
for ($i=0;$i< sizeof($xml->entry); $i++)
...
A solution (for WPF) without WaitOne because it can cause an AbandonedMutexException. This solution uses the Mutex constructor that returns the createdNew boolean to check if the mutex is already created. It also uses the GetType().GUID so renaming an executable doesn't allow multiple instances.
Global vs local mutex see note in: https://docs.microsoft.com/en-us/dotnet/api/system.threading.mutex?view=netframework-4.8
private Mutex mutex;
private bool mutexCreated;
public App()
{
string mutexId = $"Global\\{GetType().GUID}";
mutex = new Mutex(true, mutexId, out mutexCreated);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
Because Mutex implements IDisposable it is released automatically but for completeness call dispose:
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
mutex.Dispose();
}
Move everything into a base class and add the allowEveryoneRule from the accepted answer. Also added ReleaseMutex though it doesn't look like it's really needed because it is released automatically by the OS (what if the application crashes and never calls ReleaseMutex would you need to reboot?).
public class SingleApplication : Application
{
private Mutex mutex;
private bool mutexCreated;
public SingleApplication()
{
string mutexId = $"Global\\{GetType().GUID}";
MutexAccessRule allowEveryoneRule = new MutexAccessRule(
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
MutexRights.FullControl,
AccessControlType.Allow);
MutexSecurity securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
// initiallyOwned: true == false + mutex.WaitOne()
mutex = new Mutex(initiallyOwned: true, mutexId, out mutexCreated, securitySettings);
}
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
if (mutexCreated)
{
try
{
mutex.ReleaseMutex();
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
mutex.Dispose();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (!mutexCreated)
{
MessageBox.Show("Already started!");
Shutdown();
}
}
}
One of the below solve your problem
URL::previous()
URL::back()
other
URL::current()
For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
Something along the following in a plugin file is what you are looking for:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
foreach (DataRow dr in ds.Tables[0].Rows)
{
//your code here
}
You could also use the RandomStringUtils from the Apache Commons project:
Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
Usages:
RandomStringUtils.randomAlphabetic(stringLength);
RandomStringUtils.randomAlphanumeric(stringLength);
Here's how to check which columns are the wrong collation:
SELECT table_schema, table_name, column_name, character_set_name, collation_name
FROM information_schema.columns
WHERE collation_name = 'latin1_general_ci'
ORDER BY table_schema, table_name,ordinal_position;
And here's the query to fix it:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET latin1 COLLATE 'latin1_swedish_ci';
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
Line ending format used in OS
CR
(Carriage Return \r
) and LF
(LineFeed \n
) pairLF
(LineFeed \n
)We can configure git to auto-correct line ending formats for each OS in two ways.
.gitattributes
filegit config --global core.autocrlf input
This will fix any CRLF
to LF
when you commit.
git config --global core.autocrlf true
This will make sure when you checkout in windows, all LF
will convert to CRLF
It is a good idea to keep a .gitattributes
file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.
* text=auto
This will treat all files as text files and convert to OS's line ending on checkout and back to LF
on commit automatically. If wanted to tell explicitly, then use
* text eol=crlf
* text eol=lf
First one is for checkout and second one is for commit.
*.jpg binary
Treat all .jpg
images as binary files, regardless of path. So no conversion needed.
Or you can add path qualifiers:
my_path/**/*.jpg binary
The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.
Basically the difference between them are performance characteristics and blocking behavior.
Taking the easiest first, ArrayBlockingQueue
is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.
The most important difference between LinkedBlockingQueue
and ConcurrentLinkedQueue
is that if you request an element from a LinkedBlockingQueue
and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue
will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
Simply say:
git branch -d <branch-name>
git push origin :<branch-name>
Open file/etc/nginx/nginx.conf
Add or change client_max_body_size 0;
import urllib2
for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"):
print line
try this query
SELECT ID, FirstName, LastName FROM table GROUP BY(FirstName)
So you want an element to be something it's not?
Generally speaking this isn't a good idea. If you need a link, use a link. Most of the time it's easier to just use the appropriate markup where it belongs.
That all said, sometimes you just have to break the rules. Now, the question doesn't have javascript, so I'm going to put the disclaimer here:
You can't have a <div>
act as a link without either using a link (or equivalent, such as a <form>
that only contains a submit button) or using JavaScript.
From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).
With that all said, lets dig into what makes a link a link.
Links are generally elements that you click on so that they navigate you to a new document.
It seems simple enough. Listen for a click event and change the location:
Don't do this$('.link').on('click', function () {_x000D_
window.location = 'http://example.com';_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="link">Fake Link</div>
_x000D_
There you have it, the <div>
is now a link. Wait...what's that? What about accessibility? Oh right, screen readers and users of assistive technology won't be able to click on the link, especially if they're only using the keyboard.
Fixing that's pretty simple, let's allow keyboard only users to focus the <div>
, and trigger the click event when they press Enter:
$('.link').on({_x000D_
'click': function () {_x000D_
window.location = 'http://example.com';_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="link" tabindex="0">Fake Link</div>
_x000D_
Again, there you have it, this <div>
is now a link. Wait...again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn't know that the <div>
is a link yet, so even though you can get there via keyboard, users aren't being told what to do with it.
Fortunately, there's an attribute that can be used to override an HTML element's default role, so that screen readers and the like know how to categorize customized elements, like our <div>
here. The attribute is of course the [role]
attribute, and it nicely tells screen readers that our <div>
is a link:
$('[role="link"]').on({_x000D_
'click': function () {_x000D_
window.location = 'http://example.com';_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0">Fake Link</div>
_x000D_
Finally, our <div>
is a lin---oh now the other devs are complaining. What now?
Ok, so the devs don't like the code. They tried to preventDefault
on the event, and it just keeps working. That's easy to fix:
$(document).on({_x000D_
'click': function (e) {_x000D_
if (!e.isDefaultPrevented()) {_x000D_
window.location = 'http://example.com';_x000D_
}_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13 && !e.isDefaultPrevented()) {_x000D_
$(this).trigger('click');_x000D_
}_x000D_
}_x000D_
}, '[role="link"]');_x000D_
_x000D_
$('[aria-disabled="true"]').on('click', function (e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0">Fake Link</div>_x000D_
<div role="link" aria-disabled="true" tabindex="0">Fake disabled link</div>
_x000D_
There we have it---THERE'S MORE? What else don't I know? Tell me everything NOW so that I can fix it!
window.open
.[data-*]
attributes, and call it a day with that one.<DIV>
NOT AN ANCHOR!well, I'll address the first four issues, and NO MORE. I've had it with this stupid custom element garbage. I should have just used an <a>
element from the beginning.
$(document).on({_x000D_
'click': function (e) {_x000D_
var target,_x000D_
href;_x000D_
if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) {_x000D_
target = $(this).data('target') || '_self';_x000D_
href = $(this).data('href');_x000D_
if (e.ctrlKey || e.shiftKey || e.which === 2) {_x000D_
target = '_blank'; //close enough_x000D_
}_x000D_
open(href, target);_x000D_
}_x000D_
},_x000D_
'keydown': function (e) {_x000D_
if (e.which === 13 && !e.isDefaultPrevented()) {_x000D_
$(this).trigger({_x000D_
type: 'click',_x000D_
ctrlKey: e.ctrlKey,_x000D_
altKey: e.altKey,_x000D_
shiftKey: e.shiftKey_x000D_
});_x000D_
}_x000D_
}_x000D_
}, '[role="link"]');_x000D_
_x000D_
$('[aria-disabled="true"]').on('click', function (e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div role="link" tabindex="0" data-href="http://example.com/">Fake Link</div>_x000D_
<div role="link" tabindex="0" data-href="http://example.com/" data-target="_blank">Fake Link With Target</div>_x000D_
<div role="link" aria-disabled="true" tabindex="0" data-href="http://example.com/">Fake disabled link</div>
_x000D_
Note that stack snippets won't open popup windows because of how they're sandboxed.
That's it. That's the end of this rabbit hole. All of that craziness when you could have simply had:
<a href="http://example.com/">
...your markup here...
</a>
The code I posted here probably has problems. It probably has bugs that even I don't realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it's simply not worth trying to emulate it 99% of the time.
I prefer the Underscore framework. It suggests many useful operations with objects. Your task:
var newArray = homes.filter(
price <= 1000 &
sqft >= 500 &
num_of_beds >=2 &
num_of_baths >= 2.5);
can be overwriten like:
var newArray = _.filter (homes, function(home) {
return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;
});
Hope it will be useful for you!
Graphically, the cron syntax for Quarz is (source):
+-------------------- second (0 - 59)
| +----------------- minute (0 - 59)
| | +-------------- hour (0 - 23)
| | | +----------- day of month (1 - 31)
| | | | +-------- month (1 - 12)
| | | | | +----- day of week (0 - 6) (Sunday=0 or 7)
| | | | | | +-- year [optional]
| | | | | | |
* * * * * * * command to be executed
So if you want to run a command every 30 minutes you can say either of these:
0 0/30 * * * * ?
0 0,30 * * * * ?
You can check crontab expressions using either of these:
There are two easy ways, depending on if you want to deal with exceptions or get a default value.
You can use the First<T>()
or the FirstOrDefault<T>()
extension method to get the first result or default(T)
.
var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0
GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL
. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.
Just a notice for a sharing hosting server or added on domains =
For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA
.
So create a folder to your root server, not into the public_html
and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700
. Give a try...
# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600);
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');
before session_start();
or put this in your .htaccess
file.
php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA
After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS
Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
.
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
Config caching
The laravel config spreads across dozens of files, and including
every one of them for each request is a costly process. To combine all of your config files into one, use:
php artisan config:cache
Keep in mind that any changes to the config will not have any effect once you cache it. To refresh the config cache, run the above command again. In case you want to completely get rid of the config cache, run
php artisan config:clear
Routes caching Routing is also an expensive task in laravel. To cache the routes.php file run the below command:
php artisan route:cache
Mind that it doesn't work with closures. In case you're using closures this is a great chance to move them into a controller, as the artisan command will throw an exception when trying to compile routes that are bound to closures instead of proper controller methods. In the same as the config cache, any changes to routes.php will not have any effect anymore. To refresh the cache, run the above command everytime you do a change to the routes file. To completely get rid of the route cache, run the below command:
php artisan route:clear
Classmap optimization
It's not uncommon for a medium-sized project to be spread across hundreds of PHP files. As good coding behaviours dictate us, everything has its own file. This, of course, does not come without drawbacks. Laravel has to include dozens of different files for each request, which is a costly thing to do.
Hence, a good optimization method is declaring which files are used for every request (this is, for example, all your service providers, middlewares and a few more) and combining them in only one file, which will be afterwards loaded for each request. This not different from combining all your javascript files into one, so the browser will have to make fewer requests to the server.
The additional compiles files (again: service providers, middlewares and so on) should be declared by you in config/compile.php, in the files key. Once you put there everything essential for every request made to your app, concatenate them in one file with:
php artisan optimize --force
Optimizing the composer autoload
This one is not only for laravel, but for any application that's making use of composer.
I'll explain first how the PSR-4 autoload works, and then I'll show you what command you should run to optimize it. If you're not interested in knowing how composer works, I recommend you jumping directly to the console command.
When you ask composer for the App\Controllers\AuthController
class, it first searches for a direct association in the classmap. The classmap is an array with 1-to-1 associations of classes and files. Since, of course, you did not manually add the Login class and its associated file to the classmap, composer will move on and search in the namespaces.
Because App is a PSR-4 namespace, which comes by default with Laravel and it's associated to the app/
folder, composer will try converting the PSR-4 class name to a filename with basic string manipulation procedures. In the end, it guesses that App\Controllers\AuthController
must be located in an AuthController.php file, which is in a Controllers/
folder that should luckily be in the namespace folder, which is app/
.
All this hard work only to get that the App\Controllers\AuthController
class exists in the app/Controllers/AuthController.php
file. In order to have composer scanning your entire application and create direct 1-to-1 associations of classes and files, run the following command:
composer dumpautoload -o
Keep in mind that if you already ran php artisan optimize --force, you don't have to run this one anymore. Since the optimize command already tells composer to create an optimized autoload.
I had a 12GB file to edit today. The vim LargeFile plugin did not work for me. It still used up all my memory and then printed an error message :-(. I could not use hexedit for either, as it cannot insert anything, just overwrite. Here is an alternative approach:
You split the file, edit the parts and then recombine it. You still need twice the disk space though.
Grep for something surrounding the line you would like to edit:
grep -n 'something' HUGEFILE | head -n 1
Extract that range of the file. Say the lines you want to edit are at line 4 and 5. Then do:
sed -n -e '4,5p' -e '5q' HUGEFILE > SMALLPART
-n
option is required to suppress the default behaviour of sed to print everything4,5p
prints lines 4 and 55q
aborts sed after processing line 5 Edit SMALLPART
using your favourite editor.
Combine the file:
(head -n 3 HUGEFILE; cat SMALLPART; sed -e '1,5d' HUGEFILE) > HUGEFILE.new
HUGEFILE.new
will now be your edited file, you can delete the original HUGEFILE
.
I had the same issue before. Try this answer here, it works on my site.
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function() {
if ($(this).attr("href") !== "#") {
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL) {
$('nav a').parents('li, ul').removeClass('active');
$(this).parent('li').addClass('active');
return false;
}
}
});
});
Source: It was original posted here how to set active class to nav menu from twitter bootstrap
To make it read-only, the DropDownStyle property to DropDownStyle.DropDownList.
To populate the ComboBox, you will need to have a object like Language or so containing both for instance:
public class Language {
public string Name { get; set; }
public string Code { get; set; }
}
Then, you may bind a IList to your ComboBox.DataSource property like so:
IList<Language> languages = new List<Language>();
languages.Add(new Language("English", "en"));
languages.Add(new Language("French", "fr"));
ComboxBox.DataSource = languages;
ComboBox.DisplayMember = "Name";
ComboBox.ValueMember = "Code";
This will do exactly what you expect.
Update 1
I have modified it to use StreamWriter instead, add an option to check if you need column headers in your output.
public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
if (dtSource == null || writer == null) return false;
if (includeHeader)
{
string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", columnNames));
writer.Flush();
}
foreach (DataRow row in dtSource.Rows)
{
string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
writer.WriteLine(String.Join(",", fields));
writer.Flush();
}
return true;
}
As you can see, you can choose the output by initial StreamWriter, if you use StreamWriter(Stream BaseStream), you can write csv into MemeryStream, FileStream, etc.
Origin
I have an easy datatable to csv function, it serves me well:
public static void DataTableToCsv(DataTable dt, string csvFile)
{
StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(csvFile, sb.ToString(), Encoding.Default);
}
If You're using php5.6 and Ubuntu 18.04 Then run these two commands in your terminal your errors will be solved definitely.
sudo apt-get install php5.6-gd
then restart your apache server by this command.
sudo service apache2 restart
To detach from the container you simply hold Ctrl and press P + Q.
To attach to a running container you use:
$ docker container attach "container_name"
Despite the fact that a lot of solutions have been already proposed.
I guess that the following one will be short and clear:
public class IntegerToRoman {
public static String intToRoman(int number) {
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] units = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[number / 1000]
+ hundreds[(number % 1000) / 100]
+ tens[(number % 100) / 10]
+ units[number % 10];
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 5, 10, 14, 17, 20, 25, 38, 49, 63, 72, 81, 97, 98, 99, 100, 101, 248, 253, 799, 1325, 1900, 2000, 2456, 1715};
final Instant startTimeIter = Instant.now();
for (int number : numbers) {
System.out.printf("%4d -> %8s\n", number, intToRoman(number));
}
final Instant endTimeIter = Instant.now();
System.out.printf("Elapsed time: %d ms\n\n", Duration.between(startTimeIter, endTimeIter).toMillis());
}
}
Output:
1 -> I
2 -> II
3 -> III
...
2456 -> MMCDLVI
1715 -> MDCCXV
Elapsed time: 66 ms
Logic is quite simple:
3000
numberFor Spring boot v2.1.3.RELEASE, just add the follow properties into application.propertes:
spring.main.web-application-type=none
@user544079
Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">
So just thought I would throw my two cents in here...
No one has provided a true answer to OP question it seems, everyone either responds with 'NO DONT USE os.system() it's evil!!!' without explanation or provides a solution that relies on printing new lines.
For those that need to clear the terminal screen and scroll back, for whatever reason, you can use the following code:
import os
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')
print('A bunch of garbage so we can garble up the screen...')
clear()
# Same effect, less characters...
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls||echo -e \\\\033c')
This has the OP's desired effect. It does use the os.system() command so if that's evil and someone knows a way of implementing this using subprocess.call() please comment as I would also prefer to use subprocess but am not familiar with it at all.
Google has threatened to remove apps from the Play Store if they use accessibility services for non-accessibility purposes. However, this is reportedly being reconsidered.
AccessibilityService
AccessibilityService
.onAccessibilityEvent
callback, check for the TYPE_WINDOW_STATE_CHANGED
event type to determine when the current window changes.PackageManager.getActivityInfo()
.GET_TASKS
permission.AccessibilityService
, they can't press the OK button if an app has placed an overlay on the screen. Some apps that do this are Velis Auto Brightness and Lux. This can be confusing because the user might not know why they can't press the button or how to work around it. AccessibilityService
won't know the current activity until the first change of activity.public class WindowChangeDetectingService extends AccessibilityService {
@Override
protected void onServiceConnected() {
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16)
//Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
setServiceInfo(config);
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
if (event.getPackageName() != null && event.getClassName() != null) {
ComponentName componentName = new ComponentName(
event.getPackageName().toString(),
event.getClassName().toString()
);
ActivityInfo activityInfo = tryGetActivity(componentName);
boolean isActivity = activityInfo != null;
if (isActivity)
Log.i("CurrentActivity", componentName.flattenToShortString());
}
}
}
private ActivityInfo tryGetActivity(ComponentName componentName) {
try {
return getPackageManager().getActivityInfo(componentName, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
@Override
public void onInterrupt() {}
}
Merge this into your manifest:
<application>
<service
android:label="@string/accessibility_service_name"
android:name=".WindowChangeDetectingService"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="@xml/accessibilityservice"/>
</service>
</application>
Put this in res/xml/accessibilityservice.xml
:
<?xml version="1.0" encoding="utf-8"?>
<!-- These options MUST be specified here in order for the events to be received on first
start in Android 4.1.1 -->
<accessibility-service
xmlns:tools="http://schemas.android.com/tools"
android:accessibilityEventTypes="typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagIncludeNotImportantViews"
android:description="@string/accessibility_service_description"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:ignore="UnusedAttribute"/>
Each user of the app will need to explicitly enable the AccessibilityService
in order for it to be used. See this StackOverflow answer for how to do this.
Note that the user won't be able to press the OK button when trying to enable the accessibility service if an app has placed an overlay on the screen, such as Velis Auto Brightness or Lux.
And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message
MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'
A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell
sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep zzZZ"; afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s
You can set a default encoding-set whenever you run eclipse.exe.
-Dfile.encoding=UTF-8
The 4K limit you read about is for the entire cookie, including name, value, expiry date etc. If you want to support most browsers, I suggest keeping the name under 4000 bytes, and the overall cookie size under 4093 bytes.
One thing to be careful of: if the name is too big you cannot delete the cookie (at least in JavaScript). A cookie is deleted by updating it and setting it to expire. If the name is too big, say 4090 bytes, I found that I could not set an expiry date. I only looked into this out of interest, not that I plan to have a name that big.
To read more about it, here are the "Browser Cookie Limits" for common browsers.
While on the subject, if you want to support most browsers, then do not exceed 50 cookies per domain, and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.
This means you can have 1 cookie of 4093 bytes, or 2 cookies of 2045 bytes, etc.
I used to say 4095 bytes due to IE7, however now Mobile Safari comes in with 4096 bytes with a 3 byte overhead per cookie, so 4093 bytes max.
Well, IMHO..
With regards to #1, I have a strongly typed Master View which has a property to access whatever the Session object represents....in my instance the stongly typed Master View is generic which gives me some flexibility with regards to strongly typed View Pages
ViewMasterPage<AdminViewModel>
AdminViewModel
{
SomeImportantObjectThatWasInSession ImportantObject
}
AdminViewModel<TModel> : AdminViewModel where TModel : class
{
TModel Content
}
and then...
ViewPage<AdminViewModel<U>>
Changing the mirrorlist URL from https to http fixed the issue for me.
If you want the word to start with "stop", you can use the following pattern. "^stop.*"
This will match words starting with stop followed by anything.
You can add 1 to each example New = 5; old = 0;
(1+new) - (old+1) / (old +1) 5/ 1 * 100 ==> 500%
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
This query was very useful for me. It shows all values that don't have any matches
select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)
Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.
import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']
The appropriate way for doing this:
@app.route('/')
def index():
if form.validate_on_submit():
if 'download' in request.form:
pass # do something
elif 'watch' in request.form:
pass # do something else
Put watch
and download
buttons into your template:
<input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">
I will suggest you to use below the library because it allows you to set default values in one file and you can use it everywhere in the project without making one line of change. https://github.com/Shahbaz89khan/ShadowView
Option A:
git clone [email protected]:whatever folder-name
Ergo, for right here
use:
git clone [email protected]:whatever .
Option B:
Move the .git
folder, too. Note that the .git
folder is hidden in most graphical file explorers, so be sure to show hidden files.
mv /where/it/is/right/now/* /where/I/want/it/
mv /where/it/is/right/now/.* /where/I/want/it/
The first line grabs all normal files, the second line grabs dot-files. It is also possibe to do it in one line by enabling dotglob (i.e. shopt -s dotglob
) but that is probably a bad solution if you are asking the question this answer answers.
Better yet:
Keep your working copy somewhere else, and create a symbolic link. Like this:
ln -s /where/it/is/right/now /the/path/I/want/to/use
For your case this would be something like:
ln -sfn /opt/projectA/prod/public /httpdocs/public
Which easily could be changed to test if you wanted it, i.e.:
ln -sfn /opt/projectA/test/public /httpdocs/public
without moving files around. Added -fn
in case someone is copying these lines (-f
is force, -n
avoid some often unwanted interactions with already and non-existing links).
If you just want it to work, use Option A, if someone else is going to look at what you have done, use Option C.
A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Mask: 00001111b
Value: 01010101b
Result: 00000101b
Masking is implemented using AND, so in C we get:
uint8_t stuff(...) {
uint8_t mask = 0x0f; // 00001111b
uint8_t value = 0x55; // 01010101b
return mask & value;
}
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &
, and >>
(shift right). This is how we can extract the four bytes from a 32-bit integer:
void more_stuff(uint32_t value) { // Example value: 0x01020304
uint32_t byte1 = (value >> 24); // 0x01020304 >> 24 is 0x01 so
// no masking is necessary
uint32_t byte2 = (value >> 16) & 0xff; // 0x01020304 >> 16 is 0x0102 so
// we must mask to get 0x02
uint32_t byte3 = (value >> 8) & 0xff; // 0x01020304 >> 8 is 0x010203 so
// we must mask to get 0x03
uint32_t byte4 = value & 0xff; // here we only mask, no shifting
// is necessary
...
}
Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:
uint32_t byte3 = (value & 0xff00) >> 8;
Put the following code before int main()
:
using namespace std;
And you will be able to use cout
.
For example:
#include<iostream>
using namespace std;
int main(){
char t = 'f';
char *t1;
char **t2;
cout<<t;
return 0;
}
Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/
Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std;
at the top of your code. For detailed correct approach, please read the answers to this related SO question.
This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active
next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache
(where all of jQuery.data()
goes).
I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart()
and $.ajaxStop()
(which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.
When jQuery starts an AJAX request, this happens:
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
This is what causes the $.ajaxStart()
event to fire, the number of connections just went from 0 to 1 (jQuery.active++
isn't 0 after this one, and !0 == true
), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend
abort via return false
or an ajax call complete
function runs):
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
This is what causes the $.ajaxStop()
event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.
Use ConstraintLayout. Here is an example that will center the view according to the width and height of the parent screen:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF00FF"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent=".6"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".4"></LinearLayout>
</android.support.constraint.ConstraintLayout>
You might need to change your gradle to get the latest version of ConstraintLayout:
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
It is a conditional statement.
If browser supprts e.keyCode then take e.keyCode else e.charCode.
It is similar to
var code = event.keyCode || event.charCode
event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.
event.charCode: Returns the Unicode value of a character key pressed during a keypress event.
Create a ComboBox SelectionChanged Event and set ItemsSource="{Binding}" in the WPF design:
Code:
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ob = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
MessageBox.Show(ob);
}
Another interesting solution found here is using ES6 Map:
export enum Type {
low,
mid,
high
}
export const TypeLabel = new Map<number, string>([
[Type.low, 'Low Season'],
[Type.mid, 'Mid Season'],
[Type.high, 'High Season']
]);
USE
console.log(TypeLabel.get(Type.low)); // Low Season
If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:
element.find(">:first-child").toggleClass("redClass");
Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):
element.children(":first").toggleClass("redClass");
What about something like:
static inline double radians (double degrees) {return degrees * M_PI/180;}
UIImage* rotate(UIImage* src, UIImageOrientation orientation)
{
UIGraphicsBeginImageContext(src.size);
CGContextRef context = UIGraphicsGetCurrentContext();
if (orientation == UIImageOrientationRight) {
CGContextRotateCTM (context, radians(90));
} else if (orientation == UIImageOrientationLeft) {
CGContextRotateCTM (context, radians(-90));
} else if (orientation == UIImageOrientationDown) {
// NOTHING
} else if (orientation == UIImageOrientationUp) {
CGContextRotateCTM (context, radians(90));
}
[src drawAtPoint:CGPointMake(0, 0)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
You could use super(ChildClass, self).__init__()
class BaseClass(object):
def __init__(self, *args, **kwargs):
pass
class ChildClass(BaseClass):
def __init__(self, *args, **kwargs):
super(ChildClass, self).__init__(*args, **kwargs)
Your indentation is incorrect, here's the modified code:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super(ElectricCar, self).__init__(model, color, mpg)
car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__
Here's the output:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
Starting from the data.table y, you can just write:
y[, (cols):=lapply(.SD, function(i){i[is.na(i)] <- 0; i}), .SDcols = cols]
Don't forget to library(data.table)
before creating y
and running this command.
What worked for me was to completely delete the entitlements file, from the groups list, and from the Build Settings in both Project and Target. Then I recreated the entitlements from the Summary tab in the target, and it loaded fine without any error messages.
All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref ..
section it is named as ConsoleAppender. They need to match.
You can add multiple appenders to your log config but you need to register each of them in the <root>
section.
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />
You can also refer to the apache documentation on configuring log4net.
Try to use java.util.Arrays
. This module has a variety of useful methods that could be used related to Arrays.
Arrays.toString(your_array_here[]);
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://....',
success: function () {
alert("done!"+ geturl.getAllResponseHeaders());
}
});
You were almost there with your use of the split
function. You just needed to join the strings, like follows.
>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'
Although, I would recommend using the os.path.dirname
function to do this, you just need to pass the string, and it'll do the work for you. Since, you seem to be on windows, consider using the abspath
function too. An example:
>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'
If you want both the file name and the directory path after being split, you can use the os.path.split
function which returns a tuple, as follows.
>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')
An alternative implementation in pure powershell (without Add-Type
of c# source):
#requires -Version 5
#requires -PSEdition Desktop
class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
[bool] CheckValidationResult([System.Net.ServicePoint] $a,
[System.Security.Cryptography.X509Certificates.X509Certificate] $b,
[System.Net.WebRequest] $c,
[int] $d) {
return $true
}
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()
I will post answer that helped me:
go to url:
chrome://settings/clearBrowserData
it should invoke popup and then..
cached images and files
.from beginning
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
This would work as well:
df = pd.DataFrame()
new_line = pd.Series({'A2M': 4.059, 'A2ML1': 4.28}, name='HCC1419')
df = df.append(new_line, ignore_index=False)
The name
in the Series will be the index in the dataframe. ignore_index=False
is the important flag in this case.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String arg[])throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
StringTokenizer st;
String entrada = "";
long x=0, y=0;
while((entrada = br.readLine())!=null){
st = new StringTokenizer(entrada," ");
while(st.hasMoreTokens()){
x = Long.parseLong(st.nextToken());
y = Long.parseLong(st.nextToken());
}
System.out.println(x>y ?(x-y)+"":(y-x)+"");
}
}
}
This solution is a bit more efficient than the one above because it takes up the 2.128 and this takes 1.308 seconds to solve the problem.
(?!Andrea)
This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.
This method should help to programmatically generate values guaranteed to be 100% compatible with .properties
files:
public static String escapePropertyValue(final String value) {
if (value == null) {
return null;
}
try (final StringWriter writer = new StringWriter()) {
final Properties properties = new Properties();
properties.put("escaped", value);
properties.store(writer, null);
writer.flush();
final String stringifiedProperties = writer.toString();
final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
final Matcher matcher = pattern.matcher(stringifiedProperties);
if (matcher.find() && matcher.groupCount() <= 2) {
return matcher.group(matcher.groupCount());
}
// This should never happen unless the internal implementation of Properties::store changed
throw new IllegalStateException("Could not escape property value");
} catch (final IOException ex) {
// This should never happen. IOException is only because the interface demands it
throw new IllegalStateException("Could not escape property value", ex);
}
}
You can call it like this:
final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"
This method a little bit expensive but, writing properties to a file is typically an sporadic operation anyway.
I was working on a similar problem. @S.Lott said "If you have the list of variables, what's the point of "discovering" their names?" And my answer is just to see if it could be done and if for some reason you want to sort your variables by type into lists. So anyways, in my research I came came across this thread and my solution is a bit expanded and is based on @rlotun solution. One other thing, @unutbu said, "This idea has merit, but note that if two variable names reference the same value (e.g. True), then an unintended variable name might be returned." In this exercise that was true so I dealt with it by using a list comprehension similar to this for each possibility: isClass = [i for i in isClass if i != 'item']
. Without it "item" would show up in each list.
__metaclass__ = type
from types import *
class Class_1: pass
class Class_2: pass
list_1 = [1, 2, 3]
list_2 = ['dog', 'cat', 'bird']
tuple_1 = ('one', 'two', 'three')
tuple_2 = (1000, 2000, 3000)
dict_1 = {'one': 1, 'two': 2, 'three': 3}
dict_2 = {'dog': 'collie', 'cat': 'calico', 'bird': 'robin'}
x = 23
y = 29
pie = 3.14159
eee = 2.71828
house = 'single story'
cabin = 'cozy'
isClass = []; isList = []; isTuple = []; isDict = []; isInt = []; isFloat = []; isString = []; other = []
mixedDataTypes = [Class_1, list_1, tuple_1, dict_1, x, pie, house, Class_2, list_2, tuple_2, dict_2, y, eee, cabin]
print '\nMIXED_DATA_TYPES total count:', len(mixedDataTypes)
for item in mixedDataTypes:
try:
# if isinstance(item, ClassType): # use this for old class types (before 3.0)
if isinstance(item, type):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isClass.append(mapping_as_str)
isClass = [i for i in isClass if i != 'item']
elif isinstance(item, ListType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isList.append(mapping_as_str)
isList = [i for i in isList if i != 'item']
elif isinstance(item, TupleType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isTuple.append(mapping_as_str)
isTuple = [i for i in isTuple if i != 'item']
elif isinstance(item, DictType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isDict.append(mapping_as_str)
isDict = [i for i in isDict if i != 'item']
elif isinstance(item, IntType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isInt.append(mapping_as_str)
isInt = [i for i in isInt if i != 'item']
elif isinstance(item, FloatType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isFloat.append(mapping_as_str)
isFloat = [i for i in isFloat if i != 'item']
elif isinstance(item, StringType):
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
isString.append(mapping_as_str)
isString = [i for i in isString if i != 'item']
else:
for k, v in list(locals().iteritems()):
if v is item:
mapping_as_str = k
other.append(mapping_as_str)
other = [i for i in other if i != 'item']
except (TypeError, AttributeError), e:
print e
print '\n isClass:', len(isClass), isClass
print ' isList:', len(isList), isList
print ' isTuple:', len(isTuple), isTuple
print ' isDict:', len(isDict), isDict
print ' isInt:', len(isInt), isInt
print ' isFloat:', len(isFloat), isFloat
print 'isString:', len(isString), isString
print ' other:', len(other), other
# my output and the output I wanted
'''
MIXED_DATA_TYPES total count: 14
isClass: 2 ['Class_1', 'Class_2']
isList: 2 ['list_1', 'list_2']
isTuple: 2 ['tuple_1', 'tuple_2']
isDict: 2 ['dict_1', 'dict_2']
isInt: 2 ['x', 'y']
isFloat: 2 ['pie', 'eee']
isString: 2 ['house', 'cabin']
other: 0 []
'''
Since the title didn't specify that it has to be programmatic I'll assume that it was a genuine debugging/privacy management issue and solution is browser dependent and requires a browser with built in detailed cookie management toll and/or a debugging module or a plug-in/extension. I'm going to list one and ask other people to write up on browsers they know in detail and please be precise with versions.
Chromium, Iron build (SRWare Iron 4.0.280)
The wrench(tool) menu: Options / Under The Hood / [Show cookies and website permissions] For related domains/sites type the suffix into the search box (like .foo.tv). Caveat: when you have a node (site or cookie) click-highlighted only use [Remove] to kill specific subtrees. Using [Remove All] will still delete cookies for all sites selected by search and waste your debugging session.
You are quite right to be concerned - static method calls are particularly problematic for unit testing as you cannot easily mock your dependencies. What I am going to show you is how to let the Spring IoC container do the dirty work for you, leaving you with neat, testable code. SecurityContextHolder is a framework class and while it may be ok for your low-level security code to be tied to it, you probably want to expose a neater interface to your UI components (i.e. controllers).
cliff.meyers mentioned one way around it - create your own "principal" type and inject an instance into consumers. The Spring <aop:scoped-proxy/> tag introduced in 2.x combined with a request scope bean definition, and the factory-method support may be the ticket to the most readable code.
It could work like following:
public class MyUserDetails implements UserDetails {
// this is your custom UserDetails implementation to serve as a principal
// implement the Spring methods and add your own methods as appropriate
}
public class MyUserHolder {
public static MyUserDetails getUserDetails() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
return (MyUserDetails) a.getPrincipal();
}
}
}
public class MyUserAwareController {
MyUserDetails currentUser;
public void setCurrentUser(MyUserDetails currentUser) {
this.currentUser = currentUser;
}
// controller code
}
Nothing complicated so far, right? In fact you probably had to do most of this already. Next, in your bean context define a request-scoped bean to hold the principal:
<bean id="userDetails" class="MyUserHolder" factory-method="getUserDetails" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="controller" class="MyUserAwareController">
<property name="currentUser" ref="userDetails"/>
<!-- other props -->
</bean>
Thanks to the magic of the aop:scoped-proxy tag, the static method getUserDetails will be called every time a new HTTP request comes in and any references to the currentUser property will be resolved correctly. Now unit testing becomes trivial:
protected void setUp() {
// existing init code
MyUserDetails user = new MyUserDetails();
// set up user as you wish
controller.setCurrentUser(user);
}
Hope this helps!
Use open(fn, 'rb').read().decode('utf-8')
instead of just open(fn).read()
The port for the Vue-cli webpack template is found in your app root's myApp/config/index.js
.
All you have to do is modify the port
value inside the dev
block:
dev: {
proxyTable: {},
env: require('./dev.env'),
port: 4545,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
cssSourceMap: false
}
Now you can access your app with localhost:4545
also if you have .env
file better to set it from there
As @kirbyfan64sos notes in a comment, /home
is NOT your home directory (a.k.a. home folder):
The fact that /home
is an absolute, literal path that has no user-specific component provides a clue.
While /home
happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users
.
What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:
cd
with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
cd # changes to home dir; e.g., '/home/jdoe'
~
by itself / unquoted ~/
at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash
)
echo ~ # outputs, e.g., '/home/jdoe'
$HOME
- as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME
is a predefined, user-specific environment variable:
cd "$HOME/tmp" # changes to your personal folder for temp. files
Thus, to create the desired folder, you could use:
mkdir "$HOME/bin" # same as: mkdir ~/bin
Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied
error.
This can also occur when the path ends in a '' followed by the closing quotation mark. e.g. The following line is passed as one of the arguments and this is not right:
"c:\users\abc\"
instead pass that argument as shown below so that the last backslash is escaped instead of escaping the quotation mark.
"c:\users\abc\\"
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }
In my case $(document).ready(function() was missing. Try this.
$(document).ready(function(){
("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
});
You can use CellDateFormatter to fetch the Date in the same format as in excel cell. See the following code:
CellValue cv = formulaEv.evaluate(cell);
double dv = cv.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = HSSFDateUtil.getJavaDate(dv);
String df = cell.getCellStyle().getDataFormatString();
strValue = new CellDateFormatter(df).format(date);
}
This works well for me:
CREATE FUNCTION [dbo].[StripNonNumerics]
(
@Temp varchar(255)
)
RETURNS varchar(255)
AS
Begin
Declare @KeepValues as varchar(50)
Set @KeepValues = '%[^0-9]%'
While PatIndex(@KeepValues, @Temp) > 0
Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')
Return @Temp
End
Then call the function like so to see the original something next to the sanitized something:
SELECT Something, dbo.StripNonNumerics(Something) FROM TableA
Could it be a one to many relationship between the left and right tables?
To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.
It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER
.
reg
and wire
specify how the object will be assigned and are therefore only meaningful for outputs.
If you plan to assign your output in sequential code,such as within an always
block, declare it as a reg
(which really is a misnomer for "variable" in Verilog). Otherwise, it should be a wire
, which is also the default.
Use the source, Luke.
No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.
Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.
This should works too. First create an absolute <div>
element with absolute position and 100% height:
<div id="h" style="position:absolute;top:0;bottom:0;"></div>
Then, get the window height from that element via offsetHeight
var winHeight = document.getElementById('h').offsetHeight;
Update:
function getBrowserSize() {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = 0;
div.style.left = 0;
div.style.width = '100%';
div.style.height = '100%';
document.documentElement.appendChild(div);
var results = {
width: div.offsetWidth,
height: div.offsetHeight
};
div.parentNode.removeChild(div); // remove the `div`
return results;
}
console.log(getBrowserSize());
I think it would be interesting to write both of them in a way that only by switching some lines of code would give you one algorithm or the other, so that you will see that your dillema is not so strong as it seems to be at first.
I personally like the interpretation of BFS as flooding a landscape: the low altitude areas will be flooded first, and only then the high altitude areas would follow. If you imagine the landscape altitudes as isolines as we see in geography books, its easy to see that BFS fills all area under the same isoline at the same time, just as this would be with physics. Thus, interpreting altitudes as distance or scaled cost gives a pretty intuitive idea of the algorithm.
With this in mind, you can easily adapt the idea behind breadth first search to find the minimum spanning tree easily, shortest path, and also many other minimization algorithms.
I didnt see any intuitive interpretation of DFS yet (only the standard one about the maze, but it isnt as powerful as the BFS one and flooding), so for me it seems that BFS seems to correlate better with physical phenomena as described above, while DFS correlates better with choices dillema on rational systems (ie people or computers deciding which move to make on a chess game or going out of a maze).
So, for me the difference between lies on which natural phenomenon best matches their propagation model (transversing) in real life.
As an alternative:
Using CROSS APPLY and VALUES performs this operation quite simply and efficiently with just a single pass of the table (unlike union queries that do one pass for every column)
SELECT
ca.ColName, ca.ColValue
FROM YOurTable
CROSS APPLY (
Values
('ScripName' , ScripName),
('ScripCode' , ScripCode),
('Price' , cast(Price as varchar(50)) )
) as CA (ColName, ColValue)
Personally I find this syntax easier than using unpivot.
NB: You must take care that all source columns are converted into compatible types for the single value column
As I needed get all elements in a nice way I encountered this SO subject "Traversing 2 dimensional associative array/object" - no matter the name for me, because functionality counts.
var imgs_pl = {
'offer': { 'img': 'wer-handwritter_03.png', 'left': 1, 'top': 2 },
'portfolio': { 'img': 'wer-handwritter_10.png', 'left': 1, 'top': 2 },
'special': { 'img': 'wer-handwritter_15.png', 'left': 1, 'top': 2 }
};
for (key in imgs_pl) {
console.log(key);
for (subkey in imgs_pl[key]) {
console.log(imgs_pl[key][subkey]);
}
}
$ git remote add origin https://github.com/git/git.git
--- You will run this command to link your github project to origin. Here origin is user-defined.
You can rename it by $ git remote rename old-name new-name
$ git fetch origin
- Downloads objects and refs from remote repository to your local computer [origin/master]. That means it will not affect your local master branch unless you merge them using $ git merge origin/master
. Remember to checkout the correct branch where you need to merge before run this command
Note: Fetched content is represented as a remote branch. Fetch gives you a chance to review changes before integrating them into your copy of the project. To show changes between yours and remote $git diff master..origin/master
The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.
The Image I/O
class provides the following method for saving an image:
static boolean ImageIO.write(RenderedImage im, String formatName, File output) throws IOException
The tutorial explains that
The BufferedImage class implements the RenderedImage interface.
so it's able to be used in the method.
For example,
try {
BufferedImage bi = getMyImage(); // retrieve image
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
// handle exception
}
It's important to surround the write
call with a try block because, as per the API, the method throws an IOException
"if an error occurs during writing"
Also explained are the method's objective, parameters, returns, and throws, in more detail:
Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.
Parameters:
im - a RenderedImage to be written.
formatName - a String containg the informal name of the format.
output - a File to be written to.
Returns:
false if no appropriate writer is found.
Throws:
IllegalArgumentException - if any parameter is null.
IOException - if an error occurs during writing.
However, formatName
may still seem rather vague and ambiguous; the tutorial clears it up a bit:
The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.
But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.
For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.
There are, however, additional formats you can use:
The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.
String writerNames[] = ImageIO.getWriterFormatNames();
The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.
For a full and practical example, one can refer to Oracle's SaveImage.java
example.
Found the solution in Spring security examples posted in Github.
WebSecurityConfigurerAdapter
has a overloaded configure
message that takes WebSecurity
as argument which accepts ant matchers on requests to be ignored.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/authFailure");
}
See Spring Security Samples for more details
I agree with @Lukasz Rzanek that we can use git plugin
But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory
The best, quickest and easiest way to resolve the comma in data issue is to use Excel to save a comma separated file after having set Windows' list separator setting to something other than a comma (such as a pipe). This will then generate a pipe (or whatever) separated file for you that you can then import. This is described here.
You can get it in a programmatic way via an SSH library (https://code.google.com/p/sshxcute)
public static String getIpAddress() throws TaskExecFailException{
ConnBean cb = new ConnBean(host, username, password);
SSHExec ssh = SSHExec.getInstance(cb);
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
String Result = ssh.exec(sampleTask).sysout;
ssh.disconnect();
return Result;
}
This happened to me, I tried all the possible solutions with no luck!
Finaly I realized that the problem was with Jupyter notebook environment, not with sklearn!
I solved the problem by re-installing Jupyter at the same environment as sklearn
the command is: conda install -c anaconda ipython
. Done...
You can try using string replace:
string = string.replace('\r', '').replace('\n', '')
You could either explicitly name the columns you want to keep, like so:
keep = [a.id, a.julian_date, a.user_id, b.quan_created_money, b.quan_created_cnt]
Or in a more general approach you'd include all columns except for a specific one via a list comprehension. For example like this (excluding the id
column from b
):
keep = [a[c] for c in a.columns] + [b[c] for c in b.columns if c != 'id']
Finally you make a selection on your join result:
d = a.join(b, a.id==b.id, 'outer').select(*keep)
You just try this, Its so easy
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>
FILL_PARENT
is deprecated in API level 8 and MATCH_PARENT
use higherlevel API
If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:
UPDATE myTable ...
IF @@ROWCOUNT=0
INSERT INTO myTable ....
You can also use the MERGE
syntax if you're doing this with sets of data rather than single rows.
If you want to INSERT
and not UPDATE
then you can just write your single INSERT
statement and use WHERE NOT EXISTS (SELECT ...)
I saw a more concise method of getting Array.prototype
methods in general that works just as well. Converting an HTMLCollection
object into an Array
object is demonstrated below:
[].slice.call( yourHTMLCollectionObject );
And, as mentioned in the comments, for old browsers such as IE7 and earlier, you simply have to use a compatibility function, like:
function toArray(x) {
for(var i = 0, a = []; i < x.length; i++)
a.push(x[i]);
return a
}
I know this is an old question, but I felt the accepted answer was a little incomplete; so I thought I'd throw this out there FWIW.
You can change the labels' text by adorning the property with the DisplayName
attribute.
[DisplayName("Someking Status")]
public string SomekingStatus { get; set; }
Or, you could write the raw HTML explicitly:
<label for="SomekingStatus" class="control-label">Someking Status</label>
A Web Reference allows you to communicate with any service based on any technology that implements the WS-I Basic Profile 1.1, and exposes the relevant metadata as WSDL. Internally, it uses the ASMX communication stack on the client's side.
A Service Reference allows you to communicate with any service based on any technology that implements any of the many protocols supported by WCF (including but not limited to WS-I Basic Profile). Internally, it uses the WCF communication stack on the client side.
Note that both these definitions are quite wide, and both include services not written in .NET.
It is perfectly possible (though not recommended) to add a Web Reference that points to a WCF service, as long as the WCF endpoint uses basicHttpBinding
or some compatible custom variant.
It is also possible to add a Service Reference that points to an ASMX service. When writing new code, you should always use a Service Reference simply because it is more flexible and future-proof.
take a look at the plyr
package. Specifically, ddply
ddply(df, .(group), summarise, mean=mean(dt), sum=sum(dt))
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
http://desktop-qr277sp/Reports01/report/Reports/reportName?Log%In%Name=serverUsername¶mName=value
Pass parameter to the report with server authentication
If the return value is string and you need to search by Id you can use:
string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();
or using generic variable:
var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
Unutbu answer is correct. But because our mean can be more or less than zero I would still like to change this :
x = np.linspace(-3 * sigma, 3 * sigma, 100)
to this :
x = np.linspace(-3 * sigma + mean, 3 * sigma + mean, 100)
Git clone is the command you're looking for:
git clone [email protected]:username/repo.git
Update: And this is the official guide: https://help.github.com/articles/fork-a-repo
Take a look at: https://help.github.com/
It has really useful content
npm install bootstrap --save
and add relevent files into angular.json
file under the style
property for css files and under scripts
for JS files.
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
....
]
you can try this
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
As it turns out, my suspicions were right. The audience aud
claim in a JWT is meant to refer to the Resource Servers that should accept the token.
As this post simply puts it:
The audience of a token is the intended recipient of the token.
The audience value is a string -- typically, the base address of the resource being accessed, such as
https://contoso.com
.
The client_id
in OAuth refers to the client application that will be requesting resources from the Resource Server.
The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id
and client_secret
along with any user credentials that may be required. The Authorization Server validates the client using the client_id
and client_secret
and returns a JWT.
The JWT will contain an aud
claim that specifies which Resource Servers the JWT is valid for. If the aud
contains www.myfunwebapp.com
, but the client app tries to use the JWT on www.supersecretwebapp.com
, then access will be denied because that Resource Server will see that the JWT was not meant for it.
Another possile solution providing the possibility of more complicated keys can be found here: http://insidecoffe.blogspot.de/2013/04/indexable-hashmap-implementation.html
I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)
import random
first = random.randint(1,9)
first = str(first)
n = 5
nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs)) :
first += str(nrs[i])
print str(first)
Something went wrong with your GCC installation. Try reinstalling the it like this:
sudo apt-get install --reinstall g++-5
In Ubuntu the g++
is a dependency package that installs the default version of g++
for your OS version. So simply removing and installing the package again won't work, cause it will install the default version. That's why you need to reinstall.
Note: You can replace the g++-5
with your desired g++
version. To find your current g++
version run this:
g++ --version
In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:
tasks:
- shell: echo $(cat /etc/issue | awk {'print $7'})
register: echo_content
- shell: echo "It works"
when: echo_content.stdout == "12"
register: out
- debug: var=out.stdout_lines
When something happens in my view I fire off an event that my activity is listening for:
// DECLARED IN (CUSTOM) VIEW
private OnScoreSavedListener onScoreSavedListener;
public interface OnScoreSavedListener {
public void onScoreSaved();
}
// ALLOWS YOU TO SET LISTENER && INVOKE THE OVERIDING METHOD
// FROM WITHIN ACTIVITY
public void setOnScoreSavedListener(OnScoreSavedListener listener) {
onScoreSavedListener = listener;
}
// DECLARED IN ACTIVITY
MyCustomView slider = (MyCustomView) view.findViewById(R.id.slider)
slider.setOnScoreSavedListener(new OnScoreSavedListener() {
@Override
public void onScoreSaved() {
Log.v("","EVENT FIRED");
}
});
If you want to know more about communication (callbacks) between fragments see here: http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
We can see the maximum number of threads defined in the following file in linux
cat /proc/sys/kernel/threads-max
(OR)
sysctl -a | grep threads-max
CharMatcher.retainFrom
can be used, if you're using the Google Guava library:
String s = "A função";
String stripped = CharMatcher.ascii().retainFrom(s);
System.out.println(stripped); // Prints "A funo"
Here's a nice fun LINQ example.
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
I was thinking about the same today and then go with the solution.
var generateOTP = function(otpLength=6) {
let baseNumber = Math.pow(10, otpLength -1 );
let number = Math.floor(Math.random()*baseNumber);
/*
Check if number have 0 as first digit
*/
if (number < baseNumber) {
number += baseNumber;
}
return number;
};
Let me know if it has any bug. Thanks.
I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding
style="position: relative; bottom: 0px"
to your Widget2 tag. Also try:
style="position: absolute; bottom: 0px"
if you want to snap your widget to the bottom of the screen.
I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.
You are posting the data, so it should be $_POST. But 'name' is not the best name to use.
name = "name"
will only cause confusion IMO.
It depends on a server configuration. If you're working with PHP under Linux or similar, you can control it using .htaccess configuration file, like so:
#set max post size
php_value post_max_size 20M
And, yes, I can personally attest to the fact that this works :)
If you're using IIS, I don't have any idea how you'd set this particular value.
Something different than all the previous answers:
perl -lne '$count++ for m/<pattern>/g;END{print $count}' *
Your can do it like this in short hands.
int[,] values=new int[2,3]{{2,4,5},{4,5,2}};
for (int i = 0; i < values.GetLength(0); i++)
{
for (int k = 0; k < values.GetLength(1); k++) {
Console.Write(values[i,k]);
}
Console.WriteLine();
}
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
To close this question, what seemed to have worked is indeed running
docker-compose stop
docker-compose rm -f
docker-compose -f docker-compose.yml up -d
I.e. remove the containers before running up
again.
What one needs to keep in mind when doing it like this is that data volume containers are removed as well if you just run rm -f
. In order to prevent that I specify explicitly each container to remove:
docker-compose rm -f application nginx php
As I said in my question, I don't know if this is the correct process. But this seems to work for our use case, so until we find a better solution we'll roll with this one.
Opening Visual Studio as administrator will fix the problem.
For SQL Server 2005 onwards, you can do this with CROSS APPLY and a table-valued function.
Just for clarity, I'm referring to those cases where the stored procedure can be converted into a table valued function.
Following worked for me and it seems very simple as well:
Let's assume that we want to import a script ./data/get_my_file.py and want to access get_set1() function in it.
import sys
sys.path.insert(0, './data/')
import get_my_file as db
print (db.get_set1())
Try
string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease ;
and then
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";