Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
function findKey(object, value) {
for (let key in object)
if (object[key] === value) return key;
return "key is not found";
}
const object = { id_1: "apple", id_2: "pear", id_3: "peach" };
console.log(findKey(object, "pear"));
//expected output: id_2
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
Just use the sys.getsizeof function defined in the sys
module.
sys.getsizeof(object[, default])
:Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
The
default
argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause aTypeError
.
getsizeof
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.See recursive sizeof recipe for an example of using
getsizeof()
recursively to find the size of containers and all their contents.
Usage example, in python 3.0:
>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48
If you are in python < 2.6 and don't have sys.getsizeof
you can use this extensive module instead. Never used it though.
It can done simply by using the Builder's setView(). You can create any view of your choice and feed into the builder. This works good. I use a custom TextView that is rendered by the dialog builder. I dont set the message and this space is utilized to render my custome textview.
There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.
Css:
#SelectorToPrint{
display: none;
}
Script:
$("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})
This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.
If you already have a file package.json
in the project and it contains grunt
in dependency,
"devDependencies": {
"grunt": "~0.4.0",
Then you can run npm install
to resolve the issue
r = ("1"+"2"+"3") // step1 | build string ==> "123"
r = +r // step2 | to number ==> 123
r = r+100 // step3 | +100 ==> 223
r = ""+r // step4 | to string ==> "223"
//in one line
r = ""+(+("1"+"2"+"3")+100);
This should work as tested.
<?php
$filter = new Mage_Widget_Model_Template_Filter();
$_widget = $filter->filter('{{widget type="cms/widget_page_link" template="cms/widget/link/link_block.phtml" page_id="2"}}');
echo $_widget;
?>
Here is what I have arrived at after a read of all the answers presented here as well what some Airgram has done in their SDKs - A utility that I have open sourced on Github:
https://github.com/mankum93/UriUtilsAndroid/tree/master/app/src/main/java/com/androiduriutils
As simple as calling, UriUtils.getDisplayNameSize()
. It provides both the name and size of the content.
Note: Only works with a content:// Uri
Here is a glimpse on the code:
/**
* References:
* - https://www.programcreek.com/java-api-examples/?code=MLNO/airgram/airgram-master/TMessagesProj/src/main/java/ir/hamzad/telegram/MediaController.java
* - https://stackoverflow.com/questions/5568874/how-to-extract-the-file-name-from-uri-returned-from-intent-action-get-content
*
* @author [email protected]/2HjxA0C
* Created on: 03-07-2020
*/
public final class UriUtils {
public static final int CONTENT_SIZE_INVALID = -1;
/**
* @param context context
* @param contentUri content Uri, i.e, of the scheme <code>content://</code>
* @return The Display name and size for content. In case of non-determination, display name
* would be null and content size would be {@link #CONTENT_SIZE_INVALID}
*/
@NonNull
public static DisplayNameAndSize getDisplayNameSize(@NonNull Context context, @NonNull Uri contentUri){
final String scheme = contentUri.getScheme();
if(scheme == null || !scheme.equals(ContentResolver.SCHEME_CONTENT)){
throw new RuntimeException("Only scheme content:// is accepted");
}
final DisplayNameAndSize displayNameAndSize = new DisplayNameAndSize();
displayNameAndSize.size = CONTENT_SIZE_INVALID;
String[] projection = new String[]{MediaStore.Images.Media.DATA, OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
// Try extracting content size
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (sizeIndex != -1) {
displayNameAndSize.size = cursor.getLong(sizeIndex);
}
// Try extracting display name
String name = null;
// Strategy: The column name is NOT guaranteed to be indexed by DISPLAY_NAME
// so, we try two methods
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
if (nameIndex == -1 || name == null) {
nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
}
displayNameAndSize.displayName = name;
}
}
finally {
if(cursor != null){
cursor.close();
}
}
// We tried querying the ContentResolver...didn't work out
// Try extracting the last path segment
if(displayNameAndSize.displayName == null){
displayNameAndSize.displayName = contentUri.getLastPathSegment();
}
return displayNameAndSize;
}
}
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto
keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Prefer {} initialization over alternatives unless you have a strong reason not to.
If String.Compare(string1,string2,True) Then
'perform operation
EndIf
This error occurred for me because mod_rewrite was not enabled. Everything worked fine after enabling the rewrite module: https://www.debuntu.org/how-to-enable-apache-modules-under-debian-based-system-page-2/
You can do this simply with SSMS. Just go to your table name and expand the Triggers node to view a list of triggers associated with that table. Right click to modify your trigger.
Here are the few techniques I've heard of:
Use clone()
if the class implements Cloneable
. This API is a bit flawed in java and I never quite understood why clone
is not defined in the interface, but in Object
. Still, it might work.
Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new User( user.ID, user.Age, ... )
. You might even want a constructor that takes a User: new User( anotherUser ).
Implement something to copy from/to a user. Instead of using a constructor, the class may have a method copy( User )
. You can then first snapshot the object backupUser.copy( user )
and then restore it user.copy( backupUser )
. You might have a variant with methods named backup
/restore
/snapshot
.
Use the state pattern.
Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.
That all depends on the use case. Go for the simplest.
EDIT
I also recommend to have a look at these questions:
In Bjarne's words (The C++ Programming Language, 4th Edition, page 366):
Where termination is an acceptable response, an uncaught exception will achieve that because it turns into a call of terminate() (§13.5.2.5). Also, a
noexcept
specifier (§13.5.1.1) can make that desire explicit.Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it can without getting too contorted and leaves the rest to higher levels. Exceptions support that view. Furthermore,
terminate()
supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught. Similarly,noexcept
provides a simple escape for errors where trying to recover seems infeasible.double compute(double x) noexcept; { string s = "Courtney and Anya"; vector<double> tmp(10); // ... }
The vector constructor may fail to acquire memory for its ten doubles and throw a
std::bad_alloc
. In that case, the program terminates. It terminates unconditionally by invokingstd::terminate()
(§30.4.1.3). It does not invoke destructors from calling functions. It is implementation-defined whether destructors from scopes between thethrow
and thenoexcept
(e.g., for s in compute()) are invoked. The program is just about to terminate, so we should not depend on any object anyway. By adding anoexcept
specifier, we indicate that our code was not written to cope with a throw.
As stated by the other answers, "%03d" % number
works pretty well, but it goes against the rubocop ruby style guide:
Favor the use of sprintf and its alias format over the fairly cryptic String#% method
We can obtain the same result in a more readable way using the following:
format('%03d', number)
This is the simple example to understand about python unpacking,
>>> def f(*args, **kwargs):
... print 'args', args, 'kwargs', kwargs
eg1:
>>>f(1, 2)
>>> args (1,2) kwargs {} #args return parameter without reference as a tuple
>>>f(a = 1, b = 2)
>>> args () kwargs {'a': 1, 'b': 2} #args is empty tuple and kwargs return parameter with reference as a dictionary
You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts
localhost name resolution is handled within DNS itself.
127.0.0.1 mywebsite.com
after you finish your tests you just comment the line you add to disable it
127.0.0.1 mywebsite.com
Most simple, without caring about delegates
if(textBox1.InvokeRequired == true)
textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});
else
textBox1.Text = "Invoke was NOT needed";
We will find the value of X and Y from this image. We know, sin?=vertical/hypotenuse and cos?=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cos? and Y=hypotenuse * sin?.
Now look at this code
void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
glBegin(GL_TRIANGLES);
x=5*cos(i);
y=5*sin(i);
glVertex2d(x, y);
i=i+.5;
x=5*cos(i);
y=5*sin(i);
glVertex2d(x, y);
glVertex2d(0, 0);
glEnd();
i=i+.5;
}
glEnd();
glutSwapBuffers();
}
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
In OSX, you can set the classpath from scratch like this:
export CLASSPATH=/path/to/some.jar:/path/to/some/other.jar
Or you can add to the existing classpath like this:
export CLASSPATH=$CLASSPATH:/path/to/some.jar:/path/to/some/other.jar
This is answering your exact question, I'm not saying it's the right or wrong thing to do; I'll leave that for others to comment upon.
You don't actually need select_db
. You can send a query to two databases at the same time. First, give a grant to DB1
to select from DB2
by GRANT select ON DB2.* TO DB1@localhost;
. Then, FLUSH PRIVILEGES;
. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2
etc. (Don't forget that you need 'root' access to use grant command)
When setting a variable make sure you have no spaces before and/or after the =
sign. I literally spent an hour trying to figure this out, trying all kinds of solutions! This is not cool.
Correct:
WTFF=`echo "stuff"`
echo "Example: $WTFF"
Will Fail with error "stuff: not found" or similar
WTFF= `echo "stuff"`
echo "Example: $WTFF"
You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
},
import AVFoundation
import AudioToolbox
public final class MP3Player : NSObject {
// Singleton class
static let shared:MP3Player = MP3Player()
private var player: AVAudioPlayer? = nil
// Play only mp3 which are stored in the local
public func playLocalFile(name:String) {
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
}catch let error{
print(error.localizedDescription)
}
}
}
To call this function
MP3Player.shared.playLocalFile(name: "JungleBook")
This bash script is for N parallel threads. Each argument is a command.
trap
will kill all subprocesses when SIGINT is catched.
wait $PID_LIST
is waiting each process to complete.
When all processes have completed, the program exits.
#!/bin/bash
for cmd in "$@"; do {
echo "Process \"$cmd\" started";
$cmd & pid=$!
PID_LIST+=" $pid";
} done
trap "kill $PID_LIST" SIGINT
echo "Parallel processes have started";
wait $PID_LIST
echo
echo "All processes have completed";
Save this script as parallel_commands
and make it executable.
This is how to use this script:
parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"
Example:
parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"
Start 4 parallel sleep and waits until "sleep 4" finishes.
Though this question is very old but as a new in Software Development I can't stop my self to share what I have learnt :D
Creation of Stored Procedure:
CREAET PROC usp_ValidateUSer
(
@UserName nVARCHAR(50),
@Password nVARCHAR(50)
)
AS
BEGIN
IF EXISTS(SELECT '#' FROM Users WHERE Username=@UserName AND Password=@Password)
BEGIN
SELECT u.UserId, u.Username, r.UserRole
FROM Users u
INNER JOIN UserRoles r
ON u.UserRoleId=r.UserRoleId
END
END
Execution of Stored Procedure:
(If you want to test the execution of Stored Procedure in SQL)
EXEC usp_ValidateUSer @UserName='admin', @Password='admin'
Th Output:
Check the contents of SpringExample/target/classes. Is spring-config.xml there? If not, try manually removing the SpringExample/target/ directory, and force a rebuild with Project=>Clean... in Eclipse.
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
Cheap and nasty solution.. Use the ugly #! style.
To set it:
window.location.hash = '#!' + id;
To read it:
id = window.location.hash.replace(/^#!/, '');
Since it doesn't match and anchor or id in the page, it won't jump.
I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:
An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.
Despite the imprecise nature of the question, here's my interpretive answer.
var html = [
'<div> A line</div>',
'<div> Add more lines</div>',
'<div> To the array as you need.</div>'
].join('');
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = html;
document.getElementById('posts').appendChild(div);
select * FROM doc_tab
PIVOT
(
Min(document_id)
FOR document_type IN ('Voters ID','Pan card','Drivers licence')
)
outputs as this
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
Consider the below definition in web.xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>myprop</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.
So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.
Consider the following definition in web.xml
<web-app>
<context-param>
<param-name>myprop</param-name>
<param-value>value</param-value>
</context-param>
</web-app>
This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);
From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);
If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).
If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").
Once the edition is done, hit ESC again, then type :wq
to save your work or :q!
to quit without saving.
For quick reference, here you have a text-based cheat sheet.
It depends on the context.
I use if A:
when I'm expecting A
to be some sort of collection, and I only want to execute the block if the collection isn't empty. This allows the caller to pass any well-behaved collection, empty or not, and have it do what I expect. It also allows None
and False
to suppress execution of the block, which is occasionally convenient to calling code.
OTOH, if I expect A
to be some completely arbitrary object but it could have been defaulted to None
, then I always use if A is not None
, as calling code could have deliberately passed a reference to an empty collection, empty string, or a 0-valued numeric type, or boolean False
, or some class instance that happens to be false in boolean context.
And on the other other hand, if I expect A
to be some more-specific thing (e.g. instance of a class I'm going to call methods of), but it could have been defaulted to None
, and I consider default boolean conversion to be a property of the class I don't mind enforcing on all subclasses, then I'll just use if A:
to save my fingers the terrible burden of typing an extra 12 characters.
This will sort your results by the first column returned. In the example it will sort by payment_date.
I don't know if there is such a function, but with $this->uri->uri_to_assoc() you get an associative array from the $_GET parameters. With this, and the controller you are in, you know how the URL looks like. In you above URL this would mean you would be in the controller dropbox and the array would be something like this:
array("derrek" => "shopredux", "ahahaha" => "hihihi");
With this you should be able to make such a function on your own.
New, expanded answer to an old, commonly asked question...
Summary: Whitespace characters are not permitted in XML element or attribute names.
Here are the main Unicode code points related to whitespace:
#x0009
CHARACTER TABULATION#x0020
SPACE#x000A
LINE FEED (LF)#x000D
CARRIAGE RETURN (CR)#x00A0
NO-BREAK SPACE[#x2002-#x200A]
EN SPACE through HAIR SPACE#x205F
MEDIUM MATHEMATICAL SPACE#x3000
IDEOGRAPHIC SPACENone of these code points are permitted by the W3C XML BNF for XML names:
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] Name ::= NameStartChar (NameChar)*
Summary: Whitespace characters are, of course, permitted in XML content.
All of the above whitespace codepoints are permitted in XML content by the W3C XML BNF for Char
:
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
Unicode code points can be inserted as character references. Both decimal &#
decimal;
and hexadecimal &#x
hex;
forms are supported.
	
or 	
CHARACTER TABULATION

or
LINE FEED (LF)
or
CARRIAGE RETURN (CR) 
or  
SPACE 
or  
NO-BREAK SPACE Please update new user repository URL
git remote set-url origin https://[email protected]/repository.git
I tried using below commands, it's not working:
git config user.email "[email protected]"
git config user.name "user"
OR
git config --global user.email "[email protected]"
git config --global user.name "user"
That's your jQuery API problem, not your script. There is not much to worry about.
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
There is a simple function subtract
which moment library gives us to subtract time from some time.
Using it is also very simple.
moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously
//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
Hope this helps!
The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.
https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.
Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.
The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.
One side effect of this limitation is that some file extensions, such as .gif
match their Mime Type, image/gif
, while others are compromised. This includes image/jpeg
whose extension is shortened to .jpg
. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.
Given that that:
The short answer is:
image/jpg
, so the answer is
that it is not the same as image/jpeg
While we’re at it …
Legacy versions of Internet Explorer took the liberty of uploading jpeg
files with the Mime Type of image/pjpeg
, which, of course, just means more work for everybody else. They also uploaded png
files as image/x-png
.
First look for the main method is there or not.If it is there, do restart your eclipse and right click on the page which having main method, Go to run as Java application.
The selected answer is out of date and no others worked for me (Django 1.6 and [apparantly] no registered namespace.)
For Django 1.5 and later (from the docs)
Warning Don’t forget to put quotes around the function path or pattern name!
With a named URL you could do:
(r'^login/', login_view, name='login'),
...
<a href="{% url 'login' %}">logout</a>
Just as easy if the view takes another parameter
def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>
Two ways:
Have a bean implement ApplicationListener<ContextClosedEvent>
. onApplicationEvent()
will get called before the context and all the beans are destroyed.
Have a bean implement Lifecycle or SmartLifecycle. stop()
will get called before the context and all the beans are destroyed.
Either way you can shut down the task stuff before the bean destroying mechanism takes place.
Eg:
@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
@Autowired ThreadPoolTaskExecutor executor;
@Autowired ThreadPoolTaskScheduler scheduler;
@Override
public void onApplicationEvent(ContextClosedEvent event) {
scheduler.shutdown();
executor.shutdown();
}
}
(Edit: Fixed method signature)
I found that when testing native browser functions in IE8, using toString
, instanceof
, and typeof
did not work. Here is a method that works fine in IE8 (as far as I know):
function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
Alternatively, you can check for native functions using:
"getElementById" in document
Though, I have read somewhere that this will not always work in IE7 and below.
this.form.submit();
This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.
The React Router v5.1 (React >= 16.8) way of doing this:
<Route path="/comments">
<Comments myprop="value" />
</Route>
Now if you want to access Route Props inside your component then you can refer this solution. In case of functional component, there is another hook useParams()
that is not mentioned in that post.
More reference: React Router v5.1
The extended configuration section in a previous response with
...
...
<rollingStyle value="Composite" />
...
...
listed works but I did not have to use
<staticLogFileName value="false" />
. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.
in resources/views/layouts/app.blade.php file
<script type="text/javascript">
var baseUrl = '<?=url('');?>';
</script>
Try C# 7.0
var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
? dt : DateTime.Parse("1800-01-01");
You should let the user do that if they want (and you can't stop them anyway).
Your problem is that you need to know that they have and then assume that they mean OK, not cancel. Replace confirm(x)
with myConfirm(x)
:
function myConfirm(message) {
var start = Number(new Date());
var result = confirm(message);
var end = Number(new Date());
return (end<(start+10)||result==true);
}
You should parse Vimeo's API's response. There is no way to it with URL calls (like dailymotion or youtube).
Here is my PHP solution:
/**
* Gets a vimeo thumbnail url
* @param mixed $id A vimeo id (ie. 1185346)
* @return thumbnail's url
*/
function getVimeoThumb($id) {
$data = file_get_contents("http://vimeo.com/api/v2/video/$id.json");
$data = json_decode($data);
return $data[0]->thumbnail_medium;
}
Suppose STUDENTID contains some characters or numbers that you already know i.e. 'searchstring' then below query will work for you.
You could try this:
select * from STUDENTS where CHARINDEX('searchstring',STUDENTID)>0
I think this one is the fastest and easiest one.
Another possible solution, in case you're looking for all the words in a given string, which contain a number
\w*\d{1,}\w*
\w*
- Matches 0 or more instances of [A-Za-z0-9_]\d{1,}
- Matches 1 or more instances of a number\w*
- Matches 0 or more instances of [A-Za-z0-9_]The whole point in \w*
is to allow not having a character in the beginning or at the end of a word. This enables capturing the first and last words in the text.
If the goal here is to only get the numbers without the words, you can omit both \w*
.
Hello world 1 4m very happy to be here, my name is W1lly W0nk4
1 4m W1lly W0nk4
Check this example in regexr - https://regexr.com/5ff7q
Here is an easy way to get only unique raw values from array. If you convert the array to Set and after this, do the conversion from Set to array. This conversion works only for raw values, for objects in the array it is not valid. Try it by yourself.
let myObj1 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
let myObj2 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
var myArray = [55, 44, 65, myObj1, 44, myObj2, 15, 25, 65, 30];
console.log(myArray);
var mySet = new Set(myArray);
console.log(mySet);
console.log(mySet.size === myArray.length);// !! The size differs because Set has only unique items
let uniqueArray = [...mySet];
console.log(uniqueArray);
// Here you will see your new array have only unique elements with raw
// values. The objects are not filtered as unique values by Set.
// Try it by yourself.
I had the same problem. I followed these steps (in this exact order, this is VERY important):
This happens mainly because Angular won't build those modules in the correct order, i.e before the HTML.
e.g My code:
<mat-toolbar> <!-- 2 -->
<button mat-icon-button class="example-icon" aria-label="Example icon-button with menu icon">
<mat-icon>favorite</mat-icon> <!-- 1 -->
</button>
<span>My App</span>
<span class="example-spacer"></span>
<button mat-icon-button class="example-icon favorite-icon" aria-label="Example icon-button with heart icon">
</button>
<button mat-icon-button class="example-icon" aria-label="Example icon-button with share icon">
</button>
</mat-toolbar>
_x000D_
Using the simple app.run()
from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason.
Spawning threads and managing them yourself is probably not going to get you very far either, because of the Python GIL.
That said, you do still have some good options. Gunicorn is a solid, easy-to-use WSGI server that will let you spawn multiple workers (separate processes, so no GIL worries), and even comes with asynchronous workers that will speed up your app (and make it more secure) with little to no work on your part (especially with Flask).
Still, even Gunicorn should probably not be directly publicly exposed. In production, it should be used behind a more robust HTTP server; nginx tends to go well with Gunicorn and Flask.
It works perfectly fine .
public static function folderSize($dir)
{
$size = 0;
foreach (glob(rtrim($dir, '/') . '/*', GLOB_NOSORT) as $each) {
$func_name = __FUNCTION__;
$size += is_file($each) ? filesize($each) : static::$func_name($each);
}
return $size;
}
IDs are unique. Classes aren't. Elements can also have multiple classes. Also classes can be dynamically added and removed to an element.
Anywhere you can use an ID you could use a class instead. The reverse is not true.
The convention seems to be to use IDs for page elements that are on every page (like "navbar" or "menu") and classes for everything else but this is only convention and you'll find wide variance in usage.
One other difference is that for form input elements, the <label>
element references a field by ID so you need to use IDs if you're going to use <label>
. is an accessibility thing and you really should use it.
In years gone by IDs were also preferred because they're easily accessible in Javascript (getElementById). With the advent of jQuery and other Javascript frameworks this is pretty much a non-issue now.
It might be better to use communicate
:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
"Better", because of this warning:
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
I was facing exact same error
Computed property "callRingtatus" was assigned to but it has no setter
here is a sample code according to my scenario
computed: {
callRingtatus(){
return this.$store.getters['chat/callState']===2
}
}
I change the above code into the following way
computed: {
callRingtatus(){
return this.$store.state.chat.callState===2
}
}
fetch values from vuex store state instead of getters inside the computed hook
A picture is worth a thousand words:
==
equality chart:===
Equality chart:Source code to create these images:
https://github.com/sentientmachine/php_equality_charts
Those who wish to keep their sanity, read no further because none of this will make any sense, except to say that this is how the insanity-fractal, of PHP was designed.
NAN != NAN
but NAN == true
.
==
will convert left and right operands to numbers if left is a number. So 123 == "123foo"
, but "123" != "123foo"
A hex string in quotes is occasionally a float, and will be surprise cast to float against your will, causing a runtime error.
==
is not transitive because "0"== 0
, and 0 == ""
but "0" != ""
PHP Variables that have not been declared yet are false, even though PHP has a way to represent undefined variables, that feature is disabled with ==
.
"6" == " 6"
, "4.2" == "4.20"
, and "133" == "0133"
but 133 != 0133
. But "0x10" == "16"
and "1e3" == "1000"
exposing that surprise string conversion to octal will occur both without your instruction or consent, causing a runtime error.
False == 0
, ""
, []
and "0"
.
If you add 1 to number and they are already holding their maximum value, they do not wrap around, instead they are cast to infinity
.
A fresh class is == to 1.
False is the most dangerous value because False is == to most of the other variables, mostly defeating it's purpose.
If you are using PHP, Thou shalt not use the double equals operator because if you use triple equals, the only edge cases to worry about are NAN and numbers so close to their datatype's maximum value, that they are cast to infinity. With double equals, anything can be surprise ==
to anything or, or can be surprise casted against your will and !=
to something of which it should obviously be equal.
Anywhere you use ==
in PHP is a bad code smell because of the 85 bugs in it exposed by implicit casting rules that seem designed by millions of programmers programming by brownian motion.
There's no problem. I would even remove the CreateNewOrUpdateExisting
from the source and use map[key] = value
directly in your code, because this this is much more readable, because developers would usually know what map[key] = value
means.
Short answer: No. myObj isn't the name of the object, it's the name of a variable holding a reference to the object - you could have any number of other variables holding a reference to the same object.
Now, if it's your program, then you make the rules: if you want to say that any given object will only be referenced by one variable, ever, and diligently enforce that in your code, then just set a property on the object with the name of the variable.
That said, i doubt what you're asking for is actually what you really want. Maybe describe your problem in a bit more detail...?
Pedantry: JavaScript doesn't have classes. someObject
is a constructor function. Given a reference to an object, you can obtain a reference to the function that created it using the constructor property.
The answer you're looking for can be found here: JavaScript Callback Scope (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS). You just need to wrap the call to the object member in a closure that preserves access to the context object.
Just closing the metro bundler and rebuilding the app done my job.
You can wrap the text with a non-existing processing-instruction, e.g.:
<detail>
<?ignore
<band height="20">
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
</band>
?>
</detail>
Nested processing instructions are not allowed and '?>' ends the processing instruction (see http://www.w3.org/TR/REC-xml/#sec-pi)
This one should work
<button [ngClass]="{[namespace + '-mybutton']: type === 'mybutton'}"></button>
but Angular throws on this syntax. I'd consider this a bug. See also https://stackoverflow.com/a/36024066/217408
The others are invalid. You can't use []
together with {{}}
. Either one or the other. {{}}
binds the result stringified which doesn't lead to the desired result in this case because an object needs to be passed to ngClass
.
As workaround the syntax shown by @A_Sing or
<button [ngClass]="type === 'mybutton' ? namespace + '-mybutton' : ''"></button>
can be used.
In C++11 and above, you can also initialize std::vector
with an initializer list. For example:
using namespace std; // for example only
for (auto s : vector<string>{"one","two","three"} )
cout << s << endl;
So, your example would become:
void foo(vector<string> strArray){
// some code
}
vector<string> s {"hi", "there"}; // Works
foo(s); // Works
foo(vector<string> {"hi", "there"}); // also works
This just print before exit.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void sigint_handler(int);
int main(void)
{
signal(SIGINT, sigint_handler);
while (1){
pause();
}
return 0;
}
void sigint_handler(int sig)
{
/*do something*/
printf("killing process %d\n",getpid());
exit(0);
}
You've basically answered anything and everything already, so I'm no sure what the point is here?
FWIW I would use an httphandler - there seems no point in invoking a page lifecycle and having to deal with clipping off the bits of viewstate and session and what have you which don't make sense for an XML doc. It's like buying a car and stripping it for parts to make your motorbike.
And content-type is all important, it's how the requester knows what to do with the response.
I would do the following,
JSONObject obj1 = /*json*/;
JSONObject obj2 = /*json*/;
ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(obj1.toString());
JsonNode tree2 = mapper.readTree(obj2.toString());
return tree1.equals(tree2);
default port of mysql is 3306
default pot of sql server is 1433
with the webbrowser module
import webbrowser
webbrowser.open('http://example.com') # Go to example.com
I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.
Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know
If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.
In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:
How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections
Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.
variable=10
f=open("fileName.txt","w+") # file name and mode
for x in range(0,10):
f.writelines('your text')
f.writelines('if you want to add variable data'+str(variable))
# to add data you only add String data so you want to type cast variable
f.writelines("\n")
The short answer is "you can't". What you'll need to do is either use a subquery or you could convert your existing stored procedure in to a table function. Creating it as function would depend on how "reusable" you would need it to be.
Not exactly like that. But you can use the --no-commit option, so it does not automatically commit the result after the merge. In this way you can inspect, and if desired, to undo the merge without messing with the commit tree.
This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:
- APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
different; type shape differs in key cases). These differences
currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
include more of the .NET Framework BCL APIs over time.- Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
programming model. For example, Code Access Security (CAS) is not
supported, while reflection is supported.
If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.
My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.
Linq and Entity framework are included in .NET Core, so you are safe to take a shot.
Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.
Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.
You should specify which OS and development environment you're using for more targeted assistance.
For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack
option of ld
to do that.
I found that when I used the this callback function to ignore SSL certificates [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
I always got the error message Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
which sounds like the results you are having.
I found this forum post which lead me to the function below. I run this once inside the scope of my other code and it works for me.
function Ignore-SSLCertificates
{
$Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler = $Provider.CreateCompiler()
$Params = New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable = $false
$Params.GenerateInMemory = $true
$Params.IncludeDebugInformation = $false
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy
{
public class TrustAll : System.Net.ICertificatePolicy
{
public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
{
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We create an instance of TrustAll and attach it to the ServicePointManager
$TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}
You can try disabling the "VirtualBox NDIS6 Bridged Networking Driver" on all but your actual physical network adapter(s) before attempting to create the VirtualBox host-only adapter again.
See this answer.
Don't forget the awesome
git fetch -p
which fetches and prunes all origins.
First of all, you're not leveraging the advantage of using a PreparedStatement
. I would first suggest that you modify your PreparedStatement
as follows:
PreparedStatement statement = con.prepareStatement("select * from orders where status=? AND date=?")
You can then use statement.setXX(param_index, param_value)
to set the respective values. For conversion to timestamp
, have a look at the following javadocs:
PreparedStatement.setTimeStamp()
Timestamp
Hope this helps!
A simple solution:
import multiprocessing
output=[]
data = range(0,10)
def f(x):
return x**2
def handler():
p = multiprocessing.Pool(64)
r=p.map(f, data)
return r
if __name__ == '__main__':
output.append(handler())
print(output[0])
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can't do the second, because even if you use the remove()
method on Iterator, you'll get an Exception thrown.
Personally, I would prefer the first for all Collection
instances, despite the additional overheard of creating the new Collection
, I find it less prone to error during edit by other developers. On some Collection implementations, the Iterator remove()
is supported, on other it isn't. You can read more in the docs for Iterator.
The third alternative, is to create a new Collection
, iterate over the original, and add all the members of the first Collection
to the second Collection
that are not up for deletion. Depending on the size of the Collection
and the number of deletes, this could significantly save on memory, when compared to the first approach.
Same principle as Loki's answer but shorter. Just keep in mind that shorter doesn't automatically mean better.
dinner = Optional.ofNullable(cage.getChicken())
.orElse(getFreerangeChicken());
Note: This usage of Optional
is explicitly discouraged by the architects of the JDK and the designers of the Optional feature. You are allocating a fresh object and immediately throwing it away every time. But on the other hand it can be quite readable.
If the DataGridView is bound to any datasource,
DataGridView1.DataSource = Nothing
DataGridView1.DataBind()
Updated Answer There is no convenient way to do this using Dynamo DB Queries with predictable throughput. One (sub optimal) option is to use a GSI with an artificial HashKey & CreatedAt. Then query by HashKey alone and mention ScanIndexForward to order the results. If you can come up with a natural HashKey (say the category of the item etc) then this method is a winner. On the other hand, if you keep the same HashKey for all items, then it will affect the throughput mostly when when your data set grows beyond 10GB (one partition)
Original Answer: You can do this now in DynamoDB by using GSI. Make the "CreatedAt" field as a GSI and issue queries like (GT some_date). Store the date as a number (msecs since epoch) for this kind of queries.
Details are available here: Global Secondary Indexes - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Using
This is a very powerful feature. Be aware that the query is limited to (EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN) Condition - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html
import android.support.v7.widget.RecyclerView;
In Android Studio, importing is not as intuitive as one would hope. Try importing this bit and see how it helps!
you may try the TO_CHAR function to convert the result
e.g.
SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL
SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL
Hope it helps
In case if Parent class is singleton use following way:
Parent.Child childObject = (Parent.getInstance()).new Child();
where getInstance()
will return parent class singleton object.
Make sure the hamcrest jar is higher on the import order than your JUnit jar.
JUnit comes with its own org.hamcrest.Matcher
class that is probably being used instead.
You can also download and use the junit-dep-4.10.jar instead which is JUnit without the hamcrest classes.
mockito also has the hamcrest classes in it as well, so you may need to move\reorder it as well
The best practice is using File.separator in the paths.
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
How about the Intersection Observer API? This avoids the potential sluggishness from using the scroll event.
HTML
<nav class="navbar-fixed-top">Navbar</nav>
<main>
<div class="content">Some content</div>
</main>
CSS
.navbar-fixed-top--scrolled changes the nav bar background color. It's added to the nav bar when the content div is no longer 100% visible as we scroll down.
.navbar-fixed-top {
position: sticky;
top: 0;
height: 60px;
}
.navbar-fixed-top--scrolled {
/* change background-color to whatever you want */
background-color: grey;
}
JS
Create the observer to determine when the content div fully intersects with the browser viewport.
The callback function is called:
isIntersecting indicates whether the content div (the target element) is fully intersecting with the observer's root (the browser viewport by default).
// callback function to be run whenever threshold is crossed in one direction or the other
const callback = (entries, observer) => {
const entry = entries[0];
// toggle class depending on if content div intersects with viewport
const navBar = document.querySelector('.navbar-fixed-top');
navBar.classList.toggle('navbar-fixed-top--scrolled', !entry.isIntersecting);
}
// options controls circumstances under which the observer's callback is invoked
const options = {
// no root provided - by default browser viewport used to check target visibility
// only detect if target element is fully visible or not
threshold: [1]
};
const io = new IntersectionObserver(callback, options);
// observe content div
const target = document.querySelector('.content');
io.observe(target);
IntersectionObserver options
The nav bar currently changes background color when the content div starts moving off the screen.
If we want the background to change as soon as the user scrolls, we can use the rootMargin property (top, right, bottom, left) and set the top margin to negative the height of the nav bar (60px in our case).
const options = {
rootMargin: "-60px 0px 0px 0px",
threshold: [1]
};
You can see all the above in action on CodePen. Kevin Powell also has a good explanation on this (Github & YouTube).
The problem is that you do not insert your canvas element in the document body.
Just do the following:
document.body.appendChild(canvas);
Example:
var canvas = document.createElement('canvas');_x000D_
_x000D_
canvas.id = "CursorLayer";_x000D_
canvas.width = 1224;_x000D_
canvas.height = 768;_x000D_
canvas.style.zIndex = 8;_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.border = "1px solid";_x000D_
_x000D_
_x000D_
var body = document.getElementsByTagName("body")[0];_x000D_
body.appendChild(canvas);_x000D_
_x000D_
cursorLayer = document.getElementById("CursorLayer");_x000D_
_x000D_
console.log(cursorLayer);_x000D_
_x000D_
// below is optional_x000D_
_x000D_
var ctx = canvas.getContext("2d");_x000D_
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";_x000D_
ctx.fillRect(100, 100, 200, 200);_x000D_
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";_x000D_
ctx.fillRect(150, 150, 200, 200);_x000D_
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";_x000D_
ctx.fillRect(200, 50, 200, 200);
_x000D_
I've found the best way to edit tuples is to recreate the tuple using the previous version as the base.
Here's an example I used for making a lighter version of a colour (I had it open already at the time):
colour = tuple([c+50 for c in colour])
What it does, is it goes through the tuple 'colour' and reads each item, does something to it, and finally adds it to the new tuple.
So what you'd want would be something like:
values = ('275', '54000', '0.0', '5000.0', '0.0')
values = (tuple(for i in values: if i = 0: i = 200 else i = values[i])
That specific one doesn't work, but the concept is what you need.
tuple = (0, 1, 2)
tuple = iterate through tuple, alter each item as needed
that's the concept.
To remove cached .idea/ directory.
e.g. git rm -r --cached .idea
I am not experiented .But i think XmlReader is unnecessary.
It is very hard to use.
XElement is very easy to use.
If you need performance ( faster ) you must change file format and use StreamReader and StreamWriter classes.
In React Native , This worked for me
name = "hi \n\ruser"
name.replace( /[\r\n]+/gm, ""); // hi user
The neatest command is
grep -vc ^$ fileName
with -c
option, you don't even need wc -l
i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
Base 64 for html:
file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
Have you tried rebooting since you set the environment variable?
It appears that Windows keeps it's environment variable in some sort of cache, and rebooting is one method to refresh it. I'm not sure but there may be a different method, but if you are not going to be changing your variable value too often this may be good enough.
Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.
Delegate.Invoke() synchronously calls the delegate in the same thread.
Have you tried using:
(status,output) = commands.getstatusoutput("ps aux")
I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..
After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2
My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.
I found that python was leaking file descriptors by just keeping an eye on it:
watch "ls /proc/$PYTHONPID/fd | wc -l"
Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...
If anyone is facing this issue in Mysql there is no need to change varchar to nvarchar you can just change the collation of the column to utf8
As is described in this GitHub issue the build actually happens in /tmp/docker-12345
, so a relative path like ../relative-add/some-file
is relative to /tmp/docker-12345
. It would thus search for /tmp/relative-add/some-file
, which is also shown in the error message.*
It is not allowed to include files from outside the build directory, so this results in the "Forbidden path" message."
x_train = x_train.reshape(-1,28, 28, 1) #Reshape for CNN - should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
Output:
Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906
This is working for me in a console application -
string appData = System.Environment.GetEnvironmentVariable("APPDATA");
I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5)))
where XX
is the cell in reference.
I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST
and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.
You should connect to the place that your actual application needs. Otherwise you're testing whether you have a connection to somewhere irrelevant (Google in this case).
In particular, if you're trying to talk to a web service, and if you're in control of the web service, it would be a good idea to have some sort of cheap "get the status" web method. That way you have a much better idea of whether your "real" call is likely to work.
In other cases, just opening a connection to a port that should be open may be enough - or sending a ping. InetAddress.isReachable
may well be an appropriate API for your needs here.
All these answers are good but the absolute easiest way of doing it is with a fake reset, that is you use a link and a reset button.
Just add some CSS to hide your real reset button.
input[type=reset] { visibility:hidden; height:0; padding:0;}
And then on your link you add as follows
<a href="javascript:{}" onclick="reset.click()">Reset form</a>
<input type="reset" name="reset" id="reset" /><!--This input button is hidden-->
Hope this helps! A.
It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U
. (At least on my machine this produces the same order as listing glob
matches).
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except
. You should catch for a specific exception instead. I captured for Exception
because that's as good as I can do without knowing what exceptions the methods might throw.
Converted the input file to include \N
for the blank column data using the below sed command in UNix terminal:
sed -i 's/,,/,\\N,/g' $file_name
and then use LOAD DATA INFILE
command to load to mysql
@dimas's answer is not logically consistent with your question; ifAllGranted
cannot be directly replaced with hasAnyRole
.
From the Spring Security 3—>4 migration guide:
Old:
<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
New (SPeL):
<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
<p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
Replacing ifAllGranted
directly with hasAnyRole
will cause spring to evaluate the statement using an OR
instead of an AND
. That is, hasAnyRole
will return true
if the authenticated principal contains at least one of the specified roles, whereas Spring's (now deprecated as of Spring Security 4) ifAllGranted
method only returned true
if the authenticated principal contained all of the specified roles.
TL;DR: To replicate the behavior of ifAllGranted
using Spring Security Taglib's new authentication Expression Language, the hasRole('ROLE_1') and hasRole('ROLE_2')
pattern needs to be used.
In spring 2.x
. Options have changed slightly. So the above answers are almost correct but not entirely . In your application.properties
file , add the following-
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
you should change like this:
private string getValue(float price)
{
if(price >0)
return "debit";
return "credit";
}
//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
I thought I would expand on these answers for OSX and Linux folks (not that they need it):
I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.
$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found
DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.
I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)
Let's see:
$ which mvn
/usr/local/bin/mvn
There you are... you little b@stard.
Now where did you get installed to:
$ ls -l /usr/local/bin/mvn
lrwxr-xr-x 1 root wheel 39 Oct 31 13:00 /
/usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn
Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...
Do you have your little buddy mvnDebug with you?
$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
Good. Good. Very good. All going as planned.
Now move that little b@stard where I can remember him more easily.
$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
ln: /usr/local/bin/mvnDebug: Permission denied
Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!
$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)
$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000
Internally mvnDebug uses this:
MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
So you could modify it (I usually debug on port 9090).
This blog explains how to setup Eclipse remote debugging (shudder)
http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html
Ditto Netbeans
https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a
Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html
Here is some good docs on the -Xdebug command in general.
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."
"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."
-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp
Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.
If you don't mind importing the json
module, then the best way to handle it is through json.JSONDecodeError
(or json.decoder.JSONDecodeError
as they are the same) as using default errors like ValueError
could catch also other exceptions not necessarily connected to the json decode one.
from json.decoder import JSONDecodeError
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
# do whatever you want
//EDIT (Oct 2020):
As @Jacob Lee noted in the comment, there could be the basic common TypeError
raised when the JSON object is not a str
, bytes
, or bytearray
. Your question is about JSONDecodeError
, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:
from json.decoder import JSONDecodeError
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
# do whatever you want
except TypeError as e:
# do whatever you want in this case
instead of
$('html, body').animate({scrollTop:xxx}, 'slow');
use
$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');
this will return the absolute top position of whatever element you select as #div_id
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
To remove the variable from the current command session without removing it permanently, use the regular built-in set
command - just put nothing after the equals sign:
set FOOBAR=
To confirm, run set
with no arguments and check the current environment. The variable should be missing from the list entirely.
Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
An enum's default is whatever enumeration equates to zero. I don't believe this is changeable by attribute or other means.
(MSDN says: "The default value of an enum E is the value produced by the expression (E)0.")
Try the JSON Parser by Douglas Crockford at github. You can then simply create a JSON object out of your String variable as shown below:
var JSONText = '{"c":{"a":[{"name":"cable - black","value":2},{"name":"case","value":2}]},"o":{"v":[{"name":"over the ear headphones - white/purple","value":1}]},"l":{"e":[{"name":"lens cleaner","value":1}]},"h":{"d":[{"name":"hdmi cable","value":1},{"name":"hdtv essentials (hdtv cable setup)","value":1},{"name":"hd dvd \u0026 blue-ray disc lens cleaner","value":1}]}'
var JSONObject = JSON.parse(JSONText);
var c = JSONObject["c"];
var o = JSONObject["o"];
public class Car
{
public Car(string model)
{
Console.WriteLine(model);
}
}
public class Mercedes : Car
{
public Mercedes(string model): base(model)
{
}
}
Usage:
Mercedes mercedes = new Mercedes("CLA Shooting Brake");
Output: CLA Shooting Brake
I had this problem. I solved it with downloading 64x of the Java. Here is the link: http://javadl.sun.com/webapps/download/AutoDL?BundleId=87443
<style type="text/css">
.topcorner{
position:absolute;
top:10;
right:15;
}
</style>
You ca also use this in CSS external file.
#! /bin/sh
next=$1
while [ -n "${next}" ] ; do
last=$next
shift
next=$1
done
echo $last
The GD Image Manipulation Library in PHP is probably the best for working with images in PHP. Try one of the imagecopy functions (imagecopy, imagecopymerge, ...). Each of them combine 2 images in different ways. See the php documentation on imagecopy for more information.
Another option is the openxlsx
-package. It doesn't depend on java and can read, edit and write Excel-files. From the description from the package:
openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java
Example usage:
library(openxlsx)
# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')
# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')
Besides these two basic functions, the openxlsx
-package has a host of other functions for manipulating Excel-files.
For example, with the writeDataTable
-function you can create formatted tables in an Excel-file.
In case you do need to define dataSource()
, for example when you have multiple data sources, you can use:
@Autowired Environment env;
@Primary
@Bean
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("custom.datasource.url"));
dataSource.setUsername(env.getProperty("custom.datasource.username"));
dataSource.setPassword(env.getProperty("custom.datasource.password"));
return dataSource;
}
By setting up the dataSource
yourself (instead of using DataSourceBuilder
), it fixed my problem which you also had.
The always knowledgeable Baeldung has a tutorial which explains in depth.
Perform rotation using transform: rotate(xdeg)
and also apply overflow: hidden
to the parent component to avoid overlapping effect
.div-parent {
overflow: hidden
}
.div-child {
transform: rotate(270deg);
}
Here the XAML Version
<Window.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="//your source .."/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
That question solved a quite similar question for me and I thought I should share :
In raw python you can use sum()
to count True
values in a list
:
>>> sum([True,True,True,False,False])
3
But this won't work :
>>> sum([[False, False, True], [True, False, True]])
TypeError...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wb = new WebView(this);
wb.loadUrl("file:///android_asset/index.html");
setContentView(wb);
}
keep your .html in `asset` folder
:first-child
selects the first h1
if and only if it is the first child of its parent element. In your example, the ul
is the first child of the div
.
The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.
jQuery's :first
selector gives you what you're looking for. You can do this:
$('.detail_container h1:first').css("color", "blue");
M refers to the first non-ambiguous character in "decimal". If you don't add it the number will be treated as a double.
D is double.
Well, without converting to string I would do something like:
def lenDigits(x):
"""
Assumes int(x)
"""
x = abs(x)
if x < 10:
return 1
return 1 + lenDigits(x / 10)
Minimalist recursion FTW
It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827
Firefox is around the same value I think as well.
Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.
You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
Do you want to switch to this??
switch(x) {
case 12:
case 16:
case 19:
//Do something
break;
default:
//Do nothing or something else..
break;
}
The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.
/*
* SSHManager
*
* @author cabbott
* @version 1.0
*/
package cabbott.net;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SSHManager
{
private static final Logger LOGGER =
Logger.getLogger(SSHManager.class.getName());
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;
private void doCommonConstructorActions(String userName,
String password, String connectionIP, String knownHostsFileName)
{
jschSSHChannel = new JSch();
try
{
jschSSHChannel.setKnownHosts(knownHostsFileName);
}
catch(JSchException jschX)
{
logError(jschX.getMessage());
}
strUserName = userName;
strPassword = password;
strConnectionIP = connectionIP;
}
public SSHManager(String userName, String password,
String connectionIP, String knownHostsFileName)
{
doCommonConstructorActions(userName, password,
connectionIP, knownHostsFileName);
intConnectionPort = 22;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = timeOutMilliseconds;
}
public String connect()
{
String errorMessage = null;
try
{
sesConnection = jschSSHChannel.getSession(strUserName,
strConnectionIP, intConnectionPort);
sesConnection.setPassword(strPassword);
// UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
// sesConnection.setConfig("StrictHostKeyChecking", "no");
sesConnection.connect(intTimeOut);
}
catch(JSchException jschX)
{
errorMessage = jschX.getMessage();
}
return errorMessage;
}
private String logError(String errorMessage)
{
if(errorMessage != null)
{
LOGGER.log(Level.SEVERE, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, errorMessage});
}
return errorMessage;
}
private String logWarning(String warnMessage)
{
if(warnMessage != null)
{
LOGGER.log(Level.WARNING, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, warnMessage});
}
return warnMessage;
}
public String sendCommand(String command)
{
StringBuilder outputBuffer = new StringBuilder();
try
{
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
}
catch(IOException ioX)
{
logWarning(ioX.getMessage());
return null;
}
catch(JSchException jschX)
{
logWarning(jschX.getMessage());
return null;
}
return outputBuffer.toString();
}
public void close()
{
sesConnection.disconnect();
}
}
For testing.
/**
* Test of sendCommand method, of class SSHManager.
*/
@Test
public void testSendCommand()
{
System.out.println("sendCommand");
/**
* YOU MUST CHANGE THE FOLLOWING
* FILE_NAME: A FILE IN THE DIRECTORY
* USER: LOGIN USER NAME
* PASSWORD: PASSWORD FOR THAT USER
* HOST: IP ADDRESS OF THE SSH SERVER
**/
String command = "ls FILE_NAME";
String userName = "USER";
String password = "PASSWORD";
String connectionIP = "HOST";
SSHManager instance = new SSHManager(userName, password, connectionIP, "");
String errorMessage = instance.connect();
if(errorMessage != null)
{
System.out.println(errorMessage);
fail();
}
String expResult = "FILE_NAME\n";
// call sendCommand for each command and the output
//(without prompts) is returned
String result = instance.sendCommand(command);
// close only after all commands are sent
instance.close();
assertEquals(expResult, result);
}
Either as most people answered: the file doesn't exist / you're not specifying the path correctly.
Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).
For gnuplot 4.6.0 on windows 7, terminal type set to windows
Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")
Make sure you use this syntax:
plot 'path\path\desireddatafile.txt'
NOT
plot "< path\path\desireddatafile.txt>"
NOR
plot "path\path\desireddatafile.txt"
also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.
In Android 2.0+ this would look like:
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
In earlier versions it would look like:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
YourClass.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}
If you're using PDO don't forget to initiate it with UTF8:
$con = new PDO('mysql:host=' . $server . ';dbname=' . $db . ';charset=UTF8', $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
(just spent 5 hours to figure this out, hope it will save someone precious time...)
Output buffering is used by PHP to improve performance and to perform a few tricks.
You can have PHP store all output into a buffer and output all of it at once improving network performance.
You can access the buffer content without sending it back to browser in certain situations.
Consider this example:
<?php
ob_start( );
phpinfo( );
$output = ob_get_clean( );
?>
The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.
Consider this example:
<?php
ob_start( );
echo "Hello World";
if ( $some_error )
{
header( "Location: error.php" );
exit( 0 );
}
?>
Building on this question, I use the following code to indent my messages:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
This is the output:
short text: indented looooooooooooooong text: indented
This is documented in section "Flag characters" in man 3 printf
.
rng.step(n=1) {| obj | block } => rng
Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.
range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}
produces:
1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx
Reference: http://ruby-doc.org/core/classes/Range.html
......
Recently, I have tried to develop a simple web app that uses drag and drop components and has lines connecting them. I came across these two simple and amazing javascript libraries:
Working example link (usage: click on add scene to create a draggable, click on add choice to draw a leader line between two different draggables)
Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
android:textColorHint="#FFFFFF" sometime works and sometime doesnt. For me below solution works perfectly
Try The Below Code It Works In your XML file and TextLabel theme is defined in style.xml
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="@style/MyTextLabel">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Floating Label"
android:id="@+id/edtText"/>
</android.support.design.widget.TextInputLayout>
In Styles Folder TextLabel Code
<style name="MyTextLabel" parent="TextAppearance.AppCompat">
<!-- Hint color and label color in FALSE state -->
<item name="android:textColorHint">@color/Color Name</item>
<!--The size of the text appear on label in false state -->
<item name="android:textSize">20sp</item>
<!-- Label color in TRUE state and bar color FALSE and TRUE State -->
<item name="colorAccent">@color/Color Name</item>
<item name="colorControlNormal">@color/Color Name</item>
<item name="colorControlActivated">@color/Color Name</item>
</style>
If you just want to change the color of label in false state then colorAccent , colorControlNormal and colorControlActivated are not required
The simplest solution is to use:
plt.xticks(rotation=XX)
but also
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)
e.g for dates I used rotation=45 and bottom=0.20 but you can do some test for your data
If for some reason you don't want to use the plugin, then here's the script you can use to copy the resources to your android studio project:
echo "..:: Copying resources ::.."
echo "Enter folder:"
read srcFolder
echo "Enter filename with extension:"
read srcFile
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxxhdpi/"$srcFile"/
echo "xxxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xxhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xxhdpi/"$srcFile"/
echo "xxhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-xhdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-xhdpi/"$srcFile"/
echo "xhdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-hdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-hdpi/"$srcFile"/
echo "hdpi copied"
cp /Users/YOUR_USER/Downloads/material-design-icons-master/"$srcFolder"/drawable-mdpi/"$srcFile" /Users/YOUR_USER/AndroidStudioProjects/YOUR_PROJECT/app/src/main/res/drawable-mdpi/"$srcFile"/
echo "mdpi copied"
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
Try to replace it with °
, and also to set the charset to utf-8, as Martin suggests.
°C
will get you something like this:
Expanding on the answer from @Met, also using Perl:
If the input and output are TAB-delimited:
perl -F'\t' -lane 'print join "\t", @F[1, 0]' in_file
If the input and output are whitespace-delimited:
perl -lane 'print join " ", @F[1, 0]' in_file
Here,
-e
tells Perl to look for the code inline, rather than in a separate script file,
-n
reads the input 1 line at a time,
-l
removes the input record separator (\n
on *NIX) after reading the line (similar to chomp
), and add output record separator (\n
on *NIX) to each print
,
-a
splits the input line on whitespace into array @F
,
-F'\t'
in combination with -a
splits the input line on TABs, instead of whitespace into array @F
.
@F[1, 0]
is the array made up of the 2nd and 1st elements of array @F
, in this order. Remember that arrays in Perl are zero-indexed, while fields in cut
are 1-indexed. So fields in @F[0, 1]
are the same fields as the ones in cut -f1,2
.
Note that such notation enables more flexible manipulation of input than in some other answers posted above (which are fine for a simple task). For example:
# reverses the order of fields:
perl -F'\t' -lane 'print join "\t", reverse @F' in_file
# prints last and first fields only:
perl -F'\t' -lane 'print join "\t", @F[-1, 0]' in_file
Others have given the 'Why', so I'll just add that your interface can define a Control; if you wrap it in a property:
public interface IView {
Control Year { get; }
}
public Form : IView {
public Control Year { get { return uxYear; } } //numeric text box or whatever
}
The reader acts like a generator. On a file with some fake data:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Using operator.itemgetter as Ignacio suggests:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
Check your Project -> Properties -> Java Build Path has JDK
Library instead of JRE System Library
.
Go to Eclipse
installed directory, Search eclipse.ini
-> Open it
Search lines for containing any below values:
-Xms512m -Xmx512m -Xms1024m -Xmx1024m -Xms1G -Xmx1G
Just double it the memory size, Assume you have to change the
-Xms512m to -Xms1024m
Increasing the eclipse memory size will help eclipse
to gain more RAM size from your PC.
Just addition to above answers ..
[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring
For Ex..
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
[Route("{Latitude}/{Longitude}")]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
Can be called like:
http://localhost/api/values/47.678558/-122.130989
In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.
If a control is disabled
it cannot be edited and its content is excluded when the form is submitted.
If a control is readonly
it cannot be edited, but its content (if any) is still included with the submission.
You add the .ico in your resource as bobobobo said and then in your main dialog's constructor you modify:
m_hIcon = AfxGetApp()->LoadIcon(ICON_ID_FROM_RESOURCE.H);
As others have noted, in order for a jar file to be executable, the application's entry point must be set in the Main-Class
attribute of the manifest file. If the dependency class files are not collocated, then they need to be set in the Class-Path
entry of the manifest file.
I have tried all kinds of plugin combinations and what not for the simple task of creating an executable jar and somehow someway, include the dependencies. All plugins seem to be lacking one way or another, but finally I got it like I wanted. No mysterious scripts, not a million different mini files polluting the build directory, a pretty clean build script file, and above all: not a million foreign third party class files merged into my jar archive.
The following is a copy-paste from here for your convenience..
[How-to] create a distribution zip file with dependency jars in subdirectory /lib
and add all dependencies to Class-Path
entry in the manifest file:
apply plugin: 'java'
apply plugin: 'java-library-distribution'
repositories {
mavenCentral()
}
dependencies {
compile 'org.apache.commons:commons-lang3:3.3.2'
}
// Task "distZip" added by plugin "java-library-distribution":
distZip.shouldRunAfter(build)
jar {
// Keep jar clean:
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
manifest {
attributes 'Main-Class': 'com.somepackage.MainClass',
'Class-Path': configurations.runtime.files.collect { "lib/$it.name" }.join(' ')
}
// How-to add class path:
// https://stackoverflow.com/questions/22659463/add-classpath-in-manifest-using-gradle
// https://gist.github.com/simon04/6865179
}
Hosted as a gist here.
The result can be found in build/distributions
and the unzipped contents look like this:
lib/commons-lang3-3.3.2.jar
MyJarFile.jar
Contents of MyJarFile.jar#META-INF/MANIFEST.mf
:
Manifest-Version: 1.0
Main-Class: com.somepackage.MainClass
Class-Path: lib/commons-lang3-3.3.2.jar
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
Nothing, they will produce the same result
The PropertiesPlaceholderConfigurer
bean has an alternative property called "propertiesArray". Use this instead of the "properties" property, and configure it with an <array>
of property references.
Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.
' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit
Private Type FourBytes
A As Byte
B As Byte
C As Byte
D As Byte
End Type
Private Type OneLong
L As Long
End Type
Function HexDefaultSHA1(Message() As Byte) As String
Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
DefaultSHA1 Message, H1, H2, H3, H4, H5
HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function
Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function
Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub
Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
'"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
Dim U As Long, P As Long
Dim FB As FourBytes, OL As OneLong
Dim i As Integer
Dim W(80) As Long
Dim A As Long, B As Long, C As Long, D As Long, E As Long
Dim T As Long
H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0
U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)
ReDim Preserve Message(0 To (U + 8 And -64) + 63)
Message(U) = 128
U = UBound(Message)
Message(U - 4) = A
Message(U - 3) = FB.D
Message(U - 2) = FB.C
Message(U - 1) = FB.B
Message(U) = FB.A
While P < U
For i = 0 To 15
FB.D = Message(P)
FB.C = Message(P + 1)
FB.B = Message(P + 2)
FB.A = Message(P + 3)
LSet OL = FB
W(i) = OL.L
P = P + 4
Next i
For i = 16 To 79
W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
Next i
A = H1: B = H2: C = H3: D = H4: E = H5
For i = 0 To 19
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 20 To 39
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 40 To 59
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
For i = 60 To 79
T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
Next i
H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
Wend
End Sub
Function U32Add(ByVal A As Long, ByVal B As Long) As Long
If (A Xor B) < 0 Then
U32Add = A + B
Else
U32Add = (A Xor &H80000000) + B Xor &H80000000
End If
End Function
Function U32ShiftLeft3(ByVal A As Long) As Long
U32ShiftLeft3 = (A And &HFFFFFFF) * 8
If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function
Function U32ShiftRight29(ByVal A As Long) As Long
U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function
Function U32RotateLeft1(ByVal A As Long) As Long
U32RotateLeft1 = (A And &H3FFFFFFF) * 2
If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function
Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
Dim H As String, L As Long
DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function
' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog
Public Function SHA1HASH(str)
Dim i As Integer
Dim arr() As Byte
ReDim arr(0 To Len(str) - 1) As Byte
For i = 0 To Len(str) - 1
arr(i) = Asc(Mid(str, i + 1, 1))
Next i
SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
What would be useful here would be a LIKE ANY
predicate as is available in PostgreSQL
SELECT *
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])
Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR
, however:
SELECT *
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...
Or alternatively, create a semi join using an EXISTS
predicate and an auxiliary array data structure (see this question for details):
SELECT *
FROM tbl t
WHERE EXISTS (
SELECT 1
-- Alternatively, store those values in a temp table:
FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
WHERE t.my_col LIKE column_value
)
For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
I found another relatively simple way to solve that problem. By using this method we will not required to alter our cell which is almost always related to data array index, potentially causing mess in our view controller.
First, we add this following properties to our controller class:
@property (strong, nonatomic) NSMutableArray* collapsedSections;
@property (strong, nonatomic) NSMutableArray* sectionViews;
collapsedSections
will save collapsed section numbers.
sectionViews
will store our custom section view.
Synthesize it:
@synthesize collapsedSections;
@synthesize sectionViews;
Initialize it:
- (void) viewDidLoad
{
[super viewDidLoad];
self.collapsedSections = [NSMutableArray array];
self.sectionViews = [NSMutableArray array];
}
After that, we must connect our UITableView so it can be accessed from within our view controller class:
@property (strong, nonatomic) IBOutlet UITableView *tblMain;
Connect it from XIB to view controller using ctrl + drag
like usually.
Then we create view as custom section header for our table view by implementing this UITableView delegate:
- (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// Create View
CGRect frame = CGRectZero;
frame.origin = CGPointZero;
frame.size.height = 30.f;
frame.size.width = tableView.bounds.size.width;
UIView* view = [[UIView alloc] initWithFrame:frame];
[view setBackgroundColor:[UIColor blueColor]];
// Add label for title
NSArray* titles = @[@"Title 1", @"Title 2", @"Title 3"];
NSString* selectedTitle = [titles objectAtIndex:section];
CGRect labelFrame = frame;
labelFrame.size.height = 30.f;
labelFrame.size.width -= 20.f;
labelFrame.origin.x += 10.f;
UILabel* titleLabel = [[UILabel alloc] initWithFrame:labelFrame];
[titleLabel setText:selectedTitle];
[titleLabel setTextColor:[UIColor whiteColor]];
[view addSubview:titleLabel];
// Add touch gesture
[self attachTapGestureToView:view];
// Save created view to our class property array
[self saveSectionView:view inSection:section];
return view;
}
Next, we implement method to save our previously created custom section header in class property:
- (void) saveSectionView:(UIView*) view inSection:(NSInteger) section
{
NSInteger sectionCount = [self numberOfSectionsInTableView:[self tblMain]];
if(section < sectionCount)
{
if([[self sectionViews] indexOfObject:view] == NSNotFound)
{
[[self sectionViews] addObject:view];
}
}
}
Add UIGestureRecognizerDelegate
to our view controller .h file:
@interface MyViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>
Then we create method attachTapGestureToView:
- (void) attachTapGestureToView:(UIView*) view
{
UITapGestureRecognizer* tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
[tapAction setDelegate:self];
[view addGestureRecognizer:tapAction];
}
Above method will add tap gesture recognizer to all of section view we created before. Next we should implement onTap:
selector
- (void) onTap:(UITapGestureRecognizer*) gestureRecognizer
{
// Take view who attach current recognizer
UIView* sectionView = [gestureRecognizer view];
// [self sectionViews] is Array containing our custom section views
NSInteger section = [self sectionNumberOfView:sectionView];
// [self tblMain] is our connected IBOutlet table view
NSInteger sectionCount = [self numberOfSectionsInTableView:[self tblMain]];
// If section more than section count minus one set at last
section = section > (sectionCount - 1) ? 2 : section;
[self toggleCollapseSection:section];
}
Above method will invoked when user tap any of our table view section. This method search correct section number based on our sectionViews
array we created before.
Also, we implement method to get wihch section of header view belongs to.
- (NSInteger) sectionNumberOfView:(UIView*) view
{
UILabel* label = [[view subviews] objectAtIndex:0];
NSInteger sectionNum = 0;
for(UIView* sectionView in [self sectionViews])
{
UILabel* sectionLabel = [[sectionView subviews] objectAtIndex:0];
//NSLog(@"Section: %d -> %@ vs %@", sectionNum, [label text], [sectionLabel text]);
if([[label text] isEqualToString:[sectionLabel text]])
{
return sectionNum;
}
sectionNum++;
}
return NSNotFound;
}
Next, we must implement method toggleCollapseSection:
- (void) toggleCollapseSection:(NSInteger) section
{
if([self isCollapsedSection:section])
{
[self removeCollapsedSection:section];
}
else
{
[self addCollapsedSection:section];
}
[[self tblMain] reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}
This method will insert/remove section number to our collapsedSections
array we created before. When a section number inserted to that array, it means that the section should be collapsed and expanded if otherwise.
Next we implement removeCollapsedSection:
, addCollapsedSection:section
and isCollapsedSection:section
- (BOOL)isCollapsedSection:(NSInteger) section
{
for(NSNumber* existing in [self collapsedSections])
{
NSInteger current = [existing integerValue];
if(current == section)
{
return YES;
}
}
return NO;
}
- (void)removeCollapsedSection:(NSInteger) section
{
[[self collapsedSections] removeObjectIdenticalTo:[NSNumber numberWithInteger:section]];
}
- (void)addCollapsedSection:(NSInteger) section
{
[[self collapsedSections] addObject:[NSNumber numberWithInteger:section]];
}
This three method is just helpers to make us easier in accessing collapsedSections
array.
Finally, implement this table view delegate so our custom section views looks nice.
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30.f; // Same as each custom section view height
}
Hope it helps.
Maybe I missed the question, but why not:
class MyException(Exception):
pass
Edit: to override something (or pass extra args), do this:
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super(ValidationError, self).__init__(message)
# Now for your custom code...
self.errors = errors
That way you could pass dict of error messages to the second param, and get to it later with e.errors
Python 3 Update: In Python 3+, you can use this slightly more compact use of super()
:
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super().__init__(message)
# Now for your custom code...
self.errors = errors
For a vector m
, m[round(m) != m]
will return the indices of values in the vector that are not integers.
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
I do it this way for Android 2.2 Froyo release: basically use eclipse to create a class like: public class SomePickContactName extends Activity
then insert this code. Remember to add the private class variables and CONSTANTS referenced in my version of the code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, PICK_CONTACT);
}//onCreate
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_CONTACT)
{
getContactInfo(intent);
// Your class variables now have the data, so do something with it.
}
}//onActivityResult
protected void getContactInfo(Intent intent)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
// Find Email Addresses
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
Cursor address = getContentResolver().query(
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
null, null);
while (address.moveToNext())
{
// These are all private class variables, don't forget to create them.
poBox = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
type = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
} //address.moveToNext()
} //while (cursor.moveToNext())
cursor.close();
}//getContactInfo
Your initial statement in the marked solution isn't entirely true. While your new solution may accomplish your original goal, it is still possible to circumvent the original error while preserving your AuthorizationHandler logic--provided you have basic authentication scheme handlers in place, even if they are functionally skeletons.
Speaking broadly, Authentication Handlers and schemes are meant to establish + validate identity, which makes them required for Authorization Handlers/policies to function--as they run on the supposition that an identity has already been established.
ASP.NET Dev Haok summarizes this best best here: "Authentication today isn't aware of authorization at all, it only cares about producing a ClaimsPrincipal per scheme. Authorization has to be aware of authentication somewhat, so AuthenticationSchemes in the policy is a mechanism for you to associate the policy with schemes used to build the effective claims principal for authorization (or it just uses the default httpContext.User for the request, which does rely on DefaultAuthenticateScheme)." https://github.com/aspnet/Security/issues/1469
In my case, the solution I'm working on provided its own implicit concept of identity, so we had no need for authentication schemes/handlers--just header tokens for authorization. So until our identity concepts changes, our header token authorization handlers that enforce the policies can be tied to 1-to-1 scheme skeletons.
Tags on endpoints:
[Authorize(AuthenticationSchemes = "AuthenticatedUserSchemeName", Policy = "AuthorizedUserPolicyName")]
Startup.cs:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "AuthenticatedUserSchemeName";
}).AddScheme<ValidTokenAuthenticationSchemeOptions, ValidTokenAuthenticationHandler>("AuthenticatedUserSchemeName", _ => { });
services.AddAuthorization(options =>
{
options.AddPolicy("AuthorizedUserPolicyName", policy =>
{
//policy.RequireClaim(ClaimTypes.Sid,"authToken");
policy.AddAuthenticationSchemes("AuthenticatedUserSchemeName");
policy.AddRequirements(new ValidTokenAuthorizationRequirement());
});
services.AddSingleton<IAuthorizationHandler, ValidTokenAuthorizationHandler>();
Both the empty authentication handler and authorization handler are called (similar in setup to OP's respective posts) but the authorization handler still enforces our authorization policies.
Replace checked="checked"
with checked={true}
. Or you could even shorten it to just checked
.
This is because the expected value type of the checked
prop is a boolean. not a string.
DateTime#to_date
does exist with ActiveSupport:
$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
from (irb):1
>> require 'active_support/core_ext'
=> true
>> DateTime.new.to_date
=> Mon, 01 Jan -4712
I also did a little workaround of my own.
I created a (dropdownOpen) event which I listen to at my ng-select element component and call a function which will close all the other SelectComponent's opened apart from the currently opened SelectComponent.
I modified one function inside the select.ts file like below to emit the event:
private open():void {
this.options = this.itemObjects
.filter((option:SelectItem) => (this.multiple === false ||
this.multiple === true && !this.active.find((o:SelectItem) => option.text === o.text)));
if (this.options.length > 0) {
this.behavior.first();
}
this.optionsOpened = true;
this.dropdownOpened.emit(true);
}
In the HTML I added an event listener for (dropdownOpened):
<ng-select #elem (dropdownOpened)="closeOtherElems(elem)"
[multiple]="true"
[items]="items"
[disabled]="disabled"
[isInputAllowed]="true"
(data)="refreshValue($event)"
(selected)="selected($event)"
(removed)="removed($event)"
placeholder="No city selected"></ng-select>
This is my calling function on event trigger inside the component having ng2-select tag:
@ViewChildren(SelectComponent) selectElem :QueryList<SelectComponent>;
public closeOtherElems(element){
let a = this.selectElem.filter(function(el){
return (el != element)
});
a.forEach(function(e:SelectComponent){
e.closeDropdown();
})
}
I have just include Maven integration plug-in at Eclipse:
Just follow the bellow steps:
In eclipse, from upper menu item select- "Help" ->click on "Install New Software.."-> then click on "Add" button.
set the "MavenAPI" at name text box and "http://download.eclipse.org/technology/m2e/releases" at location text box.
press Ok and select the Maven project and install by clicking next next.
You can use relative paths. Try __FILE__
. This is a PHP constant which always returns the path/filename of the script it is in. So, in soap.php
, you could do:
include dirname(__FILE__).'/../inc/include.php';
The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2,
__FILE__
always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances. (source)
Another solution would be to set an include path in your httpd.conf or an .htaccess file.
Hope this helps :)
begins the session, you need to say this at the top of a page or before you call session code
session_start();
put a user id in the session to track who is logged in
$_SESSION['user'] = $user_id;
Check if someone is logged in
if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}
Find the logged in user ID
$_SESSION['user']
So on your page
<?php
session_start();
if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php
} else {
?>
Not logged in HTML and code here
<?php
}
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables