Python installation folder > Lib > idlelib > idle.pyw
send a shortcut to desktop.
From the desktop shortcut you can add it to taskbar too for quickaccess.
Hope this helps.
Just had a similar issue
Resolved it by checking in httpd.conf
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All <--- make sure this is not set to "None"
It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.
Same error occurs in localhost, i'm just changing the mysql port (8080 into localhost mysql port 5506). it works for me.
It presents a prompt to the user (the optional arg
of raw_input([arg])
), gets input from the user and returns the data input by the user in a string. See the docs for raw_input()
.
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input()
in that the latter tries to interpret the input given by the user; it is usually best to avoid input()
and to stick with raw_input()
and custom parsing/conversion code.
Note: This is for Python 2.x
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
A simple and easy clock for you and don't forget me ;)
var x;_x000D_
var startstop = 0;_x000D_
_x000D_
function startStop() { /* Toggle StartStop */_x000D_
_x000D_
startstop = startstop + 1;_x000D_
_x000D_
if (startstop === 1) {_x000D_
start();_x000D_
document.getElementById("start").innerHTML = "Stop";_x000D_
} else if (startstop === 2) {_x000D_
document.getElementById("start").innerHTML = "Start";_x000D_
startstop = 0;_x000D_
stop();_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function start() {_x000D_
x = setInterval(timer, 10);_x000D_
} /* Start */_x000D_
_x000D_
function stop() {_x000D_
clearInterval(x);_x000D_
} /* Stop */_x000D_
_x000D_
var milisec = 0;_x000D_
var sec = 0; /* holds incrementing value */_x000D_
var min = 0;_x000D_
var hour = 0;_x000D_
_x000D_
/* Contains and outputs returned value of function checkTime */_x000D_
_x000D_
var miliSecOut = 0;_x000D_
var secOut = 0;_x000D_
var minOut = 0;_x000D_
var hourOut = 0;_x000D_
_x000D_
/* Output variable End */_x000D_
_x000D_
_x000D_
function timer() {_x000D_
/* Main Timer */_x000D_
_x000D_
_x000D_
miliSecOut = checkTime(milisec);_x000D_
secOut = checkTime(sec);_x000D_
minOut = checkTime(min);_x000D_
hourOut = checkTime(hour);_x000D_
_x000D_
milisec = ++milisec;_x000D_
_x000D_
if (milisec === 100) {_x000D_
milisec = 0;_x000D_
sec = ++sec;_x000D_
}_x000D_
_x000D_
if (sec == 60) {_x000D_
min = ++min;_x000D_
sec = 0;_x000D_
}_x000D_
_x000D_
if (min == 60) {_x000D_
min = 0;_x000D_
hour = ++hour;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("milisec").innerHTML = miliSecOut;_x000D_
document.getElementById("sec").innerHTML = secOut;_x000D_
document.getElementById("min").innerHTML = minOut;_x000D_
document.getElementById("hour").innerHTML = hourOut;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/* Adds 0 when value is <10 */_x000D_
_x000D_
_x000D_
function checkTime(i) {_x000D_
if (i < 10) {_x000D_
i = "0" + i;_x000D_
}_x000D_
return i;_x000D_
}_x000D_
_x000D_
function reset() {_x000D_
_x000D_
_x000D_
/*Reset*/_x000D_
_x000D_
milisec = 0;_x000D_
sec = 0;_x000D_
min = 0_x000D_
hour = 0;_x000D_
_x000D_
document.getElementById("milisec").innerHTML = "00";_x000D_
document.getElementById("sec").innerHTML = "00";_x000D_
document.getElementById("min").innerHTML = "00";_x000D_
document.getElementById("hour").innerHTML = "00";_x000D_
_x000D_
}
_x000D_
<h1>_x000D_
<span id="hour">00</span> :_x000D_
<span id="min">00</span> :_x000D_
<span id="sec">00</span> :_x000D_
<span id="milisec">00</span>_x000D_
</h1>_x000D_
_x000D_
<button onclick="startStop()" id="start">Start</button>_x000D_
<button onclick="reset()">Reset</button>
_x000D_
print date('H:i');
$var = date('H:i');
Should do it, for the current time. Use a lower case h
for 12 hour clock instead of 24 hour.
More date time formats listed here.
Improving a bit more the previous answers, a maintenance page can be shown to your users while you perform changes to the site:
ErrorDocument 403 /maintenance.html
Order Allow,Deny
Allow from #.#.#.#
Where:
#.#.#.#
is your IP: What Is My IP Address?maintenance.html
there is a nice example here: Simple Maintenance PageThis was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
See section Attributes from documentation on directives.
observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.
I know this was asked over 6 years ago now, but just wanted to add my solution, as some of the suggestions above seem horribly complicated, but my solution was actually very simple.
All I had to do was wrap the pool.map() call to a helper function. Passing the class object along with args for the method as a tuple, which looked a bit like this.
def run_in_parallel(args):
return args[0].method(args[1])
myclass = MyClass()
method_args = [1,2,3,4,5,6]
args_map = [ (myclass, arg) for arg in method_args ]
pool = Pool()
pool.map(run_in_parallel, args_map)
While it's possible that this is due to a jar file missing from your classpath, it may not be.
It is important to keep two or three different exceptions strait in our head in this case:
java.lang.ClassNotFoundException
This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError
This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException
or an ExceptionInInitializerError
(indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError
is not necessarily a classpath problem.
I would look at the source for javax.mail.Authenticator
, and see what it is doing in it's static initializer. (Look at static variable initialization and the static block, if there is one.) If you aren't getting a ClassNotFoundException
prior to the NoClassDefFoundError
, you're almost guaranteed that it's a static initialization problem.
I have seen similar errors quite frequently when the hosts file incorrectly defines the localhost address, and the static initialization block relies on InetAddress.getLocalHost()
. 127.0.0.1 should point to 'localhost' (and probably also localhost.localdomain). It should NOT point to the actual host name of the machine (although for some reason, many older RedHat Linux installers liked to set it incorrectly).
pandas.merge()
is the underlying function used for all merge/join behavior.
DataFrames provide the pandas.DataFrame.merge()
and pandas.DataFrame.join()
methods as a convenient way to access the capabilities of pandas.merge()
. For example, df1.merge(right=df2, ...)
is equivalent to pandas.merge(left=df1, right=df2, ...)
.
These are the main differences between df.join()
and df.merge()
:
df1.join(df2)
always joins via the index of df2
, but df1.merge(df2)
can join to one or more columns of df2
(default) or to the index of df2
(with right_index=True
). df1.join(df2)
uses the index of df1
and df1.merge(df2)
uses column(s) of df1
. That can be overridden by specifying df1.join(df2, on=key_or_keys)
or df1.merge(df2, left_index=True)
. df1.join(df2)
does a left join by default (keeps all rows of df1
), but df.merge
does an inner join by default (returns only matching rows of df1
and df2
).So, the generic approach is to use pandas.merge(df1, df2)
or df1.merge(df2)
. But for a number of common situations (keeping all rows of df1
and joining to an index in df2
), you can save some typing by using df1.join(df2)
instead.
Some notes on these issues from the documentation at http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging:
merge
is a function in the pandas namespace, and it is also available as a DataFrame instance method, with the calling DataFrame being implicitly considered the left object in the join.The related
DataFrame.join
method, usesmerge
internally for the index-on-index and index-on-column(s) joins, but joins on indexes by default rather than trying to join on common columns (the default behavior formerge
). If you are joining on index, you may wish to useDataFrame.join
to save yourself some typing.
...
These two function calls are completely equivalent:
left.join(right, on=key_or_keys) pd.merge(left, right, left_on=key_or_keys, right_index=True, how='left', sort=False)
Had a similar problem when find an object by id... All i did was to use the fully qualified name in the class name. That is Before it was :
find("Class",id)
Object so it became like this :
find("assemblyName.Class",id)
As people above have noted you'll either have to recalculate an offset to the stroke's path coordinates or double its width and then mask one side or the other, because not only does SVG not natively support Illustrator's stroke alignment, but PostScript doesn't either.
The specification for strokes in Adobe's PostScript Manual 2nd edition states: "4.5.1 Stroking: The stroke operator draws a line of some thickness along the current path. For each straight or curved segment in the path, stroke draws a line that is centered on the segment with sides parallel to the segment." (emphasis theirs)
The rest of the specification has no attributes for offsetting the line's position. When Illustrator lets you align inside or outside, it's recalculating the actual path's offset (because it's still computationally cheaper than overprinting then masking). The path coordinates in the .ai document are reference, not what gets rastered or exported to a final format.
Because Inkscape's native format is spec SVG, it can't offer a feature the spec lacks.
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
Yes you can pass the model that you have shown using
return RedirectToAction("GetStudent", "Student", student1 );
assuming student1
is an instance of Student
which will generate the following url (assuming your using the default routes and the value of student1
are ID=4
and Name="Amit"
)
.../Student/GetStudent/4?Name=Amit
Internally the RedirectToAction()
method builds a RouteValueDictionary
by using the .ToString()
value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student
contained a property List<string> Subjects
, then that property would result in a query string value of
....&Subjects=System.Collections.Generic.List'1[System.String]
and binding would fail and that property would be null
void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
{
TextBox txt = (TextBox)sender;
var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
string str = txt.Text + e.Text.ToString();
int cntPrc = 0;
if (str.Contains('.'))
{
string[] tokens = str.Split('.');
if (tokens.Count() > 0)
{
string result = tokens[1];
char[] prc = result.ToCharArray();
cntPrc = prc.Count();
}
}
if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Do not change the gravity of the LinearLayout to "right" if you don't want everything to be to the right.
Try:
fill_parent
right
Code:
<TextView
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
</TextView>
I don't know if this applies to python as well, but I think it depends on the operating system that you are running.
On Linux for example, output to terminal flushes the buffer on a newline, whereas for output to files it only flushes when the buffer is full (by default). This is because it is more efficient to flush the buffer fewer times, and the user is less likely to notice if the output is not flushed on a newline in a file.
You might be able to auto-flush the output if that is what you need.
EDIT: I think you would auto-flush in python this way (based from here)
#0 means there is no buffer, so all output
#will be auto-flushed
fsock = open('out.log', 'w', 0)
sys.stdout = fsock
#do whatever
fsock.close()
Just wanted to summarize everything:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div class="unselectable" unselectable="yes" onselectstart="return false;"/>
You could do this, which facilitates reading:
>&2 echo "error"
>&2
copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to. For more information see the Bash Hackers Illustrated Redirection Tutorial.
Scrum is just one of the many iterative and incremental agile software development methods. You can find here a very detailed description of the process.
In the SCRUM methodology, a Sprint is the basic unit of development. Each Sprint starts with a planning meeting, where the tasks for the sprint are identified and an estimated commitment for the sprint goal is made. A Sprint ends with a review or retrospective meeting where the progress is reviewed and lessons for the next sprint are identified. During each Sprint, the team creates finished portions of a Product.
In the Agile methods each iteration involves a team working through a full software development cycle, including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.
So if in a SCRUM Sprint you perform all the software development phases (from requirement analysis to acceptance testing), and in my opinion you should, you can say SCRUM Sprints correspond to AGILE Iterations.
$ perl -MXML::Simple -le 'print $INC{"XML/Simple.pm"}'
From the perlvar entry on %INC
:
- %INC
The hash
%INC
contains entries for each filename included via thedo
,require
, oruse
operators. The key is the filename you specified (with module names converted to pathnames), and the value is the location of the file found. Therequire
operator uses this hash to determine whether a particular file has already been included.If the file was loaded via a hook (e.g. a subroutine reference, see require for a description of these hooks), this hook is by default inserted into
%INC
in place of a filename. Note, however, that the hook may have set the %INC entry by itself to provide some more specific info.
A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be
current_folder_path, current_folder_name = os.path.split(os.getcwd())
You may want to use the ndarray.item
method, as in a.item()
. This is also equivalent to (the now deprecated) np.asscalar(a)
. This has the benefit of working in situations with views and superfluous axes, while the above solutions will currently break. For example,
>>> a = np.asarray(1).view()
>>> a.item() # correct
1
>>> a[0] # breaks
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a = np.asarray([[2]])
>>> a.item() # correct
2
>>> a[0] # bad result
array([2])
This also has the benefit of throwing an exception if the array is not a singleton, while the a[0]
approach will silently proceed (which may lead to bugs sneaking through undetected).
>>> a = np.asarray([1, 2])
>>> a[0] # silently proceeds
1
>>> a.item() # detects incorrect size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: can only convert an array of size 1 to a Python scalar
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
I actually figured this out myself. I'll add my solution as another option.
extension UIViewController {
func prefersStatusBarHidden() -> Bool {
return true
}
}
Angular Js Demo Code :-
angular.module('ModuleName',[]).controller('main', ['$http', function($http){
var formData = { password: 'test pwd', email : 'test email' };
var postData = 'myData='+JSON.stringify(formData);
$http({
method : 'POST',
url : 'resources/curl.php',
data: postData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(res){
console.log(res);
}).error(function(error){
console.log(error);
});
}]);
Server Side Code :-
<?php
// it will print whole json string, which you access after json_decocde in php
$myData = json_decode($_POST['myData']);
print_r($myData);
?>
Due to angular behaviour there is no direct method for normal post behaviour at PHP server, so you have to manage it in json objects.
You have the month and day swapped:
'%m/%d/%Y %H:%M:%S.%f'
28
will never fit in the range for the %m
month parameter otherwise.
With %m
and %d
in the correct order parsing works:
>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)
You don't need to add '000'
; %f
can parse shorter numbers correctly:
>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)
Pattern satisfy, these below criteria
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$
You can either copy files into the folder where external partition is located or use
INSERT OVERWRITE TABLE tablename1 PARTITION (partcol1=val1, partcol2=val2...)...
statement.
I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,
For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7
then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.
C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).
finally, right click on project->Maven->Update Project...Thats it.
happy coding.
The quotes you use are the issue:
<meta http-equiv=”refresh” content=”5" >
You should use the "
<meta http-equiv="refresh" content="5">
Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:
if(Object.values == null) {
Object.values = function(obj) {
var arr, o;
arr = new Array();
for(o in obj) { arr.push(obj[o]); }
return arr;
}
}
If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git
). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
There are several ways to do this, below are two options:
Option 1 - Right click on the database you want to copy
Choose 'Tasks' > 'Generate scripts'
'Select specific database objects'
Check 'Tables'
Mark 'Save to new query window'
Click 'Advanced'
Set 'Types of data to script' to 'Schema and data'
Next, Next
You can now run the generated query on the new database.
Option 2
Right click on the database you want to copy
'Tasks' > 'Export Data'
Next, Next
Choose the database to copy the tables to
Mark 'Copy data from one or more tables or views'
Choose the tables you want to copy
Finish
Quoting from the specification:
The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
You should actually check against null
.
if (localStorage.getItem("username") === null) {
//...
}
Each time the same will be generated:
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
print(uuid)
}
Each time a new one will be generated:
let uuid = UUID().uuidString
print(uuid)
Both answers are correct. If you user .TO -method then the semicolumn is OK - but not for the addrecipients-method. There you need to split, e.g. :
Dim Splitter() As String
Splitter = Split(AddrMail, ";")
For Each Dest In Splitter
.Recipients.Add (Trim(Dest))
Next
The jQuery.browser options was deprecated earlier and removed in 1.9 release along with a lot of other deprecated items like .live.
For projects and external libraries which want to upgrade to 1.9 but still want to support these features jQuery have release a migration plugin for the time being.
If you need backward compatibility you can use migration plugin.
The CSS specification requires that position:fixed
be anchored to the viewport, not the containing positioned element.
If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.
ALTERNATIVE: Some browsers have sticky
CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:
sticky
... constrains an element to be positioned inside the intersection of its container box, and the viewport.A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.
Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky
still needs a -webkit
prefix in Safari.
See caniuse for up-to-date stats on browser support.
In regards to using extension to define data type. I noticed that MailChimp API is doing it, but I don't think this is a good idea.
GET /zzz/cars.json/1
GET /zzz/cars.xml/1
My sound like a good idea, but I think "older" approach is better - using HTTP headers
GET /xxx/cars/1
Accept: application/json
Also HTTP headers are much better for cross data type communication (if ever someone would need it)
POST /zzz/cars
Content-Type: application/xml <--- indicates we sent XML to server
Accept: application/json <--- indicates we want get data back in JSON format
Your original code has $('document')... when it should have $(document) without the quotes.
adapt as required
$m='08';
$months = array (1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
echo $months[(int)$m];
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
All DECLAREs need to be at the top. ie.
delimiter //
CREATE TRIGGER pgl_new_user
AFTER INSERT ON users FOR EACH ROW
BEGIN
DECLARE m_user_team_id integer;
DECLARE m_projects_id integer;
DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;
SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");
OPEN cur;
ins_loop: LOOP
FETCH cur INTO m_projects_id;
IF done THEN
LEAVE ins_loop;
END IF;
INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access)
VALUES (NEW.id, m_projects_id, now(), now(), 20);
END LOOP;
CLOSE cur;
END//
I want my python function to split a sentence (input) and store each word in a list
The str().split()
method does this, it takes a string, splits it into a list:
>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0
The problem you're having is because of a typo, you wrote print(words)
instead of print(word)
:
Renaming the word
variable to current_word
, this is what you had:
def split_line(text):
words = text.split()
for current_word in words:
print(words)
..when you should have done:
def split_line(text):
words = text.split()
for current_word in words:
print(current_word)
If for some reason you want to manually construct a list in the for loop, you would use the list append()
method, perhaps because you want to lower-case all words (for example):
my_list = [] # make empty list
for current_word in words:
my_list.append(current_word.lower())
Or more a bit neater, using a list-comprehension:
my_list = [current_word.lower() for current_word in words]
In Swift:
tableView.separatorStyle = .None
You have to be specific about the columns you are selecting. If your user
table had four columns id, name, username, opted_in
you must select exactly those four columns from the query. The syntax looks like:
INSERT INTO user (id, name, username, opted_in)
SELECT id, name, username, opted_in
FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id
However, there does not appear to be any reason to join against user_permission
here, since none of the columns from that table would be inserted into user
. In fact, this INSERT
seems bound to fail with primary key uniqueness violations.
MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT
statements in your code, using the last insert id from the first query, or create an AFTER INSERT
trigger on the primary table.
INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)
Or using a trigger:
CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END
It is because generics were added on to java after they made it, so its kinda clunky because the original makers of java thought that when making an array the type would be specified in the making of it. So that does not work with generics so you have to do E[] array=(E[]) new Object[15]; This compiles but it gives a warning.
In Java/Android, to test a password with at least one number, one letter, one special character in following pattern:
"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,}$"
I had the same problem when I wrote two upstreams in NGINX conf
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
server 127.0.0.1:9000;
}
...
fastcgi_pass php_upstream;
but in /etc/php/7.3/fpm/pool.d/www.conf
I listened the socket only
listen = /var/run/php/my.site.sock
So I need just socket, no any 127.0.0.1:9000
, and I just removed IP+port upstream
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
}
This could be rewritten without an upstream
fastcgi_pass unix:/var/run/php/my.site.sock;
Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.
Go to Preferences > Gradle and uncheck "Offline work".
Use utf8_encode()
Man page can be found here http://php.net/manual/en/function.utf8-encode.php
Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html
For rails 5.1+ callbacks
As of Ruby on Rails 5.1, the attribute_changed?
and attribute_was
ActiveRecord methods will be deprecated
Use saved_change_to_attribute?
instead of attribute_changed?
@user.saved_change_to_street1? # => true/false
More examples here
Assuming you want to list grants on all objects a particular user has received:
select * from all_tab_privs_recd where grantee = 'your user'
This will not return objects owned by the user. If you need those, use all_tab_privs
view instead.
I was just wondering how the random number generator in C# works.
That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.
I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int, int)
:
Random rng = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(rng.Next(1, 101));
}
Note that the upper bound is exclusive - which is why I've used 101 here.
You should also be aware of some of the "gotchas" associated with Random
- in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.
The directive has changed to character-set-system=utf8
http://dev.mysql.com/doc/refman/5.6/en/charset-configuration.html
another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
If you have more then 1 dimension array
with open("file.txt", 'w') as output:
for row in values:
output.write(str(row) + '\n')
Code to write without '[' and ']'
with open("file.txt", 'w') as file:
for row in values:
s = " ".join(map(str, row))
file.write(s+'\n')
You can use DateDiff
for this. The where clause in your query would look like:
where DATEDIFF(day,pdate,GETDATE()) < 31
use this in style
body
{
overflow:hidden;
width:100%;
}
Use this in head tag
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />
Try removing the float
attribute from span6:
{ float:none !important; }
You need to float the divs in required direction eg left
or right
.
Simplest solution seems to be specifying the ylim
range. Here is some code to do this automatically (left default, right - adjusted):
# default y-axis
barplot(dat, beside=TRUE)
# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))
The trick is to use pretty()
which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.
In the example 0 was also added pretty(c(0, dat))
which makes sure that axis starts from 0.
Alternatively, you could cherry-pick the commit-id onto your branch.
<commit-id> made in detached head state
git checkout master
git cherry-pick <commit-id>
No temporary branches, no merging.
I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.
function getVals(){_x000D_
// Get slider values_x000D_
var parent = this.parentNode;_x000D_
var slides = parent.getElementsByTagName("input");_x000D_
var slide1 = parseFloat( slides[0].value );_x000D_
var slide2 = parseFloat( slides[1].value );_x000D_
// Neither slider will clip the other, so make sure we determine which is larger_x000D_
if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
_x000D_
var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
// Initialize Sliders_x000D_
var sliderSections = document.getElementsByClassName("range-slider");_x000D_
for( var x = 0; x < sliderSections.length; x++ ){_x000D_
var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
for( var y = 0; y < sliders.length; y++ ){_x000D_
if( sliders[y].type ==="range" ){_x000D_
sliders[y].oninput = getVals;_x000D_
// Manually trigger event first time to display values_x000D_
sliders[y].oninput();_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
section.range-slider {_x000D_
position: relative;_x000D_
width: 200px;_x000D_
height: 35px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
pointer-events: none;_x000D_
position: absolute;_x000D_
overflow: hidden;_x000D_
left: 0;_x000D_
top: 15px;_x000D_
width: 200px;_x000D_
outline: none;_x000D_
height: 18px;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
pointer-events: all;_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
pointer-events: all;_x000D_
position: relative;_x000D_
z-index: 10;_x000D_
-moz-appearance: none;_x000D_
width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
position: relative;_x000D_
z-index: -1;_x000D_
background-color: rgba(0, 0, 0, 1);_x000D_
border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
-moz-appearance: none;_x000D_
background: none transparent;_x000D_
border: 0;_x000D_
}_x000D_
section.range-slider input[type=range]::-moz-focus-outer {_x000D_
border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
<span class="rangeValues"></span>_x000D_
<input value="5" min="0" max="15" step="0.5" type="range">_x000D_
<input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
If you just want something more simple, you can just change:
<p:panelGrid >
</p:panelGrid>
to:
<h:panelGrid border="0">
</h:panelGrid>
That's worked fine for me
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
You can directly plot the lines you want by feeding the plot
command with the corresponding data (boundaries of the segments):
plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)
(of course you can choose the color, line width, line style, etc.)
From your example:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)
# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')
plt.show()
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Instead to target on button class (.btn), here I target to button element itself and it works for me.
button:focus {
outline:none !important;
box-shadow:none !important;
}
And can use shadow-none
class for input field
If you are using Webstorm and if you don't have your own config file, then just enable EcmaScript.next
in Relaxing options in in
Settings | Languages & Frameworks | JavaScript | Code Quality Tools | JSHint
See this question How-do-I-resolve-these-JSHint-ES6-errors
You can easily write a bit code that will read in a file. You can either assume one sql statement per line, or assume the ;
So, assuming you have a text file such as:
insert into tblTest (t1) values ('2000');
update tbltest set t1 = '2222'
where id = 5;
insert into tblTest (t1,t2,t3)
values ('2001','2002','2003');
Note the in the above text file we free to have sql statements on more then one line.
the code you can use to read + run the above script is:
Sub SqlScripts()
Dim vSql As Variant
Dim vSqls As Variant
Dim strSql As String
Dim intF As Integer
intF = FreeFile()
Open "c:\sql.txt" For Input As #intF
strSql = input(LOF(intF), #intF)
Close intF
vSql = Split(strSql, ";")
On Error Resume Next
For Each vSqls In vSql
CurrentDb.Execute vSqls
Next
End Sub
You could expand on placing some error msg if the one statement don't work, such as
if err.number <> 0 then
debug.print "sql err" & err.Descripiton & "-->" vSqls
end dif
Regardless, the above split() and string read does alow your sql to be on more then one line...
This should do it, let me know if you have trouble with it:
Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy
'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
Alternatively, you could just:
Sub foo2()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")
'Close x:
x.Close
End Sub
To extend this to the entire sheet:
With x.Sheets("name of copying sheet").UsedRange
'Now, paste to y worksheet:
y.Sheets("sheet name").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
And yet another way, store the value as a variable and write the variable to the destination:
Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value
'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals
'Close x:
x.Close
End Sub
The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:
Copy/PasteSpecial vs Range.Value = Range.Value
That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.
You could:
Define a userStatus
parameter for the child component and provide the value when using this component from the parent:
@Component({
(...)
})
export class Profile implements OnInit {
@Input()
userStatus:UserStatus;
(...)
}
and in the parent:
<profile [userStatus]="userStatus"></profile>
Inject the parent into the child component:
@Component({
(...)
})
export class Profile implements OnInit {
constructor(app:App) {
this.userStatus = app.userStatus;
}
(...)
}
Be careful about cyclic dependencies between them.
If you are using Google Maps + Google Play Services inside a library project (especially if you recently migrated from Eclipse to Android Studio), you can encounter this error when you try to run an app that uses your library, while a different app that uses the same library is already installed on your device.
Fix:
make sure that defaultConfig.applicationId is defined in android section of the build.gradle
file for each project using your library
android {
defaultConfig.applicationId = "com.company.appname"
}
I would recommend using the package name of the specific app. With this fix, the provider names will no longer conflict, and your app will run as expected.
Symptoms
1.) Your users are seeing the dreaded "-505" install error when installing your app from the Play Store.
2.) You will see this error message when you try to install a second app that uses your library via Android Studio [INSTALL_FAILED_CONFLICTING_PROVIDER]:
In your console, you will see a message like this:
Package couldn't be installed in /data/app/com.company.appname-1
com.android.server.pm.PackageManagerException:
Can't install because provider name
com.google.android.gms.measurement.google_measurement_service
(in package com.company.appname) is already used by
com.company.otherInstalledAppName
The fix is to make sure that defaultConfig.applicationId is defined in android section of the build.gradle
file for each project using your library
android {
defaultConfig.applicationId = "com.company.appname"
}
More reading can be found here in the original bug report: Issue 784: Multiple apps using same authority provider name
declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )
echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"
echo -e " \n Total elements in arr are : ${arr[*]} \n"
echo -e " \n Total lenght of arr is : ${#arr[@]} \n"
for (( i=0; i<10; i++ ))
do echo "The value in position $i for arr is [ ${arr[i]} ]"
done
for (( j=0; j<10; j++ ))
do echo "The length in element $j is ${#arr[j]}"
done
for z in "${!arr[@]}"
do echo "The key ID is $z"
done
~
To install a specific python package version whether it is the first time, an upgrade or a downgrade use:
pip install --force-reinstall MySQL_python==1.2.4
MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:
pip install MySQL_python==
assert
is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if
statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.
Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char
version.
Yes, use source or the short form which is just .
:
. other_script.sh
Select all text in the document and press Ctrl + E + D.
You can create config once and use it everywhere.
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'Authorization': 'Bearer '+token}
});
instance.get('/path')
.then(response => {
return response.data;
})
You can use Distinct extension method from LINQ
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
I usually loop over the array and attach a comma after every entry in the string. After the loop I delete the last comma again.
Maybe not the best way, but less expensive than checking every time if it's the last object in the loop I guess.
To get your desired output:
long phoneFmt = 123456789L;
//get a 12 digits String, filling with left '0' (on the prefix)
DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
String phoneRawString= phoneDecimalFmt.format(phoneFmt);
java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
//suposing a grouping of 3-3-4
String[] phoneNumArr={phoneRawString.substring(0, 3),
phoneRawString.substring(3,6),
phoneRawString.substring(6)};
System.out.println(phoneMsgFmt.format(phoneNumArr));
The result at the Console looks like this:
(012)-345-6789
For storing phone numbers, you should consider using a data type other than numbers.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.
This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html
It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.
This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.
HashMap<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
First of all Map
is an interface it has different implementation like - HashMap
, TreeHashMap
, LinkedHashMap
etc. Interface works like a super class for the implementing class. So according to OOP's rule any concrete class that implements Map
is a Map
also. That means we can assign/put any HashMap
type variable to a Map
type variable without any type of casting.
In this case we can assign map1
to map2
without any casting or any losing of data -
map2 = map1
In swift 5
,
let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Update (27-Jun-18): It looks like there was a major update to jsdom
that causes the original answer to no longer work. I found this answer that explains how to use jsdom
now. I've copied the relevant code below.
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = jQuery = require('jquery')(window);
Note: The original answer fails to mention that it you will need to install jsdom as well using npm install jsdom
Update (late 2013): The official jQuery team finally took over the management of the jquery
package on npm:
npm install jquery
Then:
require("jsdom").env("", function (err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
});
val
is final, that is, cannot be set. Think final
in java.
Better option to change also collation of varchar columns inside table also
SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;') AS mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "myschema"
AND TABLE_TYPE="BASE TABLE"
Additionnaly if you have data with forein key on non utf8 column before launch the bunch script use
SET foreign_key_checks = 0;
It means global SQL will be for mySQL :
SET foreign_key_checks = 0;
ALTER TABLE `table1` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `table2` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE `tableXXX` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
SET foreign_key_checks = 1;
But take care if according mysql documentation http://dev.mysql.com/doc/refman/5.1/en/charset-column.html,
If you use ALTER TABLE to convert a column from one character set to another, MySQL attempts to map the data values, but if the character sets are incompatible, there may be data loss. "
EDIT: Specially with column type enum, it just crash completly enums set (even if there is no special caracters) https://bugs.mysql.com/bug.php?id=26731
Since you are probably running Windows (from looking at your tags), this would be the easiest way to open and show an image file from the console without installing extra stuff like PIL.
import os
os.system('start pic.png')
If you have added multiple (Third-Party)**libraries and Extends **Application class
Then it might occur.
For that, you have to set multiDexEnabled true
and replace your extended Application
class with MultiDexApplication
.
It will be solved.
this worked for me with minimal code
$(my_list).remove('li');
I had a similar issue. The content of the child element was supposed to stay in the parent element while the background had to extend the full viewport width.
I resolved this issue by making the child element position: relative
and adding a pseudo element (:before
) to it with position: absolute; top: 0; bottom: 0; width: 4000px; left: -1000px;
.
The pseudo element stays behind the actual child as a pseudo background element. This works in all browsers (even IE8+ and Safari 6+ - don't have the possibility to test older versions).
Small example fiddle: http://jsfiddle.net/vccv39j9/
when you are using POST method in HTML forms, you need to catch the data from req.body in the server side i.e. Node.js. and also add
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({extended: false}));
OR
use method='GET' in HTML and and catch the data by req.query in the server side i.e. Node.js
Controller as version (recommended)
Here the template
<div ng-app="example" ng-controller="myController as $ctrl">
<input type="text" ng-model="$ctrl.searchText" />
<button ng-click="$ctrl.check()">Check!</button>
{{ $ctrl.searchText }}
</div>
The JS
angular.module('example', [])
.controller('myController', function() {
var vm = this;
vm.check = function () {
console.log(vm.searchText);
};
});
An example: http://codepen.io/Damax/pen/rjawoO
The best will be to use component with Angular 2.x or Angular 1.5 or upper
########Old way (NOT recommended)
This is NOT recommended because a string is a primitive, highly recommended to use an object instead
Try this in your markup
<input type="text" ng-model="searchText" />
<button ng-click="check(searchText)">Check!</button>
{{ searchText }}
and this in your controller
$scope.check = function (searchText) {
console.log(searchText);
}
There are two methods to consider which achieve the same effect for handling null pointers to C-style strings.
The ternary operator
void setvalue(const char *value)
{
std::string mValue = value ? value : "";
}
or the humble if statement
void setvalue(const char *value)
{
std::string mValue;
if(value) mValue = value;
}
In both cases, value
is only assigned to mValue
when value
is not a null pointer. In all other cases (i.e. when value
is null), mValue
will contain an empty string.
The ternary operator method may be useful for providing an alternative default string literal in the absence of a value from value
:
std::string mValue = value ? value : "(NULL)";
<md-button class="md-fab md-primary" md-theme="cyan" aria-label="Profile">
<md-icon icon="/img/icons/ic_people_24px.svg" style="width: 24px; height: 24px;"></md-icon>
</md-button>
source: https://material.angularjs.org/#/demo/material.components.button
I believe you can get the border width using .css('border-left-width')
. You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.
See jQuery calculate padding-top as integer in px
Use the same logic as border or padding.
Alternatively, you could use outerWidth. The pseudo-code should bemargin = (outerWidth(true) - outerWidth(false)) / 2
. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.
All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use dictionaries.
In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()
Note that java11 now offers a new HTTP api HttpClient, which supports fully asynchronous operation, using java's CompletableFuture.
It also supports a synchronous version, with calls like send, which is synchronous, and sendAsync, which is asynchronous.
Example of an async request (taken from the apidoc):
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.timeout(Duration.ofMinutes(2))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context
option, as stated in the documentation:
The
this
reference within all callbacks is the object in the context option passed to$.ajax
in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
So you would use
$.ajax('http://www.example.org', {
dataType: 'xml',
data: {'a':1,'b':2,'c':3},
context: {
url: 'http://www.example.org'
}
}).done(function(xml) {alert(this.url});
As far as I know, the most pythonic/efficient method would be:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.
Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx
See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx
Example script for 'TestUser' to use the profile named 'General Admin Mail'.
USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'General Admin Mail',
@principal_name = 'TestUser',
@is_default = 1 ;
With the background-size property in those browsers which support this very new feature of CSS.
If you don't know the correct Locale and the string can have a thousand separator this could be a last resort:
doubleStrIn = doubleStrIn.replaceAll("[^\\d,\\.]++", "");
if (doubleStrIn.matches(".+\\.\\d+,\\d+$"))
return Double.parseDouble(doubleStrIn.replaceAll("\\.", "").replaceAll(",", "."));
if (doubleStrIn.matches(".+,\\d+\\.\\d+$"))
return Double.parseDouble(doubleStrIn.replaceAll(",", ""));
return Double.parseDouble(doubleStrIn.replaceAll(",", "."));
Be aware: this will happily parse strings like "R 1 52.43,2" to "15243.2".
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
If you do not want to use angular-ui-router, but would like to have your controllers lazy loaded via RequireJS, there are couple of problems with event $routeChangeStart
when using your controllers as RequireJS modules (lazy loaded).
You cannot be sure the controller will be loaded before $routeChangeStart
gets triggered -- in fact it wont be loaded. That means you cannot access properties of next
route like locals
or $$route
because they are not yet setup.
Example:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}]
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(next.$$route, next.locals); // undefined, undefined
});
}]);
This means you cannot check access rights in there.
Solution:
As loading of controller is done via resolve, you can do the same with your access control check:
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/foo", {
controller: "Foo",
resolve: {
controller: ["$q", function($q) {
var deferred = $q.defer();
require(["path/to/controller/Foo"], function(Foo) {
// now controller is loaded
deferred.resolve();
});
return deferred.promise;
}],
access: ["$q", function($q) {
var deferred = $q.defer();
if (/* some logic to determine access is granted */) {
deferred.resolve();
} else {
deferred.reject("You have no access rights to go there");
}
return deferred.promise;
}],
}
});
}]);
app.run(["$rootScope", function($rootScope) {
$rootScope.$on("$routeChangeError", function(event, next, current, error) {
console.log("Error: " + error); // "Error: You have no access rights to go there"
});
}]);
Note here that instead of using event $routeChangeStart
I'm using $routeChangeError
In my case I followed this. Summary, in gradle app level: change this :
variant.outputs.all { output ->
variant.assemble.doLast {
....
}
}
to
variant.outputs.all { output ->
variant.getAssembleProvider().configure() {
it.doLast {
....
}
}
Yes you can do it. Why don't you just try doing that?
Building slightly upon the answers here, I've wrapped this process up as a simple Bash script, which could of course be used as a Git alias as well.
The important addition to me is that this prompts me to run unit tests before committing and passes in the current branch name by default.
$ git_push_new_branch.sh
Have you run your unit tests yet? If so, pass OK or a branch name, and try again
usage: git_push_new_branch {OK|BRANCH_NAME}
e.g.
git_push_new_branch -> Displays prompt reminding you to run unit tests
git_push_new_branch OK -> Pushes the current branch as a new branch to the origin
git_push_new_branch MYBRANCH -> Pushes branch MYBRANCH as a new branch to the origin
function show_help()
{
IT=$(cat <<EOF
Have you run your unit tests yet? If so, pass OK or a branch name, and try again
usage: git_push_new_branch {OK|BRANCH_NAME}
e.g.
git_push_new_branch.sh -> Displays prompt reminding you to run unit tests
git_push_new_branch.sh OK -> Pushes the current branch as a new branch to the origin
git_push_new_branch.sh MYBRANCH -> Pushes branch MYBRANCH as a new branch to the origin
)
echo "$IT"
exit
}
if [ -z "$1" ]
then
show_help
fi
CURR_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$1" == "OK" ]
then
BRANCH=$CURR_BRANCH
else
BRANCH=${1:-$CURR_BRANCH}
fi
git push -u origin $BRANCH
This will give you the deadline :
select id,
title,
created_at + interval '1' day * claim_window as deadline
from projects
Alternatively the function make_interval
can be used:
select id,
title,
created_at + make_interval(days => claim_window) as deadline
from projects
To get all projects where the deadline is over, use:
select *
from (
select id,
created_at + interval '1' day * claim_window as deadline
from projects
) t
where localtimestamp at time zone 'UTC' > deadline
Thank you all for this thread! My colleague and I just discovered that the default_value
property is a Constant, not a Variable.
In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value
was set to the correct value.
But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect
to populate the associated Context. So the FIRST time the Select is rendered, default_value
is set to null
. Then when the Context is populated and the Select is supposed to be re-rendered, default_value
cannot be changed and thus the initial default value is not set.
The solution was ultimately simple: Use the value
property instead. But figuring out why default_value
didn't work like it did with my other forms took some time.
I'm posting this to help others in the community.
Loop through the results and place each one in an array
use mysqli_fetch_all()
to get them all at one time
Using the Thread.sleep(millis)
method.
var var1 = "something";
var var2 = "something_else";
switch(var1 + "|" + var2) {
case "something|something_else":
...
break;
case "something|...":
break;
case "...|...":
break;
}
If you have 5 possibilities for each one you will get 25 cases.
Three slightly different answers depending how you look at the question:
1) Good enough for the exact question asked is Jonathan Leffler's solution, except that to round up to 16-aligned, you only need 15 extra bytes, not 16.
A:
/* allocate a buffer with room to add 0-15 bytes to ensure 16-alignment */
void *mem = malloc(1024+15);
ASSERT(mem); // some kind of error-handling code
/* round up to multiple of 16: add 15 and then round down by masking */
void *ptr = ((char*)mem+15) & ~ (size_t)0x0F;
B:
free(mem);
2) For a more generic memory allocation function, the caller doesn't want to have to keep track of two pointers (one to use and one to free). So you store a pointer to the 'real' buffer below the aligned buffer.
A:
void *mem = malloc(1024+15+sizeof(void*));
if (!mem) return mem;
void *ptr = ((char*)mem+sizeof(void*)+15) & ~ (size_t)0x0F;
((void**)ptr)[-1] = mem;
return ptr;
B:
if (ptr) free(((void**)ptr)[-1]);
Note that unlike (1), where only 15 bytes were added to mem, this code could actually reduce the alignment if your implementation happens to guarantee 32-byte alignment from malloc (unlikely, but in theory a C implementation could have a 32-byte aligned type). That doesn't matter if all you do is call memset_16aligned, but if you use the memory for a struct then it could matter.
I'm not sure off-hand what a good fix is for this (other than to warn the user that the buffer returned is not necessarily suitable for arbitrary structs) since there's no way to determine programatically what the implementation-specific alignment guarantee is. I guess at startup you could allocate two or more 1-byte buffers, and assume that the worst alignment you see is the guaranteed alignment. If you're wrong, you waste memory. Anyone with a better idea, please say so...
[Added:
The 'standard' trick is to create a union of 'likely to be maximally aligned types' to determine the requisite alignment. The maximally aligned types are likely to be (in C99) 'long long
', 'long double
', 'void *
', or 'void (*)(void)
'; if you include <stdint.h>
, you could presumably use 'intmax_t
' in place of long long
(and, on Power 6 (AIX) machines, intmax_t
would give you a 128-bit integer type). The alignment requirements for that union can be determined by embedding it into a struct with a single char followed by the union:
struct alignment
{
char c;
union
{
intmax_t imax;
long double ldbl;
void *vptr;
void (*fptr)(void);
} u;
} align_data;
size_t align = (char *)&align_data.u.imax - &align_data.c;
You would then use the larger of the requested alignment (in the example, 16) and the align
value calculated above.
On (64-bit) Solaris 10, it appears that the basic alignment for the result from malloc()
is a multiple of 32 bytes.
]
In practice, aligned allocators often take a parameter for the alignment rather than it being hardwired. So the user will pass in the size of the struct they care about (or the least power of 2 greater than or equal to that) and all will be well.
3) Use what your platform provides: posix_memalign
for POSIX, _aligned_malloc
on Windows.
4) If you use C11, then the cleanest - portable and concise - option is to use the standard library function aligned_alloc
that was introduced in this version of the language specification.
"[1-9][0-9]*|0
"
I'd just use "[0-9]+
" to represent positive whole numbers.
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
Warning: this will delete your files, make sure you have a backup or can revert the commit.
Delete all elements in repository:
$ git rm -r *
then:
$ git commit -m 'Delete all the stuff'
if you want to remove the remaining "#" from the url
$(window).on('load', function(e){
if (window.location.hash == '#_=_') {
window.location.hash = ''; // for older browsers, leaves a # behind
history.pushState('', document.title, window.location.pathname); // nice and clean
e.preventDefault(); // no page reload
}
})
new_hash = old_hash.merge(old_hash) do |_key, value, _value|
value.upcase
end
# old_hash = {"a" => "b", "c" => "d"}
# new_hash = {"a" => "B", "c" => "D"}
Using jQuery, you can do it in a super simple one-line-script.
// HTML
<div id="columnOne">
</div>
<div id="columnTwo">
</div>
// Javascript
$("#columnTwo").height($("#columnOne").height());
This is a bit more interesting. The technique is called Faux Columns. More or less you don't actually set the actual height to be the same, but you rig up some graphical elements so they look the same height.
See Linker Tools Error LNK2019 at MSDN, it has a detailed list of common problems that cause LNK2019.
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.
I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:
func SaySomething(say string) {
// All the complicated bits involved in saying something
}
func SayHello() {
SaySomething("Hello")
}
With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println
for example just adds a newline to what fmt.Print
would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
If you know the range of number of arguments that will be provided, you can always use some function overloading, like
f(int a)
{int res=a; return res;}
f(int a, int b)
{int res=a+b; return res;}
and so on...
Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, set Enforce foreign key constraint to 'Yes' (to enable foreign key constraints) or 'No' (to disable it).
Probably this is not best code for this task, but is working -
def front_back(a, b):
if len(a) % 2 == 0 and len(b) % 2 == 0:
print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
elif len(a) % 2 == 1 and len(b) % 2 == 0:
print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):]
elif len(a) % 2 == 0 and len(b) % 2 == 1:
print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:]
else :
print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]
You'll normally be returning JSON either because:
A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.
or
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
Or, possibly, you are eating your own dogfood and doing both
In both cases render :json => some_data
will JSON-ify the provided data. The :callback
key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)
:callback
?JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com
and you will be serving your application off of services.yoursite.com
your JavaScript will not (by default) be able to make XMLHttpRequest
(XHR - aka ajax) requests from services
to api
. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
Thus, a client-side JS application could create a script
tag pointing at api.yoursite.com/your/endpoint?name=John
and have the valueOfCallbackHere
function (which would have to be defined in the client-side JS) called with the data from this other origin.)
One more point I haven't found anyone mentioned:
If you have virtual method, each declaration can have its own default value!
It depends on the interface you are calling which value will be used.
Example on ideone
struct iface
{
virtual void test(int a = 0) { std::cout << a; }
};
struct impl : public iface
{
virtual void test(int a = 5) override { std::cout << a; }
};
int main()
{
impl d;
d.test();
iface* a = &d;
a->test();
}
It prints 50
I strongly discourage you to use it like this
I followed the link to RFC1034 and read most of it and was surprised to see this:
The labels must follow the rules for ARPANET host names. They must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. There are also some restrictions on the length. Labels must be 63 characters or less.
For clarification, a domain names are made up of labels which are separated by dots ".". This spec must be outdated because it doesn't mention the use of underscores. I can understand the confusion if anybody stumbles over this spec without knowing it is obsolete. It is obsolete, isn't it?
I followed the link to RFC2181 and read some of it. Especially where it pertains to the issue of what is an authoritative, or canonical, name and the issue of what makes a valid DNS label.
As posted earlier it states there's only a length restriction then to sum it up it reads:
(about names and valid labels)
These are already adequately specified, however the specifications seem to be sometimes ignored. We seek to reinforce the existing specifications.
Kind of leaves me wondering if "a length only restriction" is "adequate". Are we going to start seeing domain names like @#$%!! soon? Isn't the internet screwed up enough?
The answer by Bryan Oakley above has a glitch as it has already been pointed out and the solution offered by Andrew Marshall though it does not carry the glitch, nevertheless it does not make it obvious for too much customization on the colors used.
As macOS Catalina asks for zsh to be the default shell from now on, I think several more people may want to customize their prompt and might be coming here for an answer. So, I thought I would try to give a broader summary and touch upon other very closely-related notions that allow more customization.
3-Digit Codes for Various Colors. First of all, here we can find 3-digit codes for various colors: https://unix.stackexchange.com/a/124409/194343. For example, 214 is some kind of orange color.
Foreground and Background. The other key information is that for Foreground and bacKground colors one can define what they want with F and K respectively. Source is zsh manual on visual effects: http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Visual-effects
So, for example, the following two commands
autoload -U colors && colors
export PS1="%F{214}%K{000}%m%F{015}%K{000}:%F{039}%K{000}%~%F{015}%K{000}\$ "
present the hostname in orange with black background, followed by a colon in white with black background, followed by the current working directory in bright blue with black background, followed by the dollar sign in white with black background.
More related information is found below.
Prompt information on the right-hand side. For example, adding a timestamp. See https://superuser.com/a/1251045/290299. Of course, this can be color-coded, for example with some light blue/purple-ish color, like this:
RPROMPT="%F{111}%K{000}[%D{%f/%m/%y}|%@]"
Colors for ls
. After reading the manual for ls, one for example can activate the colors for ls
using the following two commands:
export CLICOLOR=1
export LSCOLORS=gafacadabaegedabagacad
Finally, as a last remark that I have not tested as I am happy with my configuration, another avenue might be for someone to install the port coreutils
from MacPorts and then use gdircolors
(source: https://unix.stackexchange.com/a/174596/194343). (I may edit this last part in the future as all the above are related pieces that make every-day life much more fun and easier to cope with.)
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
I wrote a DateTextField component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class DateTextField extends JTextField {
private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
private static final int DIALOG_WIDTH = 200;
private static final int DIALOG_HEIGHT = 200;
private SimpleDateFormat dateFormat;
private DatePanel datePanel = null;
private JDialog dateDialog = null;
public DateTextField() {
this(new Date());
}
public DateTextField(String dateFormatPattern, Date date) {
this(date);
DEFAULT_DATE_FORMAT = dateFormatPattern;
}
public DateTextField(Date date) {
setDate(date);
setEditable(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
addListeners();
}
private void addListeners() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent paramMouseEvent) {
if (datePanel == null) {
datePanel = new DatePanel();
}
Point point = getLocationOnScreen();
point.y = point.y + 30;
showDateDialog(datePanel, point);
}
});
}
private void showDateDialog(DatePanel dateChooser, Point position) {
Frame owner = (Frame) SwingUtilities
.getWindowAncestor(DateTextField.this);
if (dateDialog == null || dateDialog.getOwner() != owner) {
dateDialog = createDateDialog(owner, dateChooser);
}
dateDialog.setLocation(getAppropriateLocation(owner, position));
dateDialog.setVisible(true);
}
private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
JDialog dialog = new JDialog(owner, "Date Selected", true);
dialog.setUndecorated(true);
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
return dialog;
}
private Point getAppropriateLocation(Frame owner, Point position) {
Point result = new Point(position);
Point p = owner.getLocation();
int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());
if (offsetX > 0) {
result.x -= offsetX;
}
if (offsetY > 0) {
result.y -= offsetY;
}
return result;
}
private SimpleDateFormat getDefaultDateFormat() {
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return dateFormat;
}
public void setText(Date date) {
setDate(date);
}
public void setDate(Date date) {
super.setText(getDefaultDateFormat().format(date));
}
public Date getDate() {
try {
return getDefaultDateFormat().parse(getText());
} catch (ParseException e) {
return new Date();
}
}
private class DatePanel extends JPanel implements ChangeListener {
int startYear = 1980;
int lastYear = 2050;
Color backGroundColor = Color.gray;
Color palletTableColor = Color.white;
Color todayBackColor = Color.orange;
Color weekFontColor = Color.blue;
Color dateFontColor = Color.black;
Color weekendFontColor = Color.red;
Color controlLineColor = Color.pink;
Color controlTextColor = Color.white;
JSpinner yearSpin;
JSpinner monthSpin;
JButton[][] daysButton = new JButton[6][7];
DatePanel() {
setLayout(new BorderLayout());
setBorder(new LineBorder(backGroundColor, 2));
setBackground(backGroundColor);
JPanel topYearAndMonth = createYearAndMonthPanal();
add(topYearAndMonth, BorderLayout.NORTH);
JPanel centerWeekAndDay = createWeekAndDayPanal();
add(centerWeekAndDay, BorderLayout.CENTER);
reflushWeekAndDay();
}
private JPanel createYearAndMonthPanal() {
Calendar cal = getCalendar();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH) + 1;
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(controlLineColor);
yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
startYear, lastYear, 1));
yearSpin.setPreferredSize(new Dimension(56, 20));
yearSpin.setName("Year");
yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
yearSpin.addChangeListener(this);
panel.add(yearSpin);
JLabel yearLabel = new JLabel("Year");
yearLabel.setForeground(controlTextColor);
panel.add(yearLabel);
monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
12, 1));
monthSpin.setPreferredSize(new Dimension(35, 20));
monthSpin.setName("Month");
monthSpin.addChangeListener(this);
panel.add(monthSpin);
JLabel monthLabel = new JLabel("Month");
monthLabel.setForeground(controlTextColor);
panel.add(monthLabel);
return panel;
}
private JPanel createWeekAndDayPanal() {
String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
JPanel panel = new JPanel();
panel.setFont(new Font("Arial", Font.PLAIN, 10));
panel.setLayout(new GridLayout(7, 7));
panel.setBackground(Color.white);
for (int i = 0; i < 7; i++) {
JLabel cell = new JLabel(colname[i]);
cell.setHorizontalAlignment(JLabel.RIGHT);
if (i == 0 || i == 6) {
cell.setForeground(weekendFontColor);
} else {
cell.setForeground(weekFontColor);
}
panel.add(cell);
}
int actionCommandId = 0;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 7; j++) {
JButton numBtn = new JButton();
numBtn.setBorder(null);
numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
numBtn.setActionCommand(String
.valueOf(actionCommandId));
numBtn.setBackground(palletTableColor);
numBtn.setForeground(dateFontColor);
numBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JButton source = (JButton) event.getSource();
if (source.getText().length() == 0) {
return;
}
dayColorUpdate(true);
source.setForeground(todayBackColor);
int newDay = Integer.parseInt(source.getText());
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, newDay);
setDate(cal.getTime());
dateDialog.setVisible(false);
}
});
if (j == 0 || j == 6)
numBtn.setForeground(weekendFontColor);
else
numBtn.setForeground(dateFontColor);
daysButton[i][j] = numBtn;
panel.add(numBtn);
actionCommandId++;
}
return panel;
}
private Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate());
return calendar;
}
private int getSelectedYear() {
return ((Integer) yearSpin.getValue()).intValue();
}
private int getSelectedMonth() {
return ((Integer) monthSpin.getValue()).intValue();
}
private void dayColorUpdate(boolean isOldDay) {
Calendar cal = getCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
int i = actionCommandId / 7;
int j = actionCommandId % 7;
if (isOldDay) {
daysButton[i][j].setForeground(dateFontColor);
} else {
daysButton[i][j].setForeground(todayBackColor);
}
}
private void reflushWeekAndDay() {
Calendar cal = getCalendar();
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
String s = "";
if (dayNo >= 1 && dayNo <= maxDayNo) {
s = String.valueOf(dayNo);
}
daysButton[i][j].setText(s);
dayNo++;
}
}
dayColorUpdate(false);
}
public void stateChanged(ChangeEvent e) {
dayColorUpdate(true);
JSpinner source = (JSpinner) e.getSource();
Calendar cal = getCalendar();
if (source.getName().equals("Year")) {
cal.set(Calendar.YEAR, getSelectedYear());
} else {
cal.set(Calendar.MONTH, getSelectedMonth() - 1);
}
setDate(cal.getTime());
reflushWeekAndDay();
}
}
}
If you like to have the timestamp without the timezone but local timezone do
git log -1 --format=%cd --date=local
Which gives this depending on your location
Mon Sep 28 12:07:37 2015
string outString= number.ToString("####0.00");
I guess it should be readability ;)
CROSS APPLY will be somewhat unique for people reading to tell them that a UDF is being used which will be applied to each row from the table on the left.
Ofcourse, there are other limitations where a CROSS APPLY is better used than JOIN which other friends have posted above.
If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating
.
Here's my basic theme that simply modifies some colors with no nested themes:
<style name="AppTheme" parent="Theme.AppCompat">
<item name="colorPrimary">@color/theme_colorPrimary</item>
<item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
<item name="colorAccent">@color/theme_colorAccent</item>
<item name="colorControlActivated">@color/theme_colorControlActivated</item>
<item name="android:windowBackground">@color/theme_bg</item>
<item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
<item name="colorButtonNormal">@color/theme_colorPrimary</item>
<item name="colorControlHighlight">@color/theme_colorAccent</item>
</style>
The answer is right on the error message, you need to indicate that it's standalone and therefore it doesn't conflict with the form controls:
[ngModelOptions]="{standalone: true}"
Well, you have some options.
You could configure sudo to not prompt for a password. This is not recommended, due to the security risks.
You could write an expect script to read the password and supply it to sudo when required, but that's clunky and fragile.
I would recommend designing the script to run as root and drop its privileges whenever they're not needed. Simply have it sudo -u someotheruser command
for the commands that don't require root.
(If they have to run specifically as the user invoking the script, then you could have the script save the uid and invoke a second script via sudo with the id as an argument, so it knows who to su to..)
Simple button css now you can play around with your editor
a {
display: inline-block;
background: #000000c9;
color: #000;
padding: 12px 24px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
}
a:hover {
background:#000
cursor: pointer;
transition: 0.3s ease-in;
}
Link tag
<a href="#">Hover me<a>
There actually seems to be a method in GMap3. It's a static method of the google.maps.geometry.spherical
namespace.
It takes as arguments two LatLng
objects and will utilize a default Earth radius of 6378137 meters, although the default radius can be overridden with a custom value if necessary.
Make sure you include:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
in your head section.
The call will be:
google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
In case anyone needs a (nearly) ready-to-use PHP function, the following is based on this answer:
/**
* Remove a column from a table.
*
* @param string $tableName The table to remove the column from.
* @param string $columnName The column to remove from the table.
*/
public function DropTableColumn($tableName, $columnName)
{
// --
// Determine all columns except the one to remove.
$columnNames = array();
$statement = $pdo->prepare("PRAGMA table_info($tableName);");
$statement->execute(array());
$rows = $statement->fetchAll(PDO::FETCH_OBJ);
$hasColumn = false;
foreach ($rows as $row)
{
if(strtolower($row->name) !== strtolower($columnName))
{
array_push($columnNames, $row->name);
}
else
{
$hasColumn = true;
}
}
// Column does not exist in table, no need to do anything.
if ( !$hasColumn ) return;
// --
// Actually execute the SQL.
$columns = implode('`,`', $columnNames);
$statement = $pdo->exec(
"CREATE TABLE `t1_backup` AS SELECT `$columns` FROM `$tableName`;
DROP TABLE `$tableName`;
ALTER TABLE `t1_backup` RENAME TO `$tableName`;");
}
In contrast to other answers, the SQL used in this approach seems to preserve the data types of the columns, whereas something like the accepted answer seems to result in all columns to be of type TEXT
.
Update 1:
The SQL used has the drawback that autoincrement
columns are not preserved.
The sanctioned way of creating and using child processes is through the subprocess module.
import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl
The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.
You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.
Hope the below code would clarify your doubts :
public static void testString() {
String str = "Hello";
System.out.println("Before String Concat: "+str);
str.concat("World");
System.out.println("After String Concat: "+str);
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Before StringBuffer Append: "+sb);
sb.append("World");
System.out.println("After StringBuffer Append: "+sb);
}
Before String Concat: Hello
After String Concat: Hello
Before StringBuffer Append: Hello
After StringBuffer Append: HelloWorld
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
class EchoClientProtocol(WebSocketClientProtocol):
def sendHello(self):
self.sendMessage("Hello, world!")
def onOpen(self):
self.sendHello()
def onMessage(self, msg, binary):
print "Got echo: " + msg
reactor.callLater(1, self.sendHello)
if __name__ == '__main__':
factory = WebSocketClientFactory("ws://localhost:9000")
factory.protocol = EchoClientProtocol
connectWS(factory)
reactor.run()
No need for moment.js to parse the input since its format is the standard one :
var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');
Another approach is to use ngModelChange
:
Template:
<input type="checkbox" ngModel (ngModelChange)="onChecked(obj, $event)" />
Controller:
onChecked(obj: any, isChecked: boolean){
console.log(obj, isChecked); // {}, true || false
}
I prefer this method because here you get the relevant object and true
/false
values of a checkbox.
Assuming Customer
has a setter for email - myList.get(3).setEmail("[email protected]")
But from what I see you have quite a simple error in syntax
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
the correct syntax would look like
<p th:text="${bean.field + '!' + bean.field}">Static content</p>
As a matter of fact, the syntax th:text="'static part' + ${bean.field}"
is equal to th:text="${'static part' + bean.field}"
.
Try it out. Even though this is probably kind of useless now after 6 months.
Change the file extension of your css file to .less
. You don't need to write any LESS in it; all CSS is valid LESS (except of the MS stuff that you have to escape, but that's another issue.)
Per Fractalf's answer this is fixed in v1.4.0
Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,
rdd = df.rdd.flatMap(list)
or
rdd = df.rdd.flatmap(lambda x: list(x))
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
For those who are not using JPA and instead prefer to exclude the entityManagerFactory and use Spring Data JDBC or Spring JDBC can exclude the bean to avoid the exception
@SpringBootApplication(exclude = {HibernateJpaAutoConfiguration.class})
use typeid(class).name
// illustratory code assuming all includes/namespaces etc
#include <iostream>
#include <typeinfo>
using namespace std;
struct A{};
int main(){
cout << typeid(A).name();
}
It is important to remember that this gives an implementation defined names.
As far as I know, there is no way to get the name of the object at run time reliably e.g. 'A' in your code.
EDIT 2:
#include <typeinfo>
#include <iostream>
#include <map>
using namespace std;
struct A{
};
struct B{
};
map<const type_info*, string> m;
int main(){
m[&typeid(A)] = "A"; // Registration here
m[&typeid(B)] = "B"; // Registration here
A a;
cout << m[&typeid(a)];
}
In JavaScript you can use template literals:
let value = 100;
console.log(`The size is ${ value }`);
Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue
. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:
$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...
$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
Would a dataframe of NA
s work?
something like:
data.frame(matrix(NA, nrow = 2, ncol = 3))
if you need to be more specific about the data type then may prefer: NA_integer_
, NA_real_
, NA_complex_
, or NA_character_
instead of just NA
which is logical
Something else that may be more specific that the NAs
is:
data.frame(matrix(vector(mode = 'numeric',length = 6), nrow = 2, ncol = 3))
where the mode can be of any type. See ?vector
My own class request with wsse authentication
class Request {
protected $_url;
protected $_username;
protected $_apiKey;
public function __construct($url, $username, $apiUserKey) {
$this->_url = $url;
$this->_username = $username;
$this->_apiKey = $apiUserKey;
}
public function getHeader() {
$nonce = uniqid();
$created = date('c');
$digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));
$wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
$wsseHeader .= sprintf(
'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
);
return $wsseHeader;
}
public function curl_req($path, $verb=NULL, $data=array()) {
$wsseHeader[] = "Accept: application/vnd.api+json";
$wsseHeader[] = $this->getHeader();
$options = array(
CURLOPT_URL => $this->_url . $path,
CURLOPT_HTTPHEADER => $wsseHeader,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
if( !empty($data) ) {
$options += array(
CURLOPT_POSTFIELDS => $data,
CURLOPT_SAFE_UPLOAD => true
);
}
if( isset($verb) ) {
$options += array(CURLOPT_CUSTOMREQUEST => $verb);
}
$ch = curl_init();
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if(false === $result ) {
echo curl_error($ch);
}
curl_close($ch);
return $result;
}
}
No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);
This works in all browsers -
new Date('2001/01/31 12:00:00 AM')
new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
I get this error from the sshfs command from Fedora 17 linux to debian linux on the Mindstorms EV3 brick over the LAN and through a wireless connection.
Bash command:
el@defiant /mnt $ sshfs [email protected]:/root -p 22 /mnt/ev3
fuse: bad mount point `/mnt/ev3': Transport endpoint is not connected
This is remedied with the following command and trying again:
fusermount -u /mnt/ev3
These additional sshfs options prevent the above error from concurring:
sudo sshfs -d -o allow_other -o reconnect -o ServerAliveInterval=15 [email protected]:/var/lib/redmine/plugins /mnt -p 12345 -C
In order to use allow_other
above, you need to uncomment the last line in /etc/fuse.conf
:
# Set the maximum number of FUSE mounts allowed to non-root users.
# The default is 1000.
#
#mount_max = 1000
# Allow non-root users to specify the 'allow_other' or 'allow_root'
# mount options.
#
user_allow_other
Source: http://slopjong.de/2013/04/26/sshfs-transport-endpoint-is-not-connected/
C# haven't static variables at all. You can declare static field in the particular type definition via C#. Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static field within a method - method is a scope itself, and items declared in a method must be inaccessible over the method's border.
If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:
-Wno-multichar
I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.
For a customized time and date format:
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
String cDateTime=dateFormat.format(new Date());
Output is like below format: 2015-06-18T10:15:56-05:00
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.This is what I get from console on Windows 10:
C:\>find /?
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.
If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.
The trailing backslash must be the last character on the line for it to be interpreted as a continuation command. No comments or even whitespace are allowed after it.
You should be able to put comment lines in between your commands
# output MYSQLDUMP file
cat ${MYSQLDUMP} | \
# simplify the line
sed '/created_at/d' | \
# create some newlines
tr ",;" "\n" | \
# use some sed magic
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
# more magic
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
# even more magic
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
# I hate phone numbers in my output
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \
# one more sed call and then send it to the CSV file
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}
var statuses = new[] { "A", "B", "C" };
var filteredOrders = from order in orders.Order
where statuses.Contains(order.StatusCode)
select order;
The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found
.
Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing.
Then click ok and run the App.
(Since there is no launcher activity, No app will be show in the Apps menu.).
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>com</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>net</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>org</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
This will allow to connect to .com .net .org
A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.
var Child = {_x000D_
template: '<div>{{value}}</div>',_x000D_
data: function () {_x000D_
return {_x000D_
value: 0_x000D_
};_x000D_
},_x000D_
methods: {_x000D_
setValue(value) {_x000D_
this.value = value;_x000D_
}_x000D_
},_x000D_
created() {_x000D_
this.$emit('handler', this.setValue);_x000D_
}_x000D_
}_x000D_
_x000D_
new Vue({_x000D_
el: '#app',_x000D_
components: {_x000D_
'my-component': Child_x000D_
},_x000D_
methods: {_x000D_
setValueHandler(fn) {_x000D_
this.setter = fn_x000D_
},_x000D_
click() {_x000D_
this.setter(70)_x000D_
}_x000D_
}_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<my-component @handler="setValueHandler"></my-component>_x000D_
<button @click="click">Click</button> _x000D_
</div>
_x000D_
The parent keeps track of the child handler functions and calls whenever necessary.
* Hope This will work for u
System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}
Pressing Ctrl + c while a python program is running will cause python to raise a KeyboardInterrupt
exception. It's likely that a program that makes lots of HTTP requests will have lots of exception handling code. If the except
part of the try
-except
block doesn't specify which exceptions it should catch, it will catch all exceptions including the KeyboardInterrupt
that you just caused. A properly coded python program will make use of the python exception hierarchy and only catch exceptions that are derived from Exception
.
#This is the wrong way to do things
try:
#Some stuff might raise an IO exception
except:
#Code that ignores errors
#This is the right way to do things
try:
#Some stuff might raise an IO exception
except Exception:
#This won't catch KeyboardInterrupt
If you can't change the code (or need to kill the program so that your changes will take effect) then you can try pressing Ctrl + c rapidly. The first of the KeyboardInterrupt
exceptions will knock your program out of the try
block and hopefully one of the later KeyboardInterrupt
exceptions will be raised when the program is outside of a try
block.
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
Not exactly answering the question, but I think this is a better compromise in some situations:
I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was - a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:
printf('<div style="display:none">');
...Third-party stuff here...
printf('</div>');
Warning was still in page source as a reminder to me, but invisible to the client.
JavaScript 1.0
window.location.href = window.location.pathname + window.location.search + window.location.hash;
// creates a history entry
JavaScript 1.1
window.location.replace(window.location.pathname + window.location.search + window.location.hash);
// does not create a history entry
JavaScript 1.2
window.location.reload(false);
// If we needed to pull the document from
// the web-server again (such as where the document contents
// change dynamically) we would pass the argument as 'true'.
Please check that you have <?PHP
at the top of your code. If you forget it, this error will appear.