find . -name '*.pyc' -print0 | xargs -0 rm
The find recursively looks for *.pyc files. The xargs takes that list of names and sends it to rm. The -print0 and the -0 tell the two commands to seperate the filenames with null characters. This allows it to work correctly on file names containing spaces, and even a file name containing a new line.
The solution with -exec works, but it spins up a new copy of rm for every file. On a slow system or with a great many files, that'll take too long.
You could also add a couple more args:
find . -iname '*.pyc' -print0 | xargs -0 --no-run-if-empty rm
iname adds case insensitivity, like *.PYC . The no-run-if-empty keeps you from getting an error from rm if you have no such files.
The way I always do this is like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example_string_to_int
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
// This turns the text in text box 1 into a string
int b;
if (!int.TryParse(a, out b))
{
MessageBox.Show("This is not a number");
}
else
{
textBox2.Text = a+" is a number" ;
}
// Then this 'if' statement says if the string is not a number, display an error, else now you will have an integer.
}
}
}
This is how I would do it.
eval:
This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.
ast.literal_eval:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.
Syntax:
eval(expression, globals=None, locals=None)
import ast
ast.literal_eval(node_or_string)
Example:
# python 2.x - doesn't accept operators in string format
import ast
ast.literal_eval('[1, 2, 3]') # output: [1, 2, 3]
ast.literal_eval('1+1') # output: ValueError: malformed string
# python 3.0 -3.6
import ast
ast.literal_eval("1+1") # output : 2
ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}") # output : {'a': 2, 'b': 3, 3:'xyz'}
# type dictionary
ast.literal_eval("",{}) # output : Syntax Error required only one parameter
ast.literal_eval("__import__('os').system('rm -rf /')") # output : error
eval("__import__('os').system('rm -rf /')")
# output : start deleting all the files on your computer.
# restricting using global and local variables
eval("__import__('os').system('rm -rf /')",{'__builtins__':{}},{})
# output : Error due to blocked imports by passing '__builtins__':{} in global
# But still eval is not safe. we can access and break the code as given below
s = """
(lambda fc=(
lambda n: [
c for c in
().__class__.__bases__[0].__subclasses__()
if c.__name__ == n
][0]
):
fc("function")(
fc("code")(
0,0,0,0,"KABOOM",(),(),(),"","",0,""
),{}
)()
)()
"""
eval(s, {'__builtins__':{}})
In the above code ().__class__.__bases__[0]
nothing but object itself.
Now we instantiated all the subclasses, here our main enter code here
objective is to find one class named n from it.
We need to code
object and function
object from instantiated subclasses. This is an alternative way from CPython
to access subclasses of object and attach the system.
From python 3.7 ast.literal_eval() is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. link
Use this function
var result = $('div').sort(function (a, b) {
var contentA =parseInt( $(a).data('sort'));
var contentB =parseInt( $(b).data('sort'));
return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
});
$('#mylist').html(result);
You can call this function just after adding new divs.
If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:
$(targetSelector).sort(function (a, b) {
// ...
}).appendTo($container);
Try this one.
<textarea maxlength="410" name="about_me" onkeydown="CountLeft(this.form.about_me, this.form.left);" onkeyup="CountLeft(this.form.about_me,this.form.left); "></textarea>
<input maxlength="3" name="left" readonly="" size="3" type="text" value="410" /> characters left
<script>
function CountLeft(field, count)
{
var max = "410";
if (field.value.length > max)
{
field.value = field.value.substring(0, max);
}
else
{
count.value = max - field.value.length;
}
}
</script>
I seriously do think that it is code smell if you need to mock static methods, too.
The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies.
I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)
PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...
I guess you're wondering why C or C++ lets you manipulate an object pointer like a number, but you can't manipulate an object reference in Java the same way.
Object references in Java aren't like pointers in C or C++... Pointers basically are integers and you can manipulate them like any other int. References are intentionally a more concrete abstraction and cannot be manipulated the way pointers can.
Found another answer from the npmjs.org
https://www.npmjs.com/package/cordova-plugin-update
Basically its installing the tool into your project:
npm install -g cordova-plugin-update
when done you then have to run the command
cordova-plugin-update
and it will prompt you to update if ever a newer version of a plugin is available
What kind of dates do you have in the column?
Do all of them fit within the range of the type?
As an aside, the correct way to get a Type
object for the DataColumn
constructor is the typeof
keyword, which is orders of magnitude faster.
Therefore, to create the column, you should write
new DataColumn("myDate", typeof(DateTime))
The interesting thing about mb_detect_encoding
and mb_convert_encoding
is that the order of the encodings you suggest does matter:
// $input is actually UTF-8
mb_detect_encoding($input, "UTF-8", "ISO-8859-9, UTF-8");
// ISO-8859-9 (WRONG!)
mb_detect_encoding($input, "UTF-8", "UTF-8, ISO-8859-9");
// UTF-8 (OK)
So you might want to use a specific order when specifying expected encodings. Still, keep in mind that this is not foolproof.
First, Navigate to the TOMCAT-HOME/bin
directory.
Then, Execute the following in the command-line:
catalina.bat jpda start
If the Tomcat server is running under Linux, just invoke the catalina.sh
program
catalina.sh jpda start
It's the same for Tomcat 5.5 and Tomcat 6
This message means the 'emulator-x86' or 'emulator64-x86' program is missing from $SDK/tools/, or cannot be found for some reason.
First of all, are you sure you have a valid download / install of the SDK?
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
Here is an example to play with Inline SVG for a list bullet (2020 Browsers)
list-style-image: url("data:image/svg+xml,
<svg width='50' height='50'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 72 72'>
<rect width='100%' height='100%' fill='pink'/>
<path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3
l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30
m-54 24v-24h9v24z'/></svg>")
width
& height
to set the sizeM70 42
to position the handrect
li{
font-size:2em;
list-style-image: url("data:image/svg+xml,<svg width='3em' height='3em' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 72 72'><rect width='100%' height='100%' fill='pink'/><path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3 3h-12l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30m-54 24v-24h9v24z'/></svg>");
}
span{
display:inline-block;
vertical-align:top;
margin-top:-10px;
margin-left:-5px;
}
_x000D_
<ul>
<li><span>Apples</span></li>
<li><span>Bananas</span></li>
<li>Oranges</li>
</ul>
_x000D_
I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?
No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:
var someVar = options.filters.firstName; //Returns 'abc'
Or by iterating over them using the for ... in
loop:
for(var p in options.filters) {
var someVar = options.filters[p]; //Returns the property being iterated
}
First I would like to thank Rose who was willing to help us, but your answer could solve the problem on a computer, but in others there was what was done could not always connect gets error 720. After much searching and contact the Microsoft support we can solve. In Device Manager, on the View menu, select to show hidden devices. Made it look for a remote Miniport IP or network monitor that is with warning of problems with the driver icon. In its properties in the details tab check the Key property of the driver. Look for this key in Regedit on Local Machine, make a backup of that key and delete it. Restart your windows. Reopen your device manager and select the miniport that had deleted the record. Activate the option to update the driver and look for the option driver on the computer manually and then use the option to locate the driver from the list available on the computer on the next screen uncheck show compatible hardware. Then you must select the Microsoft Vendor and the driver WAN Miniport the type that is changing, IP or IPV6 L2TP Network Monitor. After upgrading restart the computer.
I know it's a bit laborious but that was the only way that worked on all computers.
$('.close').click(function() {
//Code to be executed when close is clicked
$('#result').html('yes,result');
});
A little extension to the above answers. The trailing >
directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >>
that appends, adding your new content to the end of the file, as in:
cat <<EOF >> /etc/fstab
data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
data_server:/var/sharedServer/cert /var/sharedFolder/sometin/vsdc/cert nfs
EOF
This extends your fstab
without you having to worry about accidentally modifying any of its contents.
Use any of the following:
String str = String.valueOf('c');
String str = Character.toString('c');
String str = 'c' + "";
Add a space
between them (or more depending on your preference)
<div style="text-align: center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>
You can do this in CSS:
a.menu_links {
cursor: pointer;
}
This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href
attribute in there (it's missing from your example).
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
To answer your question:
If we can have inner private class then why can't we have outer private class...?
You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:
If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)
Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.
Try moving that mysql.bak
directory out of /var/lib/mysql
to say /root/
or something. It seems like mysql is finding that and it may be causing that ERROR 1102 (42000): Incorrect database name 'mysql.bak'
error.
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));
What I use everywhere :
Runtime.getRuntime().exec("pm clear me.myapp");
Executing above piece of code closes application and removes all databases and shared preferences
Provided the char array is null
terminated,
char chararray[10] = { 0 };
size_t len = strlen(chararray);
I had the same problem and I rename the "repository" folder on ".m2" (something like repositoryBkp the name is not important is just in case something goes wrong) and create a new "repository" folder, then I re run maven and all the project compile successfully
I have just figured out something with this error.
Just make sure that the library jar file contains the compiled R class under android.support.v7.appcompat package and copy all the res in the v7 appcompat support "project" in your ANDROID_SDK_HOME/extras/android/support/v7/appcompat folder.
I use Netbeans with the Android plugin and this solved my issue.
You should check for the type of the item in the localStorage
if(localStorage.token !== null) {
// this will only work if the token is set in the localStorage
}
if(typeof localStorage.token !== 'undefined') {
// do something with token
}
if(typeof localStorage.token === 'undefined') {
// token doesn't exist in the localStorage, maybe set it?
}
What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?
You can create new environment variables with RewriteRule lines, as mentioned by OP:
RewriteRule ^(.*) - [E=TEST0:%{DOCUMENT_ROOT}/blog/html_cache/$1.html]
But if you can't get a server-side script to work, how can you then read this environment variable? One solution is to set a header:
Header set TEST_FOOBAR "%{REDIRECT_TEST0}e"
The value accepts format specifiers, including the %{NAME}e
specifier for environment variables (don't forget the lowercase e). Sometimes, you'll need to add the REDIRECT_
prefix, but I haven't worked out when the prefix gets added and when it doesn't.
I too was searching for this for sometime, and finally was able to do it as I needed, ie Navigation Bar is inaccessible, status bar is inaccessible, even if you long press power button, neither the power menu nor navigation buttons are shown. Thanks to @Assaf Gamliel , his answer took me to the right path.
I followed this tutorial with some slight modifications. While specifying Type, I specified WindowManager.LayoutParams.TYPE_SYSTEM_ERROR
instead of WindowManager.LayoutParams.TYPE_PHONE
, else our "overlay" won't hide the system bars. You can play around with the Flags, Height, Width etc so that it'll behave as you want it to.
SELECT
[User], Activity,
STUFF(
(SELECT DISTINCT ',' + PageURL
FROM TableName
WHERE [User] = a.[User] AND Activity = a.Activity
FOR XML PATH (''))
, 1, 1, '') AS URLList
FROM TableName AS a
GROUP BY [User], Activity
On Mac install nginx with brew:
/usr/local/etc/nginx/nginx.conf
location / {
root html; # **means /usr/local/Cellar/nginx/1.8.0/html and it soft linked to /usr/local/var/www**
index index.html;
}
Try this one:
Sub clear_sht
Dim sht As Worksheet
Set sht = Worksheets(GENERATOR_SHT_NAME)
col_cnt = sht.UsedRange.Columns.count
If col_cnt = 0 Then
col_cnt = 1
End If
sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub
Declare the Start and End date
DECLARE @SDATE AS DATETIME
TART_DATE AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE = DATEADD(SECOND, 3910, GETDATE())
-- Get the Result in HH:MI:SS:MMM(24H) format
SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
The new official AWS CLI natively supports most of the functionality of s3cmd
. I'd previously been using s3cmd
or the ruby AWS SDK to do things like this, but the official CLI works great for this.
http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html
aws s3 sync s3://oldbucket s3://newbucket
It is called the Card Security Code (CSC) according to Wikipedia, but has also been known as other things, such as the Card Verification Value (CVV) or Card Verfication Code (CVC).
The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
Because this seems to be known by multiple names, and its name doesn't seem to be printed on the card itself, you'll probably (unfortunately) still need to tell your users how to find the code - ie by describing it as the "3 digit code on back of card".
2018 update
The situation has not improved, and is now worse - there are even more different names now. However, you can if you like use different terms depending on the card type:
Note that some American Express and Discover cards use a 4-digit code on the front of the card. See the above linked Wikipedia article for more.
You can use styles for modifiy the login button like this
<style name="FacebookLoginButton">
<item name="android:textSize">@dimen/smallTxtSize</item>
<item name="android:background">@drawable/facebook_signin_btn</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:layout_marginBottom">10dp</item>
<item name="android:layout_gravity">center_horizontal</item>
</style>
and in layout
<com.facebook.widget.LoginButton
xmlns:fb="http://schemas.android.com/apk/res-auto"
android:id="@+id/loginFacebookButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
fb:login_text="@string/loginFacebookButton"
fb:logout_text=""
style="@style/FacebookLoginButton"/>
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
Pre-append your commands with sudo
.
For example, Instead of vim textfile.txt
, used sudo vim textfile.txt
. This will resolve the issue.
It is likely a scope issue. Try the following instead:
addToBasket: function(){
item = this.photo;
this.$http.post('/api/buy/addToBasket', item);
this.basketAddSuccess = true;
var self = this;
setTimeout(function(){
self.basketAddSuccess = false;
}, 2000);
}
(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.
My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.
# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE
[according to Martin Beckett, the guy who send me this answer ]
You can debug into an external library.
In the project settings tab look for 'visual studio directories' in the 'source code' field include the path to the openCV sources. Then make sure that the .pdb files for each of the debug dll are in the same directory as the dll.
TL;DR: Use the error
function:
ifndef MY_FLAG
$(error MY_FLAG is not set)
endif
Note that the lines must not be indented. More precisely, no tabs must precede these lines.
In case you're going to test many variables, it's worth defining an auxiliary function for that:
# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
# 1. Variable name(s) to test.
# 2. (optional) Error message to print.
check_defined = \
$(strip $(foreach 1,$1, \
$(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
$(if $(value $1),, \
$(error Undefined $1$(if $2, ($2))))
And here is how to use it:
$(call check_defined, MY_FLAG)
$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
LIB_INCLUDE_DIR \
LIB_SOURCE_DIR, \
library path)
This would output an error like this:
Makefile:17: *** Undefined OUT_DIR (build directory). Stop.
The real check is done here:
$(if $(value $1),,$(error ...))
This reflects the behavior of the ifndef
conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:
# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)
# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)
As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:
$(if $(value $1)
tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use$(if $(filter undefined,$(origin $1)) ...
And:
Moreover, if it's a directory and it must exist when the check is run, I'd use
$(if $(wildcard $1))
. But would be another function.
It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.
$(call check_defined, ...)
from inside the recipeJust move the check into the recipe:
foo :
@:$(call check_defined, BAR, baz value)
The leading @
sign turns off command echoing and :
is the actual command, a shell no-op stub.
The check_defined
function can be improved to also output the target name (provided through the $@
variable):
check_defined = \
$(strip $(foreach 1,$1, \
$(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
$(if $(value $1),, \
$(error Undefined $1$(if $2, ($2))$(if $(value @), \
required by target `$@')))
So that, now a failed check produces a nicely formatted output:
Makefile:7: *** Undefined BAR (baz value) required by target `foo'. Stop.
check-defined-MY_FLAG
special targetPersonally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:
# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
# %: The name of the variable to test.
#
check-defined-% : __check_defined_FORCE
@:$(call check_defined, $*, target-specific)
# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :
Usage:
foo :|check-defined-BAR
Notice that the check-defined-BAR
is listed as the order-only (|...
) prerequisite.
Pros:
Cons:
make -t
(see Instead of Executing Recipes) will pollute your root directory with lots of check-defined-...
files. This is a sad drawback of the fact that pattern rules can't be declared .PHONY
.I believe, these limitations can be overcome using some eval
magic and secondary expansion hacks, although I'm not sure it's worth it.
GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH
. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:
export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :
The checked content attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />
The following are invalid:
<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text" />
Recommendation
If you care about writing valid XHTML, use disabled="disabled"
, since <input disabled>
is invalid and other alternatives are less readable. Else, just use <input disabled>
as it is shorter.
I had the same problem, in fact, I juste forgot to run the service after installation ..
Start mysql server :
/etc/init.d/mysql start
You may also use this.Resources["mykey"]
. I guess that is not much better than your own suggestion.
I like PodTech.io's answer to achieve this without additional tools. For me, it did not run out of the box, so I had to slightly change it. I am not sure if the command wScript.Sleep 12000
(12 sec delay) in the original script is required or not, so I kept it.
Here's the modified script Zip.cmd
based on his answer, which works fine on my end:
@echo off
if "%1"=="" goto end
setlocal
set TEMPDIR=%TEMP%\ZIP
set FILETOZIP=%1
set OUTPUTZIP=%2.zip
if "%2"=="" set OUTPUTZIP=%1.zip
:: preparing VBS script
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo Set fso = WScript.CreateObject("Scripting.FileSystemObject") >> _zipIt.vbs
echo Set objZipFile = fso.CreateTextFile(ZipFile, True) >> _zipIt.vbs
echo objZipFile.Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo objZipFile.Close >> _zipIt.vbs
echo Set objShell = WScript.CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo Set objZip = objShell.NameSpace(fso.GetAbsolutePathName(ZipFile)) >> _zipIt.vbs
echo if not (objZip is nothing) then >> _zipIt.vbs
echo objZip.CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 12000 >> _zipIt.vbs
echo end if >> _zipIt.vbs
@ECHO Zipping, please wait...
mkdir %TEMPDIR%
xcopy /y /s %FILETOZIP% %TEMPDIR%
WScript _zipIt.vbs %TEMPDIR% %OUTPUTZIP%
del _zipIt.vbs
rmdir /s /q %TEMPDIR%
@ECHO ZIP Completed.
:end
Usage:
One parameter (no wildcards allowed here):
Zip FileToZip.txt
will create FileToZip.txt.zip
in the same folder containing the zipped file FileToZip.txt
.
Two parameters (optionally with wildcards for the first parameter), e.g.
Zip *.cmd Scripts
creates Scripts.zip
in the same folder containing all matching *.cmd
files.
Note: If you want to debug the VBS script, check out this hint, it describes how to activate the debugger to go through it step by step.
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
Instead of using HibernateUtil.java, to create sessionfactory object, you should use this:
SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Because in order to avoid the exception, you'll have to declare the class object in HibernateUtil.java file as configuration.addAnnotatedClass(Student_Info.class);
which looks dumb because we have provided the entry already in hibernate.cfg.xml file.
To use the AnnotationConfiguration class you'll have to add a jar to your project build path: http://www.java2s.com/Code/Jar/h/Downloadhibernate353jar.htm
The TypeScript team sorted this out in Visual Studio 2017 versions 15.3 and later, including the free Community edition.
How to See Which TypeScript Versions are Installed in Visual Studio
All you now need do is to go to project properties of any TypeScript Visual Studio project (right-click the project file in Solution Explorer/Properties), then go to the TypeScript Build tab on the left-hand side. This has a 'Typescript version' dropdown that shows you the version the project is using, and if you open it the dropdown shows you ALL versions of TypeScript currently installed in Visual Studio.
The actual installs are currently at C:\Program Files (x86)\Microsoft SDKs\TypeScript
and then subfolders by version number, at least on Win10 on my computer. If you want to see the exact version (e.g. 2.8.3 rather than just 2.8) you can find the appropriate tsc.exe
in here and look at its properties (Details tab in right-click/Properties in File Explorer).
How to Install Specific TypeScript Version
If you want to install a specific version of TypeScript for Visual Studio, you can download older versions from the Details->Releases section of the TypeScript SDK for Visual Studio 2017 Downloads page. You can verify that the version has been installed either with the 'Typescript version' dropdown in VS or inspecting the C:\Program Files (x86)\Microsoft SDKs\TypeScript
folder.
// if you need to check if all items' MyProperty doesn't have null
if (list.All(x => x.MyProperty != null))
// do something
// or if you need to check if at least one items' property has doesn't have null
if (list.Any(x => x.MyProperty != null))
// do something
But you always have to check for null
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
CSS style only for IE8:
.divLogRight{color:Blue; color:Red\9; *color:Blue;}
Only IE8 will be Red.
first Blue: for all browsers.
Red: IE6,7,8 Only
Second Blue: IE6,7 Only
So Red = for IE8 only.
For a very complete summary of browser hacks (including Internet Explorer (IE), Safari, Chrome, iPhone, and Opera) visit this link: http://paulirish.com/2009/browser-specific-css-hacks/
Float:left
... Although I presume you want the input to be styled not the div?
.button input{
color:#08233e;float:left;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
}
.button input:hover{
background-color:rgba(255,204,0,0.8);
}
you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine
<input type="file" name="file" />
Edit - based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:
import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return datetime.date(year, month, day)
In use:
>>> somedate = datetime.date.today()
>>> somedate
datetime.date(2010, 11, 9)
>>> add_months(somedate,1)
datetime.date(2010, 12, 9)
>>> add_months(somedate,23)
datetime.date(2012, 10, 9)
>>> otherdate = datetime.date(2010,10,31)
>>> add_months(otherdate,1)
datetime.date(2010, 11, 30)
Also, if you're not worried about hours, minutes and seconds you could use date
rather than datetime
. If you are worried about hours, minutes and seconds you need to modify my code to use datetime
and copy hours, minutes and seconds from the source to the result.
the window
contains everything, so you can call window.screen
and window.document
to get those elements. Check out this fiddle, pretty-printing the contents of each object: http://jsfiddle.net/JKirchartz/82rZu/
You can also see the contents of the object in firebug/dev tools like this:
console.dir(window);
console.dir(document);
console.dir(screen);
window
is the root of everything, screen
just has screen dimensions, and document
is top DOM object. so you can think of it as window
being like a super-document
...
This does what you want:
public static void main (String[] args) {
String a = "\\joe\\jill\\";
String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", "");
System.out.println(b);
}
The $
is used to remove the sequence in the end of string. The ^
is used to remove in the beggining.
As an alternative, you can use the syntax:
String b = a.replaceAll("\\\\$|^\\\\", "");
The |
means "or".
In case you want to trim other chars, just adapt the regex:
String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
If there is a possibility that the element does not exist in the XML I would test both that the element is present and that the string-length is greater than zero:
<xsl:choose>
<xsl:when test="categoryName and string-length(categoryName) > 0">
<xsl:value-of select="categoryName " />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="other" />
</xsl:otherwise>
</xsl:choose>
Here's a workaround that requires you to draw lines pixel by pixel, but will prevent anti aliasing.
// some helper functions
// finds the distance between points
function DBP(x1,y1,x2,y2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// finds the angle of (x,y) on a plane from the origin
function getAngle(x,y) { return Math.atan(y/(x==0?0.01:x))+(x<0?Math.PI:0); }
// the function
function drawLineNoAliasing(ctx, sx, sy, tx, ty) {
var dist = DBP(sx,sy,tx,ty); // length of line
var ang = getAngle(tx-sx,ty-sy); // angle of line
for(var i=0;i<dist;i++) {
// for each point along the line
ctx.fillRect(Math.round(sx + Math.cos(ang)*i), // round for perfect pixels
Math.round(sy + Math.sin(ang)*i), // thus no aliasing
1,1); // fill in one pixel, 1x1
}
}
Basically, you find the length of the line, and step by step traverse that line, rounding each position, and filling in a pixel.
Call it with
var context = cv.getContext("2d");
drawLineNoAliasing(context, 20,30,20,50); // line from (20,30) to (20,50)
Click on Start menu > Programs > Microsoft Sql Server > Configuration Tools
Select Sql Server Surface Area Configuration.
Now click on Surface Area configuration for services and connections
On the left pane of pop up window click on Remote Connections and Select Local and Remote connections radio button.
Select Using both TCP/IP and named pipes radio button.
click on apply and ok.
Now when try to connect to sql server using sql username and password u'll get the error mentioned below
Cannot connect to SQLEXPRESS.
ADDITIONAL INFORMATION:
Login failed for user 'username'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) ation To fix this error follow steps mentioned below
connect to sql server using window authentication.
Now right click on your server name at the top in left pane and select properties.
Click on security and select sql server and windows authentication mode radio button.
Click on OK.
restart sql server servive by right clicking on server name and select restart.
Now your problem should be fixed and u'll be able to connect using sql server username and password.
Have fun. Ateev Gupta
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
int main()
{
char d = 'd';
std::string y("Hello worl");
y += d;
y.push_back(d);
y.append(1, d); //appending the character 1 time
y.insert(y.end(), 1, d); //appending the character 1 time
y.resize(y.size()+1, d); //appending the character 1 time
y += std::string(1, d); //appending the character 1 time
}
Note that in all of these examples you could have used a character literal directly: y += 'd';
.
Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'};
didn't work, but char d[2] = { 'd'};
(note the array is size two) would have been worked roughly the same as const char* d = "d";
, and a string literal can be appended: y.append(d);
.
Today NodeJS supports new async/await
syntax. This is an easy syntax and makes the life much easier
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)
Learn more:
Kotlin:
var ver: String = packageManager.getPackageInfo(packageName, 0).versionName
This work for me:
<a href="#" onclick="sposta(100)">SPOSTA</a>
function sposta(id) {
$("#sposta").data("id",id).dialog({
autoOpen: true,
modal: true,
buttons: { "Sposta": function () { alert($(this).data('id')); } }
});
}
When you click on "Sposta" in dialog alert display 100
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
The ZERO WIDTH SPACE character is inserted when you use jQuery to add elements using DOM manipulation functions like .before() and .after()
I've run into this when adding hidden modal dialog frames at the end of my document and then finding that the ZERO WIDTH SPACE screws up the layout down there, adding unwanted space.
The quick fix was to insert it before the footer, not after it. Its hidden anyway.
I can't find anything in jQuery that does this:
https://github.com/jquery/jquery/blob/master/src/manipulation.js
So it might be the browser that adds it.
I don't know about others, but I was used to define a "global constant" (DEBUG
) and then a global function (debug(msg)
) that would print msg
only if DEBUG == True
.
Then I write my debug statements like:
debug('My value: %d' % value)
...then I pick up unit testing and never did this again! :)
Yes, but the syntax is different than what you have
SELECT
<fields>
FROM
<table1>
LEFT JOIN <table2>
ON <criteria for join>
AND <other criteria for join>
LEFT JOIN <table3>
ON <criteria for join>
AND <other criteria for join>
Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!
Run this in internet explorer 7 or 8 and you'll see.
jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!
There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function() {
// the following two blocks of HTML are identical except the P tag is outside the form in the first case
var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";
// <FORM> tag nested within <P>
RunTest("<FORM> tag nested within <P> tag", html1); // succeeds in Internet Explorer
RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1); // fails with added new line in Internet Explorer
// <P> tag nested within <HTML>
RunTest("<P> tag nested within <FORM> tag", html2); // succeeds in Internet Explorer
RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2); // succeeds in Internet Explorer even with \n
});
function RunTest(testName, html) {
// run with jQuery
$("#placeholder").html(html);
var jqueryDOM = $('#placeholder').html();
var jqueryFormSerialize = $("#placeholder form").serialize();
// run with innerHTML
$("#placeholder")[0].innerHTML = html;
var innerHTMLDOM = $('#placeholder').html();
var innerHTMLFormSerialize = $("#placeholder form").serialize();
var expectedSerializedValue = "field1=111&field2=222";
alert( 'TEST NAME: ' + testName + '\n\n' +
'The HTML :\n"' + html + '"\n\n' +
'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +
'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +
'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +
'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED")
);
}
</script>
</head>
<div id="placeholder">
This is #placeholder text will
</div>
</html>
You can use CSS linear-gradient()
with rgba()
.
div {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
background: linear-gradient(rgba(255,255,255,.5), rgba(255,255,255,.5)), url("https://i.imgur.com/xnh5x47.jpg");_x000D_
}_x000D_
span {_x000D_
background: black;_x000D_
color: white;_x000D_
}
_x000D_
<div><span>Hello world.</span></div>
_x000D_
Same issue on my Mac with a pre-packaged RCP client that was unzip only. The other answers pointed me to the eclipse.ini where all the paths looked valid, tried to check the working directory of my Eclipse bundle that doesn't see that easy to do. Seems when Finder starts an application it's working directory is / so that seems to be the issue.
Updated both references in my eclipse.ini to absolute paths and voila!
-startup
/Applications/RCPClient/client/eclipse/plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
/Applications/RCPClient/eclipse/plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.2.R36x_v20101019_1345
...
To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?
Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.
We are using Elasticsearch version 1.6 and I used this query from a co-worker to cover not null and not empty for a field:
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"bool": {
"must": [
{
"exists": {
"field": "myfieldName"
}
},
{
"not": {
"filter": {
"term": {
"myfieldName": ""
}
}
}
}
]
}
}
}
}
}
You can alter the "Right margin" attribute in the preferences, which can be found via
File | Settings | Project Settings | Code Style - General
Right Margin (columns) In this text box, specify the number of columns to be used to display pages in the editor.
Source: Jetbrains
<?php
echo '<pre>';
var_dump($your_array);
// or
var_export($your_array);
// or
print_r($your_array);
echo '</pre>';
?>
Or Use external libraries like REF: https://github.com/digitalnature/php-ref
NOTE if you are using python 3.x:
request.FILES
is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type="file") is "myfile" so "myfile" will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile']
you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:
list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
filename = f.name
list.append(filename)
of course one can squeeze the whole thing in one line, but this is easy to understand
I working well with it
<script>
$(function () {
$("#catalog tbody tr").draggable({
appendTo:"body",
helper:"clone"
});
$("#cart tbody").droppable({
activeClass:"ui-state-default",
hoverClass:"ui-state-hover",
accept:":not(.ui-sortable-helper)",
drop:function (event, ui) {
$('.placeholder').remove();
row = ui.draggable;
$(this).append(row);
}
});
});
</script>
try this one:
<table style="border:1px solid">
<tr>
<td style="min-width:50px">one</td>
<td style="min-width:100px">two</td>
</tr>
</table>
_x000D_
None of the above answers fixed my issue.
The above answers are probably more likely the cause of your problem but my issue was that I was using the wrong bucket name. It was a valid bucket name, it just wasn't my bucket.
The bucket I was pointing to was in a different region that my lambda function so check your bucket name!
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
Building upon the already compact solution from @Dan, here's a self-contained function version of it. Variable names are reduced to single letters for those who just want it to be as compact as possible at the expense of context.
const ns = {};
ns.sizeof = function(v) {
let f = ns.sizeof, //this needs to match the name of the function itself, since arguments.callee.name is defunct
o = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": i => 2 * i.length,
"object": i => !i ? 0 : Object
.keys(i)
.reduce((t, k) => f(k) + f(i[k]) + t, 0)
};
return o[typeof v](v);
};
ns.undef;
ns.bool = true;
ns.num = 1;
ns.string = "Hello";
ns.obj = {
first_name: 'Brendan',
last_name: 'Eich',
born: new Date(1961, 6, 4),
contributions: ['Netscape', 'JavaScript', 'Brave', 'BAT'],
politically_safe: false
};
console.log(ns.sizeof(ns.undef));
console.log(ns.sizeof(ns.bool));
console.log(ns.sizeof(ns.num));
console.log(ns.sizeof(ns.string));
console.log(ns.sizeof(ns.obj));
console.log(ns.sizeof(ns.obj.contributions));
_x000D_
This can be done using the unique function in ufp.path module.
import ufp.path
ufp.path.unique('./test.ext')
if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.
simple version:
just give out the reject function.
function Sleep(ms,cancel_holder) {
return new Promise(function(resolve,reject){
var done=false;
var t=setTimeout(function(){if(done)return;done=true;resolve();}, ms);
cancel_holder.cancel=function(){if(done)return;done=true;if(t)clearTimeout(t);reject();}
})
}
a wraper solution (factory)
the solution I found is to pass a cancel_holder object. it will have a cancel function. if it has a cancel function then it is cancelable.
This cancel function rejects the promise with Error('canceled').
Before resolve, reject, or on_cancel prevent the cancel function to be called without reason.
I have found convenient to pass the cancel action by injection
function cancelablePromise(cancel_holder,promise_fn,optional_external_cancel) {
if(!cancel_holder)cancel_holder={};
return new Promise( function(resolve,reject) {
var canceled=false;
var resolve2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; resolve.apply(this,arguments);}
var reject2=function(){ if(canceled) return; canceled=true; delete cancel_holder.cancel; reject.apply(this,arguments);}
var on_cancel={}
cancel_holder.cancel=function(){
if(canceled) return; canceled=true;
delete cancel_holder.cancel;
cancel_holder.canceled=true;
if(on_cancel.cancel)on_cancel.cancel();
if(optional_external_cancel)optional_external_cancel();
reject(new Error('canceled'));
};
return promise_fn.call(this,resolve2,reject2,on_cancel);
});
}
function Sleep(ms,cancel_holder) {
return cancelablePromise(cancel_holder,function(resolve,reject,oncacnel){
var t=setTimeout(resolve, ms);
oncacnel.cancel=function(){if(t)clearTimeout(t);}
})
}
let cancel_holder={};
// meanwhile in another place it can be canceled
setTimeout(function(){ if(cancel_holder.cancel)cancel_holder.cancel(); },500)
Sleep(1000,cancel_holder).then(function() {
console.log('sleept well');
}, function(e) {
if(e.message!=='canceled') throw e;
console.log('sleep interrupted')
})
You may check if you are sending clearText through HTTP
Fix : https://medium.com/@son.rommer/fix-cleartext-traffic-error-in-android-9-pie-2f4e9e2235e6
OR
In the Case of Apache HTTP client deprecation (From Google ) :
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default.
To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:
Source https://developer.android.com/about/versions/pie/android-9.0-changes-28
<?php
require_once '../config/config.php';
require_once '../classes/class.College.php';
$Response = array();
$Parms = $_POST;
$Parms['Id'] = Id;
$Parms['function'] = 'DeleteCollege';
switch ($Parms['function']) {
case 'InsertCollege': {
$Response = College::InsertCollege($Parms);
break;
}
case 'GetCollegeById': {
$Response = College::GetCollegeById($Parms['Id']);
break;
}
case 'GetAllCollege': {
$Response = College::GetAllCollege();
break;
}
case 'UpdateCollege': {
$Response = College::UpdateCollege($Parms);
break;
}
case 'DeleteCollege': {
College::DeleteCollege($Parms['Id']);
$Response = array('status' => 'R');
break;
}
}
echo json_encode($Response);
?>
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings xdt:Transform="Replace">
<!-- production environment config --->
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
Information for this answer are brought from this answer and this blog post.
notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).
Simply use this:
this.Invoke((MethodInvoker)delegate
{
YourControl.Property= value; // runs thread safe
});
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Use this :
Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());
Month name will contain the full month name,,if you want short month name use this
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
String month_name = month_date.format(cal.getTime());
A bit safer version than using xargs, also not recursive:
ls -p | grep -v '/$' | grep '\.pdf$' | while read file; do rm "$file"; done
Filtering our directories here is a bit unnecessary as 'rm' won't delete it anyway, and it can be removed for simplicity, but why run something that will definitely return error?
It means that the delegate you pass is executed on the thread that created the Control object (which is the UI thread).
You need to call this method when your application is multi-threaded and you want do some UI operation from a thread other than the UI thread, because if you just try to call a method on a Control from a different thread you'll get a System.InvalidOperationException.
You could utilize a regular expression test and the toUpperCase
method:
String.prototype.charAtIsUpper = function (atpos){
var chr = this.charAt(atpos);
return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
};
// usage (note: character position is zero based)
'hi There'.charAtIsUpper(3); //=> true
'BLUE CURAÇAO'.charAtIsUpper(9); //=> true
'Hello, World!'.charAtIsUpper(5); //=> false
I think that the code you are looking for is:
Array.Copy(oldArray, 0, newArray, BeginIndex, EndIndex - BeginIndex)
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
None of these solutions worked for me. But I was able to get vertical centering by using <div class="form-row align-items-center">
for each form row, per the Bootstrap examples.
SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM membership_dates md
output::
id entity_id start_date end_date days
1 1236 2018-01-16 00:00:00 2018-08-31 00:00:00 227
2 2876 2015-06-26 00:00:00 2019-06-30 00:00:00 1465
3 3880 1990-06-05 00:00:00 2018-07-04 00:00:00 10256
4 3882 1993-07-05 00:00:00 2018-07-04 00:00:00 9130
hope it helps someone in future
getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for
{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"
but you need to get into the array and then do a search for "characters"
try this
String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
ArrayList<String> temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters");
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
checked it :)
If you're on C# 7, you should consider using value tuples as your composite key. Value tuples typically offer better performance than the traditional reference tuples (Tuple<T1, …>
) since value tuples are value types (structs), not reference types, so they avoid the memory allocation and garbage collection costs. Also, they offer conciser and more intuitive syntax, allowing for their fields to be named if you so wish. They also implement the IEquatable<T>
interface needed for the dictionary.
var dict = new Dictionary<(int PersonId, int LocationId, int SubjectId), string>();
dict.Add((3, 6, 9), "ABC");
dict.Add((PersonId: 4, LocationId: 9, SubjectId: 10), "XYZ");
var personIds = dict.Keys.Select(k => k.PersonId).Distinct().ToList();
Had this issue today on iOS 8 & 9 and it seems that we now need to add height: 100%;
So add
html,
body {
position: relative;
height: 100%;
overflow: hidden;
}
componentWillReceiveProps(nextProps) { // your code here}
I think that is the event you need. componentWillReceiveProps
triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.
Try this:
mongod --fork --logpath /var/log/mongodb.log
You may need to create the db-folder:
mkdir -p /data/db
If you get any 'Permission denied'-error, I'ld recommend changing the permissions of the particular files instead of running mongod as root.
Amazing to see the old "C/C++ must be faster than Java because Java is interpreted" myth is still alive and kicking. There are articles going back a few years, as well as more recent ones, that explain with concepts or measurements why this simply isn't always the case.
Current virtual machine implementations (and not just the JVM, by the way) can take advantage of information gathered during program execution to dynamically tune the code as it runs, using a variety of techniques:
and a variety of other adjustments based on knowing what the code is actually doing, and on the actual characteristics of the environment in which it's running.
Just Change the Connection mysql string to 127.0.0.1 and it will work
If you use JSON properly, you can have nested object without any issue :
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));
I find it useful.
var imgData = 'data:image/jpeg;base64,verylongbase64;'
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(35, 25, "Octonyan loves jsPDF");
doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
Also, if you don't know part of code where error occured, you can profile "bad" sql execution using sql profiler integrated to mssql.
Bad datetime param will displayed something like that :
Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT()
function returns a string, not a date. When you wrote
(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date
I think you were essentially asking MySQL to try to format the values in date_purchased
according to that format string, and instead of calling that column date_purchased
, call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format()
returns a string, not a date.)
I don't think that's what you wanted to do, but that's what you were doing.
Don't confuse how a value looks with what the value is.
Here it is: http://jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
html
<input id="myinputfield" value="This is some text" type="button">?
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});?
Moving tables:
First run:
SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';
-- Or suggested in the comments (did not test it myself)
SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; '
FROM dba_tables
WHERE OWNER = '<SCHEMA>'
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>
Where <schema_name>
is the name of the user.
And <tablespace_name>
is the destination tablespace.
As a result you get lines like:
ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Moving indexes:
First run:
SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;'
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';
The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.
As a result you should get something like:
ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Last but not least, moving LOBs:
First run:
SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';
This moves the LOB objects to the other tablespace.
As a result you should get something like:
ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);
Paste the results in a script or in a oracle sql developer like application and run it.
O and there is one more thing:
For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.
I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);
From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
The command Edit.ParameterInfo
(mapped to Ctrl+Shift+Space by default) will show the overload tooltip if it's invoked when the cursor is inside the parameter brackets of a method call.
The command Edit.QuickInfo
(mapped to Ctrl+KCtrl+I by default) will show the tooltip that you'd see if you moused over the cursor location.
You can see this example.
// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );
detectPartial :
visible
is boolean variable which indicates if the element is visible or not.
It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.
For example:
$("#theButton").button().click( function(event) {
$.post( url, data )
.always( function( response ) {
window.open( newurl + response, '_blank' );
} );
} );
will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:
$("#theButton").button().click( function(event) {
var newtab = window.open( '', '_blank' );
$.post( url, data )
.always( function( response ) {
newtab.location = newurl + response;
} );
} );
we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.
One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.
That is, a double[][]
can validly be:
double[][] x = new double[5][];
x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];
Because each entry in the array is a reference to an array of double
. With a jagged array, you can do an assignment to an array like you want in your second example:
x[0] = new double[13];
On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double
:
double[,] ServicePoint = new double[10,9];
ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.
UPDATE:
To clarify based on your question, the reason your #1 had a syntax error is because you had this:
double[][] ServicePoint = new double[10][9];
And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:
double[][] ServicePoint = new double[10][];
Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):
ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];
Hope that helps!
There is this plugin on github that load content into an element. Here is the repo
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Sometimes a client wants two y scales. Giving them the "flawed" speech is often pointless. But I do like the ggplot2 insistence on doing things the right way. I am sure that ggplot is in fact educating the average user about proper visualization techniques.
Maybe you can use faceting and scale free to compare the two data series? - e.g. look here: https://github.com/hadley/ggplot2/wiki/Align-two-plots-on-a-page
Just use Python's standard string formatting methods:
>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'
If you are using a Python version under 2.6, use
>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'
Swift 3 & 4/5
self.navigationController!.viewControllers.removeAll()
self.navigationController?.viewControllers.remove(at: "insert here a number")
Swift 2.1
remove all:
self.navigationController!.viewControllers.removeAll()
remove at index
self.navigationController?.viewControllers.removeAtIndex("insert here a number")
There a bunch of more possible actions like removeFirst,range etc.
for the people who are facing below error in mysql 5.7+ version -
Access denied for user 'root'@'localhost' (using password: YES)
Open new terminal
sudo /etc/init.d/mysql stop
...
MySQL Community Server 5.7.8-rc is stopped
sudo mysqld_safe --skip-grant-tables &
this will skipp all grant level privileges and start the mysql in safe mode
Sometimes the process got stucked just because of
grep: write error: Broken pipe 180102 11:32:28 mysqld_safe Logging to '/var/log/mysql/error.log'.
Simply press Ctrl+Z or Ctrl+C to interrupt and exit process
mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
use mysql;
Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A
Database changed
mysql> update user set authentication_string=password('password') where user='root';
Query OK, 4 rows affected, 1 warning (0.03 sec)
Rows matched: 4 Changed: 4 Warnings: 1
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye
sudo /etc/init.d/mysql stop
..180102 11:37:12 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended . * MySQL Community Server 5.7.8-rc is stopped arif@ubuntu:~$ sudo /etc/init.d/mysql start .. * MySQL Community Server 5.7.8-rc is started
mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)
after mysql 5.7+ version the column password replaced by name authentication_string from the mysql.user table.
hope these steps will help anyone, thanks.
I need to do 2 things to connect with instance name
1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)
Restart sql and done
.NET Framework and .NET Core are both frameworks.
.NET Standard is a standard (in other words, a specification).
You can make an executable project (like a console application, or ASP.NET application) with .NET Framework and .NET Core, but not with .NET Standard.
With .NET Standard you can make only a class library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.
Command to put list of all files and folders into a text file is as below:
Eg: dir /b /s | sort > ListOfFilesFolders.txt
import datetime
import calendar
day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])
08 05 2015
Friday
I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:
while (i.hasNext()) {
// code goes here
}
I did one iteration at the start, and then checked for condition using:
do {
// code goes here
} while (i.hasNext());
I hope this will help some people at some stage.
Try:
$("#"+styleTarget).css({ 'font-size': $(this).val() });
By putting the value in quotes, it becomes a string, and "+$(this).val()+"px
is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:
Using a map:
$("#elem").css({
fontSize: 20
});
Using key and value parameters:
All of these are valid.
$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");
You can replace "fontSize"
with "font-size"
but it will have to be quoted then.
I own a mac too! here is the code that will work:
myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works
before doing anything or adding any components set the look and feel so it looks better:
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Min-value will always start at zero and its nothing you can do about it. But you can change its value when user start scrolling it around.
Here I set the max-value as 64. This calculations are simple: I want the user to pick a time from 15min to 16 hours, and he picks one of every 15min to 16 hours, clear? I know, very simple :)
SeekBar seekBar = (SeekBar) dialog.findViewById(R.id.seekBar);
seekBar.setMax(64);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
float b;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float des = (float) progress / 4;
b = des;
hours.setText(des + " hours");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
hoursSelected = b;
}
});
On comparison with session variables, static variables will have same value for all users considering i am using an application that is deployed in server. If two users accessing the same page of an application then the static variable will hold the latest value and the same value will be supplied to both the users unlike session variables that is different for each user. So, if you want something common and same for all users including the values that are supposed to be used along the application code then only use static.
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src
).
New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies
section of your package.json. Anytime you use something from scripts
in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.
For example:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
Then in package.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
Then at your command prompt you can run:
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
So actually my npm install executes npm install again .. which is weird but seems to work.
Note: you might have issues if you are using the most common setup for npm
where global Node package installs required sudo
. One option is to change your npm
configuration so this isn't necessary:
npm config set prefix ~/npm
, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH
to your ~/.bashrc
.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
This must definitely work.. have a try
How about
SELECT id, COUNT(IF status=42 THEN 1 ENDIF) AS cnt
FROM table
GROUP BY table
Shorter than CASE
:)
Works because COUNT()
doesn't count null values, and IF
/CASE
return null when condition is not met and there is no ELSE
.
I think it's better than using SUM()
.
$("#select_id").find("option:selected").text();
It is helpful if your control is on Server side. In .NET it looks like:
$('#<%= dropdownID.ClientID %>').find("option:selected").text();
letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
...
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
Your example shows "instance variables", not really class variables.
Look in hi_obj.__class__.__dict__.items()
for the class variables, along with other other class members like member functions and the containing module.
class Hi( object ):
class_var = ( 23, 'skidoo' ) # class variable
def __init__( self ):
self.ii = "foo" # instance variable
self.jj = "bar"
Class variables are shared by all instances of the class.
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
plt.gca().add_patch(circle1)
A quick condensed version of the accepted answer, to quickly plug a circle into an existing plot. Refer to the accepted answer and other answers to understand the details.
By the way:
gca()
means Get Current Axisvery strange, but in my case, i switch wifi connection...
I use some public wifi and switch to my phone connection
you can try this in the stylesheet:
@page{size:auto; margin-bottom:5mm;}
But this also removes the page number
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
Slightly modified code for Swift 3.0
let calendar = NSCalendar.current as NSCalendar
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: startDateTime)
let date2 = calendar.startOfDay(for: endDateTime)
let flags = NSCalendar.Unit.day
let components = calendar.components(flags, from: date1, to: date2, options: [])
return components.day!
(26.10.2020)
This is in my opinion much cleaner and simpler than the correct answer. This one also includes how to add the csrftoken and using login_required methods with ajax.
@login_required
def some_view(request):
"""Returns a json response to an ajax call. (request.user is available in view)"""
# Fetch the attributes from the request body
data_attribute = request.GET.get('some_attribute') # Make sure to use POST/GET correctly
# DO SOMETHING...
return JsonResponse(data={}, status=200)
urlpatterns = [
path('some-view-does-something/', views.some_view, name='doing-something'),
]
The ajax call is quite simple, but is sufficient for most cases. You can fetch some values and put them in the data object, then in the view depicted above you can fetch their values again via their names.
You can find the csrftoken function in django's documentation. Basically just copy it and make sure it is rendered before your ajax call so that the csrftoken variable is defined.
$.ajax({
url: "{% url 'doing-something' %}",
headers: {'X-CSRFToken': csrftoken},
data: {'some_attribute': some_value},
type: "GET",
dataType: 'json',
success: function (data) {
if (data) {
console.log(data);
// call function to do something with data
process_data_function(data);
}
}
});
This might be a bit off topic but I have rarely seen this used and it is a great way to minimize window relocations as well as manual html string creation in javascript.
This is very similar to the one above but this time we are rendering html from the response without reloading the current window.
If you intended to render some kind of html from the data you would receive as a response to the ajax call, it might be easier to send a HttpResponse back from the view instead of a JsonResponse. That allows you to create html easily which can then be inserted into an element.
# The login required part is of course optional
@login_required
def create_some_html(request):
"""In this particular example we are filtering some model by a constraint sent in by
ajax and creating html to send back for those models who match the search"""
# Fetch the attributes from the request body (sent in ajax data)
search_input = request.GET.get('search_input')
# Get some data that we want to render to the template
if search_input:
data = MyModel.objects.filter(name__contains=search_input) # Example
else:
data = []
# Creating an html string using template and some data
html_response = render_to_string('path/to/creation_template.html', context = {'models': data})
return HttpResponse(html_response, status=200)
creation_template.html
{% for model in models %}
<li class="xyz">{{ model.name }}</li>
{% endfor %}
urlpatterns = [
path('get-html/', views.create_some_html, name='get-html'),
]
This is the template where we want to add the data to. In this example in particular we have a search input and a button that sends the search input's value to the view. The view then sends a HttpResponse back displaying data matching the search that we can render inside an element.
{% extends 'base.html' %}
{% load static %}
{% block content %}
<input id="search-input" placeholder="Type something..." value="">
<button id="add-html-button" class="btn btn-primary">Add Html</button>
<ul id="add-html-here">
<!-- This is where we want to render new html -->
</ul>
{% end block %}
{% block extra_js %}
<script>
// When button is pressed fetch inner html of ul
$("#add-html-button").on('click', function (e){
e.preventDefault();
let search_input = $('#search-input').val();
let target_element = $('#add-html-here');
$.ajax({
url: "{% url 'get-html' %}",
headers: {'X-CSRFToken': csrftoken},
data: {'search_input': search_input},
type: "GET",
dataType: 'html',
success: function (data) {
if (data) {
console.log(data);
// Add the http response to element
target_element.html(data);
}
}
});
})
</script>
{% endblock %}
Python 3 handles strings a bit different. Originally there was just one type for
strings: str
. When unicode gained traction in the '90s the new unicode
type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as str
but with multibyte support.
In Python 3 there are two different types:
bytes
type. This is just a sequence of bytes, Python doesn't know
anything about how to interpret this as characters.str
type. This is also a sequence of bytes, but Python knows how to
interpret those bytes as characters.unicode
type was dropped. str
now supports unicode.In Python 2 implicitly assuming an encoding could cause a lot of problems; you
could end up using the wrong encoding, or the data may not have an encoding at
all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to
guess) is often a lot better and much more in line with the "Python philosophy"
of "explicit is better than implicit".
This change is incompatible with Python 2 as many return values have changed,
leading to subtle problems like this one; it's probably the main reason why
Python 3 adoption has been so slow. Since Python doesn't have static typing2
it's impossible to change this automatically with a script (such as the bundled
2to3
).
str
to bytes
with bytes('h€llo', 'utf-8')
; this should
produce b'H\xe2\x82\xacllo'
. Note how one character was converted to three
bytes.bytes
to str
with b'H\xe2\x82\xacllo'.decode('utf-8')
.Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.
In your specific piece of code, nextline
is of type bytes
, not str
,
reading stdout
and stdin
from subprocess
changed in Python 3 from str
to
bytes
. This is because Python can't be sure which encoding this uses. It
probably uses the same as sys.stdin.encoding
(the encoding of your system),
but it can't be sure.
You need to replace:
sys.stdout.write(nextline)
with:
sys.stdout.write(nextline.decode('utf-8'))
or maybe:
sys.stdout.write(nextline.decode(sys.stdout.encoding))
You will also need to modify if nextline == ''
to if nextline == b''
since:
>>> '' == b''
False
Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.
1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A'
) and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')
). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.
2 Yes, you can use function annotations, but it's a comparatively new feature and little used.
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
The vshost.exe feature was introduced with Visual Studio 2005 (to answer your comment).
The purpose of it is mostly to make debugging launch quicker - basically there's already a process with the framework running, just ready to load your application as soon as you want it to.
See this MSDN article and this blog post for more information.
I was getting the same error of fsocket() and I just updated my hosts files
hope it will solve your problem
for any further query please ping me at http://kingologic.com
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.
var generatedIdCounter = 0;
$.fn.id = function() {
var identifier = this.attr('id');
if(!identifier) {
generatedIdCounter++;
identifier = 'isGenerated_' + generatedIdCounter;
this.attr('id', identifier);
}
return identifier;
}
How to use:
$('.classname').id();
$('#elementId').id();
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
try this code to create Scale animation without using xml
ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
Try this "one-liner" from Delta's Blog, String To MemoryStream (C#).
MemoryStream stringInMemoryStream =
new MemoryStream(ASCIIEncoding.Default.GetBytes("Your string here"));
The string will be loaded into the MemoryStream
, and you can read from it. See Encoding.GetBytes(...), which has also been implemented for a few other encodings.
The problem is that .gitignore
ignores just files that weren't tracked before (by git add
). Run git reset name_of_file
to unstage the file and keep it. In case you want to also remove the given file from the repository (after pushing), use git rm --cached name_of_file
.
I've used regex a number of times, but I always have to relearn it each time, which is frustrating :-)
So Here's a non-regex solution:
function csvRowToArray(row, delimiter = ',', quoteChar = '"'){
let nStart = 0, nEnd = 0, a=[], nRowLen=row.length, bQuotedValue;
while (nStart <= nRowLen) {
bQuotedValue = (row.charAt(nStart) === quoteChar);
if (bQuotedValue) {
nStart++;
nEnd = row.indexOf(quoteChar + delimiter, nStart)
} else {
nEnd = row.indexOf(delimiter, nStart)
}
if (nEnd < 0) nEnd = nRowLen;
a.push(row.substring(nStart,nEnd));
nStart = nEnd + delimiter.length + (bQuotedValue ? 1 : 0)
}
return a;
}
How it works:
row
.nEnd
to the closing quote.nEnd
to the next delimiter.nStart
to nEnd
plus the length of the delimeter.Sometimes it's good to write your own small function, rather than use a library. Your own code is going to perform well and use only a small footprint. In addition, you can easily tweak it to suit your own needs.
There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li
siblings in an array, and on click, check the indexOf
the clicked element in that array.
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
li.addEventListener('click', () => {_x000D_
const index = lis.indexOf(li);_x000D_
console.log(index);_x000D_
});_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, with event delegation:
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li> which is a child of wizard:_x000D_
if (!target.matches('#wizard > li')) return;_x000D_
_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of li
s on every click, rather than beforehand:
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li>_x000D_
if (!target.matches('li')) return;_x000D_
_x000D_
const lis = [...wizard.children];_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
inplace=True
makes the function impure. It changes the original dataframe and returns None. In that case, You breaks the DSL chain.
Because most of dataframe functions return a new dataframe, you can use the DSL conveniently. Like
df.sort_values().rename().to_csv()
Function call with inplace=True
returns None and DSL chain is broken. For example
df.sort_values(inplace=True).rename().to_csv()
will throw NoneType object has no attribute 'rename'
Something similar with python’s build-in sort and sorted. lst.sort()
returns None
and sorted(lst)
returns a new list.
Generally, do not use inplace=True
unless you have specific reason of doing so. When you have to write reassignment code like df = df.sort_values()
, try attaching the function call in the DSL chain, e.g.
df = pd.read_csv().sort_values()...
As per comment "That is not pushing to an array. It is merely assigning to it"
If you looking for the best practice to assign value to array then its only way that you can assign value.
Array[index]= value;
there is only way to assign value when you do not want to use List
.
Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.
<a href="Controller/ActionMethod">
<input type="button" value="Click Me" />
</a>
Adding parameters:
<a href="Controller/ActionMethod?userName=ted">
<input type="button" value="Click Me" />
</a>
Adding parameters from a non-enumerated Model:
<a href="Controller/[email protected]">
<input type="button" value="Click Me" />
</a>
You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
There is an extended stored procedure sp_spaceused
that gets this information out. It's fairly convoluted to do it from the data dictionary, but This link fans out to a script that does it. This stackoverflow question has some fan-out to information on the underlying data structures that you can use to construct estimates of table and index sizes for capcity planning.
This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w
does not remove.
function toLowerCamelCase(str) {
return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
if (+match === 0 || match === '-' || match === '.' ) {
return ""; // or if (/\s+/.test(match)) for white spaces
}
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e
One suggestion is that use a pdf library like PDFJS.
Yo have to append, the following "data:application/pdf;base64"
+ your pdf String, and set the src of your element to that.
Try with this example:
var pdfsrc = "data:application/pdf;base64" + "67987yiujkhkyktgiyuyhjhgkhgyi...n"
<pdf-element id="pdfOpen" elevation="5" downloadable src="pdfsrc" ></pdf-element>
Hope it helps :)
Use .col instead of col-lg-3 :
<div class="row">
<div class="col">
Fixed content
</div>
<div class="col-lg-9">
Normal scrollable content
</div>
</div>
This is going to depend on your application but in general the fastest way to transpose a matrix would be to invert your coordinates when you do a look up, then you do not have to actually move any data.
Here is my solution. Use [ExportModelStateToTempData] / [ImportModelStateFromTempData] is uncomfortable in my opinion.
~/Views/Home/Error.cshtml:
@{
ViewBag.Title = "Error";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Error</h2>
<hr/>
<div style="min-height: 400px;">
@Html.ValidationMessage("Error")
<br />
<br />
<button onclick="Error_goBack()" class="k-button">Go Back</button>
<script>
function Error_goBack() {
window.history.back()
}
</script>
</div>
~/Controllers/HomeController.sc:
public class HomeController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Error()
{
return this.View();
}
...
}
~/Controllers/BaseController.sc:
public class BaseController : Controller
{
public BaseController() { }
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
if (filterContext.Controller.TempData.ContainsKey("Error"))
{
var modelState = filterContext.Controller.TempData["Error"] as ModelState;
filterContext.Controller.ViewData.ModelState.Merge(new ModelStateDictionary() { new KeyValuePair<string, ModelState>("Error", modelState) });
filterContext.Controller.TempData.Remove("Error");
}
}
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
if (filterContext.Controller.ViewData.ModelState.ContainsKey("Error"))
{
filterContext.Controller.TempData["Error"] = filterContext.Controller.ViewData.ModelState["Error"];
}
}
base.OnActionExecuted(filterContext);
}
}
~/Controllers/MyController.sc:
public class MyController : BaseController
{
public ActionResult Index()
{
return View();
}
public ActionResult Details(int id)
{
if (id != 5)
{
ModelState.AddModelError("Error", "Specified row does not exist.");
return RedirectToAction("Error", "Home");
}
else
{
return View("Specified row exists.");
}
}
}
I wish you successful projects ;-)
To keep this simple, I just changed the directory from which I was importing the data to a local folder on the server.
I had the file located on a shared folder, I just copied my files to "c:\TEMP\Reports" on my server (updated the query to BULK INSERT from the new folder). The Agent task completed successfully :)
Finally after a long time I'm able to BULK Insert automatically via agent job.
Best regards.
Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".
Google indeed ignores most punctuation, with the following exceptions:
As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.
Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.
For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
You can just iterate over the elements in the array and call array[i].trim()
on each element
Using aggregate function like below :
[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]
it will give you result like following :
{
"total" : 1,
"book" : "book33",
"address" : "address90"
},
{
"total" : 1,
"book" : "book5",
"address" : "address1"
},
{
"total" : 1,
"book" : "book99",
"address" : "address9"
},
{
"total" : 1,
"book" : "book1",
"address" : "address5"
},
{
"total" : 1,
"book" : "book5",
"address" : "address2"
},
{
"total" : 1,
"book" : "book3",
"address" : "address4"
},
{
"total" : 1,
"book" : "book11",
"address" : "address77"
},
{
"total" : 1,
"book" : "book9",
"address" : "address3"
},
{
"total" : 1,
"book" : "book1",
"address" : "address15"
},
{
"total" : 2,
"book" : "book1",
"address" : "address2"
},
{
"total" : 3,
"book" : "book1",
"address" : "address1"
}
I didn't quite get your expected result format, so feel free to modify this to one you need.
An enumerated type is basically a data type that lets you describe each member of a type in a more readable and reliable way.
Here is a simple example to explain why:
Assuming you are writing a method that has something to do with seasons:
First, you declared some int static constants to represent each season.
public static final int SPRING = 0;
public static final int SUMMER = 1;
public static final int FALL = 2;
public static final int WINTER = 2;
Then, you declared a method to print name of the season into the console.
public void printSeason(int seasonCode) {
String name = "";
if (seasonCode == SPRING) {
name = "Spring";
}
else if (seasonCode == SUMMER) {
name = "Summer";
}
else if (seasonCode == FALL) {
name = "Fall";
}
else if (seasonCode == WINTER) {
name = "Winter";
}
System.out.println("It is " + name + " now!");
}
So, after that, you can print a season name like this.
printSeason(SPRING);
printSeason(WINTER);
This is a pretty common (but bad) way to do different things for different types of members in a class. However, since these code involves integers, so you can also call the method like this without any problems.
printSeason(0);
printSeason(1);
or even like this
printSeason(x - y);
printSeason(10000);
The compiler will not complain because these method calls are valid, and your printSeason
method can still work.
But something is not right here. What does a season code of 10000
supposed to mean? What if x - y
results in a negative number? When your method receives an input that has no meaning and is not supposed to be there, your program knows nothing about it.
You can fix this problem, for example, by adding an additional check.
...
else if (seasonCode == WINTER) {
name = "Winter";
}
else {
throw new IllegalArgumentException();
}
System.out.println(name);
Now the program will throw a RunTimeException
when the season code is invalid. However, you still need to decide how you are going to handle the exception.
By the way, I am sure you noticed the code of FALL
and WINTER
are both 2, right?
You should get the idea now. This pattern is brittle. It makes you write condition checks everywhere. If you're making a game, and you want to add an extra season into your imaginary world, this pattern will make you go though all the methods that do things by season, and in most case you will forget some of them.
You might think class inheritance is a good idea for this case. But we just need some of them and no more.
That's when enum
comes into play.
enum
typeIn Java, enum
types are classes that export one instance for each enumeration constant via a public static final field.
Here you can declare four enumeration constants: SPRING, SUMMER, FALL, WINTER
. Each has its own name
.
public enum Season {
SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter");
private String name;
Season(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Now, back to the method.
public void printSeason(Season season) {
System.out.println("It is " + season.getName() + " now!");
}
Instead of using int
, you can now use Season
as input. Instead of a condition check, you can tell Season
to give you its name.
This is how you use this method now:
printSeason(Season.SPRING);
printSeason(Season.WINTER);
printSeason(Season.WHATEVER); <-- compile error
You will get a compile-time error when you use an incorrect input, and you're guaranteed to get a non-null singleton reference of Season
as long as the program compiles.
When we need an additional season, we simply add another constant in Season
and no more.
public enum Season {
SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter"),
MYSEASON("My Season");
...
Whenever you need a fixed set of constants, enum
can be a good choice (but not always). It's a more readable, more reliable and more powerful solution.
When a
and b
are 1-dimensional sequences, numpy.cov(a,b)[0][1]
is equivalent to your cov(a,b)
.
The 2x2 array returned by np.cov(a,b)
has elements equal to
cov(a,a) cov(a,b)
cov(a,b) cov(b,b)
(where, again, cov
is the function you defined above.)
You can use NSURLConnection as follows:
Set your NSURLRequest
: Use requestWithURL:(NSURL *)theURL
to initialise the request.
If you need to specify a POST request and/or HTTP headers, use NSMutableURLRequest
with
(void)setHTTPMethod:(NSString *)method
(void)setHTTPBody:(NSData *)data
(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
Send your request in 2 ways using NSURLConnection
:
Synchronously: (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
This returns a NSData
variable that you can process.
IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI.
Asynchronously: (void)start
Don't forget to set your NSURLConnection's delegate to handle the connection as follows:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.data setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
[self.data appendData:d];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] autorelease] show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
// Do anything you want with it
[responseText release];
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSString *username = @"username";
NSString *password = @"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
Just for reference which functional interface can be used for method reference in cases method throws and/or returns a value.
void notReturnsNotThrows() {};
void notReturnsThrows() throws Exception {}
String returnsNotThrows() { return ""; }
String returnsThrows() throws Exception { return ""; }
{
Runnable r1 = this::notReturnsNotThrows; //ok
Runnable r2 = this::notReturnsThrows; //error
Runnable r3 = this::returnsNotThrows; //ok
Runnable r4 = this::returnsThrows; //error
Callable c1 = this::notReturnsNotThrows; //error
Callable c2 = this::notReturnsThrows; //error
Callable c3 = this::returnsNotThrows; //ok
Callable c4 = this::returnsThrows; //ok
}
interface VoidCallableExtendsCallable extends Callable<Void> {
@Override
Void call() throws Exception;
}
interface VoidCallable {
void call() throws Exception;
}
{
VoidCallableExtendsCallable vcec1 = this::notReturnsNotThrows; //error
VoidCallableExtendsCallable vcec2 = this::notReturnsThrows; //error
VoidCallableExtendsCallable vcec3 = this::returnsNotThrows; //error
VoidCallableExtendsCallable vcec4 = this::returnsThrows; //error
VoidCallable vc1 = this::notReturnsNotThrows; //ok
VoidCallable vc2 = this::notReturnsThrows; //ok
VoidCallable vc3 = this::returnsNotThrows; //ok
VoidCallable vc4 = this::returnsThrows; //ok
}
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
Here's a bug report on the feature you're requesting.
It's status is "reviewed" but I don't believe it's been implemented yet.
You can get the single value for the attribute with below code:
$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);
In Python 2, raw_input()
returns a string, and input()
tries to run the input as a Python expression.
Since getting a string was almost always what you wanted, Python 3 does that with input()
. As Sven says, if you ever want the old behaviour, eval(input())
works.
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap
:
pacman -S python-basemap
Every call to the Iterator.next()
moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry
implementations usually implement the toString()
method, so you don't have to print the key-value pair manually.
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry);
}
You have to call dr.Read()
before attempting to read any data. That method will return false if there is nothing to read.
In my case junk files from editor caused the problem. I had a config as below:
#...
http {
# ...
include ../sites/*;
}
In the ../sites
directory initially I had a default.config
file.
However, by mistake I saved duplicate files as default.config.save
and default.config.save.1
.
Removing them resolved the issue.