in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
You can also use TempVars - note '!' syntax is essential
I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Dim SQL As String
SQL = _
"SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
"c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
"FROM tblClient AS c " & _
"WHERE c.ClientID = @ClientID"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
.Parameters.Append prm
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
mstrLastName = Nz(!LastName, "")
mstrFirstName = Nz(!FirstName, "")
mstrMI = Nz(!MI, "")
mdDOB = !DOB
mstrSSN = Nz(!SSN, "")
mlngRaceID = Nz(!RaceID, -1)
mlngEthnicityID = Nz(!EthnicityID, -1)
mlngGenderID = Nz(!GenderID, -1)
mbooDeleted = Deleted
mdRecordDate = Nz(!RecordDate, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.
If you're Lucky only the corrupted item(s) will be lost, if any.
With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools
.
In order to fix that, one should:
Programs and Features
find Visual Studios related version
there, click on it,Change
.
Then the setup window will appear, Web Developer Tools
there and continue to setup.It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools
now.
Mark gravell suggested this if you have .NET Core 3, System.Runtime.Intrinsics.X86.Popcnt.PopCount
public bool IsPowerOfTwo(uint i)
{
return Popcnt.PopCount(i) == 1
}
Single instruction, faster than (x != 0) && ((x & (x - 1)) == 0)
but less portable.
In this example, the line do_something_else()
will not be executed if do_not_continue
is True
. Control will return, instead, to whichever function called some_function
.
def some_function():
if do_not_continue:
return # implicitly, this is the same as saying `return None`
do_something_else()
If anybody still wants this, Java regex for support Unicode? is a good one. It's for when you want ONLY letters (no matter what encoding - japaneese, sweedish) iside an EditText. Later, you can check it using Matcher
and Pattern.compile()
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
The above assumes that you have a folder called CSS
in the root of your website like this:
http://www.website.com/CSS/Style.css
var postData = "text";
$.ajax({
type: "post",
url: "url",
data: postData,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
Another possibility is that the result is not awaited on the client side. This can happen if any one method on the call stack does not use the await keyword to wait for the call to be completed.
Create a serialization surrogate.
Example, you have a class with public property of type Dictionary.
To support Xml serialization of this type, create a generic key-value class:
public class SerializeableKeyValue<T1,T2>
{
public T1 Key { get; set; }
public T2 Value { get; set; }
}
Add an XmlIgnore attribute to your original property:
[XmlIgnore]
public Dictionary<int, string> SearchCategories { get; set; }
Expose a public property of array type, that holds an array of SerializableKeyValue instances, which are used to serialize and deserialize into the SearchCategories property:
public SerializeableKeyValue<int, string>[] SearchCategoriesSerializable
{
get
{
var list = new List<SerializeableKeyValue<int, string>>();
if (SearchCategories != null)
{
list.AddRange(SearchCategories.Keys.Select(key => new SerializeableKeyValue<int, string>() {Key = key, Value = SearchCategories[key]}));
}
return list.ToArray();
}
set
{
SearchCategories = new Dictionary<int, string>();
foreach (var item in value)
{
SearchCategories.Add( item.Key, item.Value );
}
}
}
When you click the Button
if(isset($_POST['save'])){
$sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
**if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}**
}
This will execute the Query in the variable $sql
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
This type of query worked for me:
db.events.aggregate({$group: {_id : "$date", number: { $sum : 1} }} )
See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/
6 years later... I found this post and I liked more the numpy aproach:
import numpy as np
dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')
truncated_dates = dates_array.astype('datetime64[D]')
cheers
You can use rails dbconsole
to view the database that your rails application is using. It's alternative answer rails db
. Both commands will direct you the command line interface and will allow you to use that database query syntax.
http://pchart.sourceforge.net/ looks very good and it's free.
jspdf and Angular 8
I generate a pdf and want to upload the pdf with POST request, this is how I do (For clarity, I delete some of the code and service layer)
import * as jsPDF from 'jspdf';
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient)
upload() {
const pdf = new jsPDF()
const blob = pdf.output('blob')
const formData = new FormData()
formData.append('file', blob)
this.http.post('http://your-hostname/api/upload', formData).subscribe()
}
Another alternative: for 'switch's
' like statements, with a lot of conditions, I like to use maps:
return Card(
elevation: 0,
margin: EdgeInsets.all(1),
child: conditions(widget.coupon)[widget.coupon.status] ??
(throw ArgumentError('invalid status')));
conditions(Coupon coupon) => {
Status.added_new: CheckableCouponTile(coupon.code),
Status.redeemed: SimpleCouponTile(coupon.code),
Status.invalid: SimpleCouponTile(coupon.code),
Status.valid_not_redeemed: SimpleCouponTile(coupon.code),
};
It's easier to add/remove elements to the condition list without touch the conditional statement.
Another example:
var condts = {
0: Container(),
1: Center(),
2: Row(),
3: Column(),
4: Stack(),
};
class WidgetByCondition extends StatelessWidget {
final int index;
WidgetByCondition(this.index);
@override
Widget build(BuildContext context) {
return condts[index];
}
}
a = 0.000006;
b = 6;
c = a/b;
textbox.Text = c.ToString("0.000000");
As you requested:
textbox.Text = c.ToString("0.######");
This will only display out to the 6th decimal place if there are 6 decimals to display.
what platform are you running?..
if its unix, maybe adding
alias java='java -Xmx1g'
to .bashrc (or similar) work
edit: Changing XmX to Xmx
From what I've learned with Alex Cowan in the course Continuous Delivery & DevOps, CI and CD is part of a product pipeline that consists in the time it goes from an Observations to a Released Product.
From Observations to Designs the goal is to get high quality testable ideas. This part of the process is considered Continuous Design.
What happens after, when we go from the Code onwards, it's considered a Continuous Delivery capability whose aim is to execute the ideas and release to the customer very fast (you can read Jez Humble's book Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation for more details). The following pipeline explains which steps Continuous Integration (CI) and Continuous Delivery (CD) consist of.
Continuous Integration, as Mattias Petter Johansson explains,
is when a software team has habit of doing multiple merges per day and they have an automated verification system in place to check those merges for problems.
(you can watch the following two videos for a more pratical overview using CircleCI - Getting started with CircleCI - Continuous Integration P2 and Running CircleCI on Pull Request).
One can specify the CI/CD pipeline as following, that goes from New Code to a released Product.
The first three steps have to do with Tests, extending the boundary of what's being tested.
Continuous Deployment, on the other hand, is to handle the Deployment automatically. So, any code commit that passes the automated testing phase is automatically released into the production.
Note: This isn't necessarily what your pipelines should look like, yet they can serve as reference.
In Linux, it was solved by opening PyCharm from the terminal and leaving it open. After that, I was able to choose the correct interpreter in preferences. In my case, linked to a virtual environment (venv).
Had a problem on IIS 8 when retrieving Content via Ajax. The issue was that MaximumWorkerProcesses
was set to 2
and Javascript opened 17 concurrent requests. That was more than the AppPool could handle and a new pool (without auth-data) was opened.
Solution was to Change MaximumWorkerProcesses
to 0
in IIS -> Server -> Application Pools -> [myPool] -> Advanced Settings -> Process Model -> MaximumWorkerProcesses
.
If you are using C function fgetc
then you should check a next character whether it is equal to the new line character or to EOF. For example
unsigned int count = 0;
while ( 1 )
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
if ( c == EOF ) break;
}
else
{
++count;
}
}
or maybe it would be better to rewrite the code using do-while loop. For example
unsigned int count = 0;
do
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
}
else
{
++count;
}
} while ( c != EOF );
Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc
to read lines of a file.
But if the program is written in C++ then it would be much better if you would use std::ifstream
and std::string
classes and function std::getline
to read a whole line.
Try this:
0,30 * * * * your command goes here
According to the official Mac OS X crontab(5) manpage, the /
syntax is supported. Thus, to figure out why it wasn't working for you, you'll need to look at the logs for cron. In those logs, you should find a clear failure message.
Note: Mac OS X appears to use Vixie Cron, the same as Linux and the BSDs.
Note here i am using custom cell this code is perfectly working for me
@IBAction func call(sender: UIButton)
{
var contentView = sender.superview;
var cell = contentView?.superview as EmployeeListCustomCell
if (!(cell.isKindOfClass(EmployeeListCustomCell)))
{
cell = (contentView?.superview)?.superview as EmployeeListCustomCell
}
let phone = cell.lblDescriptionText.text!
//let phone = detailObject!.mobile!
let url:NSURL = NSURL(string:"tel://"+phone)!;
UIApplication.sharedApplication().openURL(url);
}
I've found also a nice and simple way to address hostsvars right on one of Ansible's Github issues
Looks like you can do this as well:
- debug:
msg: "{{ ansible_ssh_host }}"
For a hosted environment (that's the normal one), the C11 standard (ISO/IEC 9899:2011) says:
5.1.2.2.1 Program startup
The function called at program startup is named
main
. The implementation declares no prototype for this function. It shall be defined with a return type ofint
and with no parameters:int main(void) { /* ... */ }
or with two parameters (referred to here as
argc
andargv
, though any names may be used, as they are local to the function in which they are declared):int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
If they are declared, the parameters to the main function shall obey the following constraints:
- The value of
argc
shall be nonnegative.argv[argc]
shall be a null pointer.- If the value of
argc
is greater than zero, the array membersargv[0]
throughargv[argc-1]
inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.- If the value of
argc
is greater than zero, the string pointed to byargv[0]
represents the program name;argv[0][0]
shall be the null character if the program name is not available from the host environment. If the value ofargc
is greater than one, the strings pointed to byargv[1]
throughargv[argc-1]
represent the program parameters.- The parameters
argc
andargv
and the strings pointed to by theargv
array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.10) Thus,
int
can be replaced by a typedef name defined asint
, or the type ofargv
can be written aschar **argv
, and so on.
The value returned from main()
is transmitted to the 'environment' in an implementation-defined way.
5.1.2.2.3 Program termination
1 If the return type of the
main
function is a type compatible withint
, a return from the initial call to themain
function is equivalent to calling theexit
function with the value returned by themain
function as its argument;11) reaching the}
that terminates themain
function returns a value of 0. If the return type is not compatible withint
, the termination status returned to the host environment is unspecified.11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in
main
will have ended in the former case, even where they would not have in the latter.
Note that 0
is mandated as 'success'. You can use EXIT_FAILURE
and EXIT_SUCCESS
from <stdlib.h>
if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.
In C89 (and hence in Microsoft C), there is no statement about what happens if the main()
function returns but does not specify a return value; it therefore leads to undefined behaviour.
7.22.4.4 The
exit
function¶5 Finally, control is returned to the host environment. If the value of
status
is zero orEXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned. If the value ofstatus
isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
The C++11 standard (ISO/IEC 14882:2011) says:
3.6.1 Main function [basic.start.main]
¶1 A program shall contain a global function called main, which is the designated start of the program. [...]
¶2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation defined. All implementations shall allow both of the following definitions of main:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
In the latter form
argc
shall be the number of arguments passed to the program from the environment in which the program is run. Ifargc
is nonzero these arguments shall be supplied inargv[0]
throughargv[argc-1]
as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) andargv[0]
shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or""
. The value ofargc
shall be non-negative. The value ofargv[argc]
shall be 0. [ Note: It is recommended that any further (optional) parameters be added afterargv
. —end note ]¶3 The function
main
shall not be used within a program. The linkage (3.5) ofmain
is implementation-defined. [...]¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling
std::exit
with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executingreturn 0;
The C++ standard explicitly says "It [the main function] shall have a return type of type int
, but otherwise its type is implementation defined", and requires the same two signatures as the C standard to be supported as options. So a 'void main()' is directly not allowed by the C++ standard, though there's nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling main
(but the C standard does not).
There's a paragraph of §18.5 Start and termination in the C++11 standard that is identical to the paragraph from §7.22.4.4 The exit
function in the C11 standard (quoted above), apart from a footnote (which simply documents that EXIT_SUCCESS
and EXIT_FAILURE
are defined in <cstdlib>
).
Classically, Unix systems support a third variant:
int main(int argc, char **argv, char **envp) { ... }
The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via 'extern char **environ;
'. This global variable is unique among those in POSIX in that it does not have a header that declares it.
This is recognized by the C standard as a common extension, documented in Annex J:
J.5.1 Environment arguments
¶1 In a hosted environment, the main function receives a third argument,
char *envp[]
, that points to a null-terminated array of pointers tochar
, each of which points to a string that provides information about the environment for this execution of the program (5.1.2.2.1).
The Microsoft VS 2010 compiler is interesting. The web site says:
The declaration syntax for main is
int main();
or, optionally,
int main(int argc, char *argv[], char *envp[]);
Alternatively, the
main
andwmain
functions can be declared as returningvoid
(no return value). If you declaremain
orwmain
as returning void, you cannot return an exit code to the parent process or operating system by using a return statement. To return an exit code whenmain
orwmain
is declared asvoid
, you must use theexit
function.
It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with void main()
does exit — and the MS web site is silent too.
Interestingly, MS does not prescribe the two-argument version of main()
that the C and C++ standards require. It only prescribes a three argument form where the third argument is char **envp
, a pointer to a list of environment variables.
The Microsoft page also lists some other alternatives — wmain()
which takes wide character strings, and some more.
The Microsoft Visual Studio 2005 version of this page does not list void main()
as an alternative. The versions from Microsoft Visual Studio 2008 onwards do.
As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called main
and there are no constraints on its return type. The standard says:
5.1.2 Execution environments
Two execution environments are defined: freestanding and hosted. In both cases, program startup occurs when a designated C function is called by the execution environment. All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment.
5.1.2.1 Freestanding environment
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined.
The effect of program termination in a freestanding environment is implementation-defined.
The cross-reference to clause 4 Conformance refers to this:
¶5 A strictly conforming program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.
¶6 The two forms of conforming implementation are hosted and freestanding. A conforming hosted implementation shall accept any strictly conforming program. A conforming freestanding implementation shall accept any strictly conforming program in which the use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers
<float.h>
,<iso646.h>
,<limits.h>
,<stdalign.h>
,<stdarg.h>
,<stdbool.h>
,<stddef.h>
,<stdint.h>
, and<stdnoreturn.h>
. A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any strictly conforming program.4)¶7 A conforming program is one that is acceptable to a conforming implementation.5)
3) A strictly conforming program can use conditional features (see 6.10.8.3) provided the use is guarded by an appropriate conditional inclusion preprocessing directive using the related macro. For example:
#ifdef __STDC_IEC_559__ /* FE_UPWARD defined */ /* ... */ fesetround(FE_UPWARD); /* ... */ #endif
4) This implies that a conforming implementation reserves no identifiers other than those explicitly reserved in this International Standard.
5) Strictly conforming programs are intended to be maximally portable among conforming implementations. Conforming programs may depend upon non-portable features of a conforming implementation.
It is noticeable that the only header required of a freestanding environment that actually defines any functions is <stdarg.h>
(and even those may be — and often are — just macros).
Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.)
1.4 Implementation compliance [intro.compliance]
¶7 Two kinds of implementations are defined: a hosted implementation and a freestanding implementation. For a hosted implementation, this International Standard defines the set of available libraries. A freestanding implementation is one in which execution may take place without the benefit of an operating system, and has an implementation-defined set of libraries that includes certain language-support libraries (17.6.1.3).
¶8 A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.
¶9 Each implementation shall include documentation that identifies all conditionally-supported constructs that it does not support and defines all locale-specific characteristics.3
3) This documentation also defines implementation-defined behavior; see 1.9.
17.6.1.3 Freestanding implementations [compliance]
Two kinds of implementations are defined: hosted and freestanding (1.4). For a hosted implementation, this International Standard describes the set of available headers.
A freestanding implementation has an implementation-defined set of headers. This set shall include at least the headers shown in Table 16.
The supplied version of the header
<cstdlib>
shall declare at least the functionsabort
,atexit
,at_quick_exit
,exit
, andquick_exit
(18.5). The other headers listed in this table shall meet the same requirements as for a hosted implementation.Table 16 — C++ headers for freestanding implementations
Subclause Header(s) <ciso646> 18.2 Types <cstddef> 18.3 Implementation properties <cfloat> <limits> <climits> 18.4 Integer types <cstdint> 18.5 Start and termination <cstdlib> 18.6 Dynamic memory management <new> 18.7 Type identification <typeinfo> 18.8 Exception handling <exception> 18.9 Initializer lists <initializer_list> 18.10 Other runtime support <cstdalign> <cstdarg> <cstdbool> 20.9 Type traits <type_traits> 29 Atomics <atomic>
int main()
in C?The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — int main(void)
— but there are also two examples in the standard which show int main()
: §6.5.3.4 ¶8 and §6.7.6.3 ¶20. Now, it is important to note that examples are not 'normative'; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes int main()
in an example, it suggests that int main()
is not forbidden, even if it is not the preferred notation.
6.5.3.4 The
sizeof
and_Alignof
operators…
¶8 EXAMPLE 3 In this example, the size of a variable length array is computed and returned from a function:
#include <stddef.h> size_t fsize3(int n) { char b[n+3]; // variable length array return sizeof b; // execution time sizeof } int main() { size_t size; size = fsize3(10); // fsize3 returns 13 return 0; }
Well if you want fully transparent than you can use
border: 5px solid transparent;
If you mean opaque/transparent, than you can use
border: 5px solid rgba(255, 255, 255, .5);
Here, a
means alpha, which you can scale, 0-1.
Also some might suggest you to use opacity
which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba
seems better than using opacity
.
For older browsers, always declare the background color using #
(hex) just as a fall back, so that if old browsers doesn't recognize the rgba
, they will apply the hex
color to your element.
Demo 2 (With a background image for nested div)
Demo 3 (With an img
tag instead of a background-image
)
body {
background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);
}
div.wrap {
border: 5px solid #fff; /* Fall back, not used in fiddle */
border: 5px solid rgba(255, 255, 255, .5);
height: 400px;
width: 400px;
margin: 50px;
border-radius: 50%;
}
div.inner {
background: #fff; /* Fall back, not used in fiddle */
background: rgba(255, 255, 255, .5);
height: 380px;
width: 380px;
border-radius: 50%;
margin: auto; /* Horizontal Center */
margin-top: 10px; /* Vertical Center ... Yea I know, that's
manually calculated*/
}
Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.
The above error run the commend line\
please change the command $ node server it's working and server is started
Here's a batch file, called base64encode.bat, that encodes base64.
@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con
(
set base64tmp=base64.tmp
certutil -encode "%1" %base64tmp% > nul
findstr /v /c:- %base64tmp%
erase %base64tmp%
) > %base64out%
Using the selectedOptions property (HTML5) you can get the selected option(s)
document.getElementbyId("id").selectedOptions;
With JQuery can be achieved by doing this
$("#id")[0].selectedOptions;
or
$("#id").prop("selectedOptions");
The property contains an HTMLCollection array similitar to this one selected option
[<option value=?"1">?ABC</option>]
or multiple selections
[<option value=?"1">?ABC</option>, <option value=?"2">?DEF</option> ...]
control + shift + F will do the work
@uvsmtid Your post finally lead me into the right direction
:
simply deleting (actually renaming) the public key file id_rsa.pub
solved the problem for me, that git was working though nagging about invalid format.
Not quite sure, yet the file is not actually needed, since the pub key can be extracted from private key file id_rsa
anyway.
In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:
private static final char[] DIGITS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return DIGITS[digitValue];
}
Or, equivalently:
private static int ASCII_ZERO = 0x30;
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return ((char) (digitValue + ASCII_ZERO));
}
Look at error_reporting directive in php.ini.
Sometimes clear will not work. Use float: none
as an override
Just add !
before an exclusion rule.
According to the gitignore man page:
Patterns have the following format:
...
- An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified his example to do this here: http://jsfiddle.net/QLfMU/116/
using Dollar is simple as typing:
@Test
public void repeatString() {
String string = "abc";
assertThat($(string).repeat(3).toString(), is("abcabcabc"));
}
PS: repeat works also for array, List, Set, etc
Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.
In one case, I found that query
worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.
I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query
could be faster than prepare
& execute
because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.
Given a couple rare conditions:
If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.
If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.
PDO::lastInsertId
is not supported by the Microsoft ODBC driver.
Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:
To start, I've created a basic table in Microsoft SQL Server
CREATE TABLE performancetest (
sid INT IDENTITY PRIMARY KEY,
id INT,
val VARCHAR(100)
);
And now a basic timed test for performance metrics.
$logs = [];
$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
$start = microtime(true);
$i = 0;
while ($i < $count) {
$sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
if ($type === 'query') {
$smt = $pdo->query($sql);
} else {
$smt = $pdo->prepare($sql);
$smt ->execute();
}
$sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
$i++;
}
$total = (microtime(true) - $start);
$logs[$type] []= $total;
echo "$total $type\n";
};
$trials = 15;
$i = 0;
while ($i < $trials) {
if (random_int(0,1) === 0) {
$test('query');
} else {
$test('prepare');
}
$i++;
}
foreach ($logs as $type => $log) {
$total = 0;
foreach ($log as $record) {
$total += $record;
}
$count = count($log);
echo "($count) $type Average: ".$total/$count.PHP_EOL;
}
I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query
than prepare
/execute
5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769
I'm curious to see how this test compares in other environments, like MySQL.
If you want to have lists only when they are necessary, and values in any other cases, then you can do this:
class DictList(dict):
def __setitem__(self, key, value):
try:
# Assumes there is a list on the key
self[key].append(value)
except KeyError: # If it fails, because there is no key
super(DictList, self).__setitem__(key, value)
except AttributeError: # If it fails because it is not a list
super(DictList, self).__setitem__(key, [self[key], value])
You can then do the following:
dl = DictList()
dl['a'] = 1
dl['b'] = 2
dl['b'] = 3
Which will store the following {'a': 1, 'b': [2, 3]}
.
I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:
my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
rev_med[v] = k
Which will generate the same output as above: {'a': 1, 'b': [2, 3]}
.
CAVEAT: This implementation relies on the non-existence of the append
method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,
dl = DictList()
dl['a'] = 1
dl['b'] = [2]
dl['b'] = 3
would produce the same result as before {'a': 1, 'b': [2, 3]}
, but one might expected the following: {'a': 1, 'b': [[2], 3]}
.
If you want to transpose a matrix like A = np.array([[1,2],[3,4]]), then you can simply use A.T, but for a vector like a = [1,2], a.T does not return a transpose! and you need to use a.reshape(-1, 1), as below
import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))
A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)
You can check for text in your page source as follow:
Assert.IsTrue(driver.PageSource.Contains("Your Text Here"))
Containers will already generally wrap their content nicely. It often doesn't work as well the other way around: children don't fill their ancestors nicely. So, set your width/height values on the inner-most element rather than the outer-most element, and let the outer elements wrap their contents.
.container {
background: blue;
padding: 10px;
}
img {
display: block;
max-height: 200px;
max-width: 200px;
}
Instead of this:
var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };
List <var> list = new List<var>();
list.Add(o);
list.Add(o1);
You could do this:
var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };
List<object> list = new List<object>();
list.Add(o);
list.Add(o1);
However, you will get a compiletime error if you try to do something like this in another scope, although it works at runtime:
private List<object> GetList()
{
List<object> list = new List<object>();
var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };
list.Add(o);
list.Add(o1);
return list;
}
private void WriteList()
{
foreach (var item in GetList())
{
Console.WriteLine("Name={0}{1}", item.Name, Environment.NewLine);
}
}
The problem is that only the members of Object are available at runtime, although intellisense will show the properties id and name.
In .net 4.0 a solution is to use the keyword dynamic istead of object in the code above.
Another solution is to use reflection to get the properties
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
var anonymous = p.GetList(new[]{
new { Id = 1, Name = "Foo" },
new { Id = 2, Name = "Bar" }
});
p.WriteList(anonymous);
}
private List<T> GetList<T>(params T[] elements)
{
var a = TypeGenerator(elements);
return a;
}
public static List<T> TypeGenerator<T>(T[] at)
{
return new List<T>(at);
}
private void WriteList<T>(List<T> elements)
{
PropertyInfo[] pi = typeof(T).GetProperties();
foreach (var el in elements)
{
foreach (var p in pi)
{
Console.WriteLine("{0}", p.GetValue(el, null));
}
}
Console.ReadLine();
}
}
}
The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E>
interface ... which the article notes):
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
This error also appears if the partition on which tmpdir
resides fills up (due to an alter table or other
Depends on how you hid it.
If you used the CSS visibility
value then
$('#test1').css('visibility', 'visible');
If you used CSS `display'
$('#test1').css('display', 'block'); //or inline or any of the other combos
You might even have made it opacity = 0
$('#test1').css('opacity', '1');
You can use SQL Management Objects to perform this. These are the same objects that Management Studio uses to execute queries. I believe Server.ConnectionContext.ExecuteNonQuery()
will perform what you need.
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
This solution appears better to me, regarding maintainability and design for change:
Create the logging property file embedding it in the resource project folder, to be included in the jar file:
# Logging
handlers = java.util.logging.ConsoleHandler
.level = ALL
# Console Logging
java.util.logging.ConsoleHandler.level = ALL
Load the property file from code:
public static java.net.URL retrieveURLOfJarResource(String resourceName) {
return Thread.currentThread().getContextClassLoader().getResource(resourceName);
}
public synchronized void initializeLogger() {
try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException e) {
// ...
}
}
It's a new feature of ECMAScript 5. John Resig wrote up a nice summary of it.
It's just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this:
"use strict";
Putting it in your code now shouldn't cause any problems with current browsers as it's just a string. It may cause problems with your code in the future if your code violates the pragma. For instance, if you currently have foo = "bar"
without defining foo
first, your code will start failing...which is a good thing in my opinion.
If you want to write bytes then you should open the file in binary mode.
f = open('/tmp/output', 'wb')
To add the background for all cells (using Maciej's answer):
for (int section = 0; section < [self.tableView numberOfSections]; section++) {
for (int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
//stuff to do with each cell
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
}
}
If it's php 7 on ubuntu, try this
apt-get install php7.0-curl
/etc/init.d/apache2 restart
I had a similar error, but in my case the cause was file renaming. I was creating a gzipped file file1.tar.gz
and repeatedly updating it in another tarfile with tar -uvf ./combined.tar ./file1.tar.gz
. I got the unexpected EOF error when after untarring combined.tar
and trying to untar file1.tar.gz
.
I noticed there was a difference in the output of file
before and after tarring:
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file1.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
$tar xvf combined.tar
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file_old.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
So, it appears that the file had a different name when I originally created combined.tar
, and using the tar update function doesn't overwrite the metadata for the gzipped filename. The solution was to recreate combined.tar
from scratch instead of updating it.
I still don't know exactly what happened, since changing the name of a gzipped file doesn't normally break it.
Put the iframe
inside the <p>
and make the iframe
CSS
float:left;
display:inline-block;
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values. e.g.,
name varchar(10)
will reserve 6 bytes of memory even if the name is 'Ravi__', whereas
name varchar2(10)
will reserve space according to the length of the input string. e.g., 4 bytes of memory for 'Ravi__'.
Here, _ represents NULL.
NOTE: varchar will reserve space for null values and varchar2 will not reserve any space for null values.
If you are using the Support Library provided DrawerLayout as suggested in the Creating a navigation drawer training, you can use the newly added android.support.v7.app.ActionBarDrawerToggle (note: different from the now deprecated android.support.v4.app.ActionBarDrawerToggle):
shows a Hamburger icon when drawer is closed and an arrow when drawer is open. It animates between these two states as the drawer opens.
While the training hasn't been updated to take the deprecation/new class into account, you should be able to use it almost exactly the same code - the only difference in implementing it is the constructor.
Jackson has to know in what order to pass fields from a JSON object to the constructor. It is not possible to access parameter names in Java using reflection - that's why you have to repeat this information in annotations.
If you use sass in your own project, you can override the default bootstrap gutter size by copy pasting the sass variables from bootstrap's _variables.scss file into your own projects sass file somewhere, like:
// Grid columns
//
// Set the number of columns and specify the width of the gutters.
$grid-gutter-width-base: 50px !default;
$grid-gutter-widths: (
xs: $grid-gutter-width-base,
sm: $grid-gutter-width-base,
md: $grid-gutter-width-base,
lg: $grid-gutter-width-base,
xl: $grid-gutter-width-base
) !default;
Now your gutters will be 50px instead of 30px. I find this to be the cleanest method to adjust the gutter size.
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
If it is SQL Server 2017 or SQL Server Vnext, SQL Azure you can use string_agg
as below:
select id, string_agg(concat(name, ':', [value]), ', ')
from #YourTable
group by id
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
I don't know if this helps, but when you subclass (including anonymously) a generic type, the type information is available via reflection. e.g.,
public abstract class Foo<E> {
public E instance;
public Foo() throws Exception {
instance = ((Class)((ParameterizedType)this.getClass().
getGenericSuperclass()).getActualTypeArguments()[0]).newInstance();
...
}
}
So, when you subclass Foo, you get an instance of Bar e.g.,
// notice that this in anonymous subclass of Foo
assert( new Foo<Bar>() {}.instance instanceof Bar );
But it's a lot of work, and only works for subclasses. Can be handy though.
If You are using rvm, then try the following command:
rvmsudo gem install bundler
According to another question: Could not find rails (>= 0) amongst [] (Gem::LoadError)
Hope it helped, Cheers
This implementation wrap entity exception to exception with detail text.
It handles DbEntityValidationException
, DbUpdateException
, datetime2
range errors (MS SQL), and include key of invalid entity in message (useful when savind many entities at one SaveChanges
call).
First, override SaveChanges
in DbContext class:
public class AppDbContext : DbContext
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbEntityValidationException dbEntityValidationException)
{
throw ExceptionHelper.CreateFromEntityValidation(dbEntityValidationException);
}
catch (DbUpdateException dbUpdateException)
{
throw ExceptionHelper.CreateFromDbUpdateException(dbUpdateException);
}
}
ExceptionHelper class:
public class ExceptionHelper
{
public static Exception CreateFromEntityValidation(DbEntityValidationException ex)
{
return new Exception(GetDbEntityValidationMessage(ex), ex);
}
public static string GetDbEntityValidationMessage(DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
return exceptionMessage;
}
public static IEnumerable<Exception> GetInners(Exception ex)
{
for (Exception e = ex; e != null; e = e.InnerException)
yield return e;
}
public static Exception CreateFromDbUpdateException(DbUpdateException dbUpdateException)
{
var inner = GetInners(dbUpdateException).Last();
string message = "";
int i = 1;
foreach (var entry in dbUpdateException.Entries)
{
var entry1 = entry;
var obj = entry1.CurrentValues.ToObject();
var type = obj.GetType();
var propertyNames = entry1.CurrentValues.PropertyNames.Where(x => inner.Message.Contains(x)).ToList();
// check MS SQL datetime2 error
if (inner.Message.Contains("datetime2"))
{
var propertyNames2 = from x in type.GetProperties()
where x.PropertyType == typeof(DateTime) ||
x.PropertyType == typeof(DateTime?)
select x.Name;
propertyNames.AddRange(propertyNames2);
}
message += "Entry " + i++ + " " + type.Name + ": " + string.Join("; ", propertyNames.Select(x =>
string.Format("'{0}' = '{1}'", x, entry1.CurrentValues[x])));
}
return new Exception(message, dbUpdateException);
}
}
Add spring.profiles.active=tests
in your application.properties file, you can add multiple properties file in your spring boot application like application-stage.properties
, application-prod.properties
, etc. And you can specify in your application.properties file while file to refer by adding spring.profiles.active=stage
or spring.profiles.active=prod
you can also pass the profile at the time running the spring boot application by providing the command:
java -jar
-Dspring.profiles.active=local
build/libs/turtle-rnr-0.0.1-SNAPSHOT.jar
According to the profile name the properties file is picked up, in the above case passing profile local
consider the application-local.properties
file
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
if your intention is send the full array from the html to the controller, can use this:
from the blade.php:
<input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}">
in controller
public function Get(Request $req) {
$quotation = array('quotation' => json_decode($req->quotation));
//or
return view('quotation')->with('quotation',json_decode($req->quotation))
}
You can use the following:
Jedi Code Library provides an enhanced StringList with built-in Split function, that is capable of both adding and replacing the existing text. It also provides reference-counted interface. So this can be used even with older Delphi versions that have no SplitStrings and without careful and a bit tedious customizations of stock TStringList to only use specified delimiters.
For example given text file of lines like Dog 5 4 7
one can parse them using:
var slF, slR: IJclStringList; ai: TList<integer>; s: string; i: integer;
action: procedure(const Name: string; Const Data: array of integer);
slF := TJclStringList.Create; slF.LoadFromFile('some.txt');
slR := TJclStringList.Create;
for s in slF do begin
slR.Split(s, ' ', true);
ai := TList<Integer>.Create;
try
for i := 1 to slR.Count - 1 do
ai.Add(StrToInt(slR[i]));
action(slR[0], ai.ToArray);
finally ai.Free; end;
end;
http://wiki.delphi-jedi.org/wiki/JCL_Help:IJclStringList.Split@string@string@Boolean
Make sure you have MainActivity
and .ScanActivity
into your AndroidManifest.xml
file:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ScanActivity">
</activity>
From javadoc:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself
The error No provider for NameService
is a common issue that many Angular2 beginners face.
Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:
Solution:
@NgModule({
imports: [...],
providers: [CustomServiceName]
})
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
The problem is arising as unsigned char is a 4 byte number not a 1 byte number as many think, so change it to
union {
unsigned int integer;
char byte[4];
} temp32bitint;
and cast while printing, to prevent promoting to 'int' (which C does by default)
printf("%u, %u \n", (unsigned char)Buffer[0], (unsigned char)Buffer[1]);
Here is a C function that handles positive OR negative integer OR fractional values for BOTH OPERANDS
#include <math.h>
float mod(float a, float N) {return a - N*floor(a/N);} //return in range [0, N)
This is surely the most elegant solution from a mathematical standpoint. However, I'm not sure if it is robust in handling integers. Sometimes floating point errors creep in when converting int -> fp -> int.
I am using this code for non-int s, and a separate function for int.
NOTE: need to trap N = 0!
Tester code:
#include <math.h>
#include <stdio.h>
float mod(float a, float N)
{
float ret = a - N * floor (a / N);
printf("%f.1 mod %f.1 = %f.1 \n", a, N, ret);
return ret;
}
int main (char* argc, char** argv)
{
printf ("fmodf(-10.2, 2.0) = %f.1 == FAIL! \n\n", fmodf(-10.2, 2.0));
float x;
x = mod(10.2f, 2.0f);
x = mod(10.2f, -2.0f);
x = mod(-10.2f, 2.0f);
x = mod(-10.2f, -2.0f);
return 0;
}
(Note: You can compile and run it straight out of CodePad: http://codepad.org/UOgEqAMA)
Output:
fmodf(-10.2, 2.0) = -0.20 == FAIL!
10.2 mod 2.0 = 0.2
10.2 mod -2.0 = -1.8
-10.2 mod 2.0 = 1.8
-10.2 mod -2.0 = -0.2
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
If you wish to see all changes made in commits that changed a particular file (rather than just the changes to the file itself), you can pass --full-diff
:
git log -p --full-diff [branch] -- <path>
If you want to intelligently handle missing parameters you can do something like:
IF %1.==. GOTO No1
IF %2.==. GOTO No2
... do stuff...
GOTO End1
:No1
ECHO No param 1
GOTO End1
:No2
ECHO No param 2
GOTO End1
:End1
Here is the simplest way:
<select name="ab" onchange="if (this.selectedIndex) doSomething();">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
Works both with mouse selection and keyboard Up/Down keys whes select is focused.
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
May be not quite what you were looking for but how about using conditional formatting functionality of Excel
EDIT: As an alternate you could create a vba function that acts as a formula that will do the calulation for you. something like
Function getBucket(rng As Range) As String
Dim strReturn As String
Select Case rng.Value
Case 0 to 10
strReturn = "Small"
Case 11 To 20
strReturn = "Medium"
Case 21 To 30
strReturn = "Large"
Case 31 To 40
strReturn = "Huge"
Case Else
strReturn = "OMG!!!"
End Select
getBucket = strReturn
End Function
If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.
The following command creates the self signed certificate and key needed for apache and works fine in windows:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt
For me, turns out I was setting Access-Control-Allow-Origin
response header to a specific (and the correct) host.com
but it had to be returned as http://host.com
instead. What does firefox do? It silently swallows the GET request and returns a status 0 to the XHR, with no warnings output to the javascript console, whereas for other similar failures it would at least say something. Ai ai.
With the Android Studio default generated Activity superclass is ActionBarActivity
and then, none of solution in other responses works. To solve just change superclass:
public class xxxActivity extends ActionBarActivity{
to:
public class xxxActivity extends Activity {
This is the method I like to use as well but I believe you need to add the bool true parameter to the clone method in order for any events to remain attached with the new object and you need to clear the contents.
var input = $("#fileInput");
function clearInput() {
input = input.val('').clone(true);
};
Please check my working code.
function sendMail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => '[email protected]', // change it to yours
'smtp_pass' => 'xxx', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$message = '';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('[email protected]'); // change it to yours
$this->email->to('[email protected]');// change it to yours
$this->email->subject('Resume from JobsBuddy for your Job posting');
$this->email->message($message);
if($this->email->send())
{
echo 'Email sent.';
}
else
{
show_error($this->email->print_debugger());
}
}
declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()
select
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date
In this query, I worked out the result came from current date of the day.
You can do it using a unicode character also
System.out.print('\u0022' + "Hello" + '\u0022');
like Paul said, use
conda create --prefix=/users/.../yourEnvName python=x.x
if you are located in the folder in which you want to create your virtual environment, just omit the path and use
conda create --prefix=yourEnvName python=x.x
conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with
source activate yourEnvName
you can use this query to do the above task
DECLARE @test NVARCHAR(max)
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test SELECT field2= @test
for detail and step by step explanation visit the following link
http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html
function extractKeyValue(obj, value) {
return Object.keys(obj)[Object.values(obj).indexOf(value)];
}
Made for closure compiler to extract key name which will be unknown after compilation
More sexy version but using future Object.entries
function
function objectKeyByValue (obj, val) {
return Object.entries(obj).find(i => i[1] === val);
}
indentation is important in Python. Your if else statement should be within triple arrow (>>>), In Mac python IDLE version 3.7.4 elif statement doesn't comes with correct indentation when you go on next line you have to shift left to avoid syntax error.
You can use the minsize
and maxsize
to set a minimum & maximum size, for example:
def __init__(self,master):
master.minsize(width=666, height=666)
master.maxsize(width=666, height=666)
Will give your window a fixed width & height of 666 pixels.
Or, just using minsize
def __init__(self,master):
master.minsize(width=666, height=666)
Will make sure your window is always at least 666 pixels large, but the user can still expand the window.
According to the GNU make
manual:
CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).
src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.
CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.
These variables are used by the implicit rules of make
Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.
src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules
This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12
but Excel.XlFileFormat.xlOpenXMLWorkbook
. The actual C# command was
excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
I hope this helps someone else in the future.
Missing.Value
is found in the System.Reflection
namespace.
Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:
wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
echo "Sorry you are Offline"
exit 1
fi
Notice how instead of -ne
, you can just use !=
. In an arithmetic context, we don't even have to prepend $
to parameters, i.e.,
var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"
works perfectly fine. This doesn't appply to the $?
special parameter, though.
Further, since (( ... ))
evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to
if (( $? )); then
but this might confuse more people than the keystrokes saved are worth.
The (( ... ))
construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).
This all being said, it's better to avoid $?
altogether in my opinion, as in Cole's answer and Steven's answer.
To prevent "max" and "min" to be listed in a "for ... in" loop:
Object.defineProperty(Array.prototype, "max", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return Math.max.apply(null, this);
}
});
Object.defineProperty(Array.prototype, "min", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return Math.min.apply(null, this);
}
});
Usage:
var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5
Note that you have to be careful if your row contains a factor. Here is an example:
df_1 = data.frame(V1 = factor(11:15),
V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns
[1] 1 21
Here is another example (by default data.frame() converts characters to factors)
df_2 = data.frame(V1 = letters[1:5],
V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"
To prevent this behavior, you need to take care of the factor, before extracting it:
df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11 21
df_2[3,] %>% as.character()
[1] "c" "3"
Slightly different from what you described, but I think this might be what you actually need:
svn blame filename
It will print the file with each line prefixed by the time and author of the commit that last changed it.
In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.
Right click your project file on the Solution Explorer, select Add
, then New item
(or CTRL+SHIFT+A). There you can find Application Manifest File
.
The file name is app.manifest.
What you can do is use nltk to tokenize words and then store all of the words in a list, here's what I did. If you don't know nltk; it stands for natural language toolkit and is used to process natural language. Here's some resource if you wanna get started [http://www.nltk.org/book/]
import nltk
from nltk.tokenize import word_tokenize
file = open("abc.txt",newline='')
result = file.read()
words = word_tokenize(result)
for i in words:
print(i)
The output will be this:
09807754
18
n
03
aristocrat
0
blue_blood
0
patrician
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
64/32 bit error? I found this as a problem as my dev machine was 32bit and the production server 64bit. If so, you may need to call the 32bit runtime directly from the command line.
This link says it better (No 64bit JET driver): http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/da076e51-8149-4948-add1-6192d8966ead/
You can not make reference to static variable from non-static method. To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only. Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
Etag and Last-modified headers are validators.
They help the browser and/or the cache (reverse proxy) to understand if a file/page, has changed, even if it preserves the same name.
Expires and Cache-control are giving refresh information.
This means that they inform, the browser and the reverse in-between proxies, up to what time or for how long, they may keep the page/file at their cache.
So the question usually is which one validator to use, etag or last-modified, and which refresh infomation header to use, expires or cache-control.
Another solution is to use stat_count()
when dealing with discrete variables (and stat_bin()
with continuous ones).
ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") +
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))
according to the mySQL reference manual this the syntax of using if and else statement :
IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF
So regarding your query :
x = IF((action=2)&&(state=0),1,2);
or you can use
IF ((action=2)&&(state=0)) then
state = 1;
ELSE
state = 2;
END IF;
There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
In addition to all the above ways to convert the text, if you simply use 'strings', it will make the output on separate lines by default. With the added benefit that it may also prevent any chars that may scramble your terminal from appearing.
Both output in one command:
strings /proc//cmdline /proc//environ
The real question is... is there a way to see the real command line of a process in Linux that has been altered so that the cmdline contains the altered text instead of the actual command that was run.
I have added few lines inside package.json:
"scripts": {
...
"clean": "rmdir /s /q node_modules",
"reinstall": "npm run clean && npm install",
"rebuild": "npm run clean && npm install && rmdir /s /q dist && npm run build --prod",
...
}
If you want to clean
only you can use this rimraf node_modules
.
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
first convert your date string to date
then convert it to timestamp
by using following set of line
Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;
The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.
Here is an easy to understand solution
import numpy as np
import pandas as pd
# Creating a 2 dimensional numpy array
>>> data = np.array([[5.8, 2.8], [6.0, 2.2]])
>>> print(data)
>>> data
array([[5.8, 2.8],
[6. , 2.2]])
# Creating pandas dataframe from numpy array
>>> dataset = pd.DataFrame({'Column1': data[:, 0], 'Column2': data[:, 1]})
>>> print(dataset)
Column1 Column2
0 5.8 2.8
1 6.0 2.2
I had the Cannot edit in read-only editor
error when trying to edit code after stopping the debug mode (for 2-3 minutes after pressing Shift+F5
).
Turns out the default Node version (v9.11.1) wasn't exiting gracefully, leaving VScode stuck on read-only.
Simply adding "runtimeVersion": "12.4.0"
to my launch.json file fixed it.
alternatively, change your default Node version to the latest stable version (you can see the current version on the DEBUG CONSOLE
when starting debug mode).
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
a:visited
{
color: #881033;
}
(or whatever color you want it to be)
text-decoration
is for underlining(overlining etc.
decoration
ist not a valid css rule.
My own take at @kvivek's script, with more easily machine parsable output:
#!/bin/sh
# Outputs OS Name, Version & misc. info in a machine-readable way.
# See also NeoFetch for a more professional and elaborate bash script:
# https://github.com/dylanaraps/neofetch
SEP=","
PRINT_HEADER=false
print_help() {
echo "`basename $0` - Outputs OS Name, Version & misc. info"
echo "in a machine-readable way."
echo
echo "Usage:"
echo " `basename $0` [OPTIONS]"
echo "Options:"
echo " -h, --help print this help message"
echo " -n, --names print a header line, naming the fields"
echo " -s, --separator SEP overrides the default field-separator ('$SEP') with the supplied one"
}
# parse command-line args
while [ $# -gt 0 ]
do
arg="$1"
shift # past switch
case "${arg}" in
-h|--help)
print_help
exit 0
;;
-n|--names)
PRINT_HEADER=true
;;
-s|--separator)
SEP="$1"
shift # past value
;;
*) # non-/unknown option
echo "Unknown switch '$arg'" >&2
print_help
;;
esac
done
OS=`uname -s`
DIST="N/A"
REV=`uname -r`
MACH=`uname -m`
PSUEDONAME="N/A"
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
if [ "${OS}" = "SunOS" ] ; then
DIST=Solaris
DIST_VER=`uname -v`
# also: cat /etc/release
elif [ "${OS}" = "AIX" ] ; then
DIST="${OS}"
DIST_VER=`oslevel -r`
elif [ "${OS}" = "Linux" ] ; then
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/redhat-release `
DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/redhat-release `
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
DIST_VER=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`sed -e 's/.*\(//' -e 's/\)//' /etc/mandrake-release`
DIST_VER=`sed -e 's/.*release\ //' -e 's/\ .*//' /etc/mandrake-release`
elif [ -f /etc/debian_version ] ; then
DIST="Debian"
DIST_VER=`cat /etc/debian_version`
PSUEDONAME=`lsb_release -a 2> /dev/null | grep '^Codename:' | sed -e 's/.*[[:space:]]//'`
#elif [ -f /etc/gentoo-release ] ; then
#TODO
#elif [ -f /etc/slackware-version ] ; then
#TODO
elif [ -f /etc/issue ] ; then
# We use this indirection because /etc/issue may look like
# "Debian GNU/Linux 10 \n \l"
ISSUE=`cat /etc/issue`
ISSUE=`echo -e "${ISSUE}" | head -n 1 | sed -e 's/[[:space:]]\+$//'`
DIST=`echo -e "${ISSUE}" | sed -e 's/[[:space:]].*//'`
DIST_VER=`echo -e "${ISSUE}" | sed -e 's/.*[[:space:]]//'`
fi
if [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
# NOTE `sed -e 's/.*(//' -e 's/).*//' /proc/version`
# is an option that worked ~ 2010 and earlier
fi
if $PRINT_HEADER
then
echo "OS${SEP}Distribution${SEP}Distribution-Version${SEP}Pseudo-Name${SEP}Kernel-Revision${SEP}Machine-Architecture"
fi
echo "${OS}${SEP}${DIST}${SEP}${DIST_VER}${SEP}${PSUEDONAME}${SEP}${REV}${SEP}${MACH}"
NOTE: Only tested on Debian 11
osInfo
output:
Linux,Debian,10.0,buster,4.19.0-5-amd64,x86_64
osInfo --names -s "\t| "
output:
OS | Distribution | Distribution-Version | Pseudo-Name | Kernel-Revision | Machine-Architecture
Linux | Debian | 10.0 | buster | 4.19.0-5-amd64 | x86_64
osInfo | awk -e 'BEGIN { FS=","; } { print $2 " " $3 " (" $4 ")" }'
output:
Debian 10.0 (buster)
Best answer is to use the from dateutil import parser
.
usage:
from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split
function) and also doesn't add an unnecesssary <br/>
after the last item.
ALTER TABLE <table name>
ADD <new column name> <data type> NOT NULL
GO
ALTER TABLE <table name>
ADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>
GO
You almost did it. You were tricked by the fact that abs(imagem-255)
will give a wrong result since your dtype
is an unsigned integer. You have to do (255-imagem)
in order to keep the integers unsigned:
def inverte(imagem, name):
imagem = (255-imagem)
cv2.imwrite(name, imagem)
You can also invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
Add this to your Dockerfile
RUN cat /run.sh | tr -d '\r' > /run.sh
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
});
});
And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.
Similar to David Schmitt's answer, plus Josh's suggestion, but doesn't leave a shell process running:
(cd /c && exec /a/helloworld)
This way is more similar to how you usually run commands on the shell. To see the practical difference, you have to run ps ef
from another shell with each solution.
The most simple way I would be going for is;
i = -1
for step in my_list:
i += 1
print(i)
#OR - WE CAN CHANGE THE ORDER OF EXECUTION - SEEMS MORE REASONABLE
i = 0
for step in my_list:
print(i) #DO SOMETHING THEN INCREASE "i"
i += 1
THIS WORKS GREAT - I tested it so, please SET NAME for every object
give the name to the object upon creation
mesh.name = 'nameMeshObject';
and use this if you have to delete an object
delete3DOBJ('nameMeshObject');
function delete3DOBJ(objName){
var selectedObject = scene.getObjectByName(objName);
scene.remove( selectedObject );
animate();
}
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#test').keypress(allowOnlyTwoPositiveDigts);
});
function allowOnlyTwoPositiveDigts(e){
var test = /^[\-]?[0-9]{1,2}?$/
return test.test(this.value+String.fromCharCode(e.which))
}
</script>
</head>
<body>
<input id="test" type="text" />
</body>
</html>
You can return the state this way:
$state.go($state.$current.parent.self.name, $state.params);
An example:
(function() {
'use strict'
angular.module('app')
.run(Run);
/* @ngInject */
function Run($rootScope, $state) {
$rootScope.back = function() {
$state.go($state.$current.parent.self.name, $state.params);
};
};
})();
Possibly related, if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:
$a = range(1, 5); // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm
An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.
Learn python the hard way ex 34
try this
animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']
# print "The first (1st) animal is at 0 and is a bear."
for i in range(len(animals)):
print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])
# "The animal at 0 is the 1st animal and is a bear."
for i in range(len(animals)):
print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])
method below retrieves seven days and return short name of days in List Array in Kotlin though, you can just reformat then in Java format, just presenting idea how Calendar can return short name
private fun getDayDisplayName():List<String>{
val calendar = Calendar.getInstance()
val dates= mutableListOf<String>()
dates.clear()
val s= calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
dates.add(s)
for(i in 0..5){
calendar.roll( Calendar.DATE, -1)
dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
}
return dates.toList()
}
out put results like
I/System.out: Wed
Tue
Mon
Sun
I/System.out: Sat
Fri
Thu
If you're using jQuery 1.5, then statusCode
will work.
If you're using jQuery 1.4, try this:
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
You should see the status code from the first alert.
It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2
and you do cd c:\dir3
, then run the batch, the current directory will be c:\dir3
.
Swift 5.3, I believe.
The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"]
and you want to add "Tim"
to the array, then you can use myArray.insert("Tim", at=*index*)
so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)
I know you can look up IP address to get approximate location, but it's not always accurate. Perhaps they're using that?
update:
Typically, your browser uses information about the Wi-Fi access points around you to estimate your location. If no Wi-Fi access points are in range, or your computer doesn't have Wi-Fi, it may resort to using your computer's IP address to get an approximate location.
With the regular tabular
environment, you want to use the p{width}
column type, as marcog indicates. But that forces you to give explicit widths.
Another solution is the tabularx
environment:
\usepackage{tabularx}
...
\begin{tabularx}{\linewidth}{ r X }
right-aligned foo & long long line of blah blah that will wrap when the table fills the column width\\
\end{tabularx}
All X columns get the same width. You can influence this by setting \hsize
in the format declaration:
>{\setlength\hsize{.5\hsize}} X >{\setlength\hsize{1.5\hsize}} X
but then all the factors have to sum up to 1, I suppose (I took this from the LaTeX companion). There is also the package tabulary
which will adjust column widths to balance row heights. For the details, you can get the documentation for each package with texdoc tabulary
(in TeXlive).
I think this is what you're after?
.shadow {_x000D_
-webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
-moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
}
_x000D_
<div class="shadow">wefwefwef</div>
_x000D_
Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.
Feel free to use it.
/**
* Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
* the value of the key to be used and the object itself from the list entry is used as the
* objct. An empty <code>Map</code> is returned upon null input.
* Reflection is used to retrieve the key from the object instance and method name passed in.
*
* @param <K> The type of the key to be used in the map
* @param <V> The type of value to be used in the map and the type of the elements in the
* collection
* @param coll The collection to be converted.
* @param keyType The class of key
* @param valueType The class of the value
* @param keyMethodName The method name to call on each instance in the collection to retrieve
* the key
* @return A map of key to value instances
* @throws IllegalArgumentException if any of the other paremeters are invalid.
*/
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
final Class<K> keyType,
final Class<V> valueType,
final String keyMethodName) {
final HashMap<K, V> map = new HashMap<K, V>();
Method method = null;
if (isEmpty(coll)) return map;
notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));
try {
// return the Method to invoke to get the key for the map
method = valueType.getMethod(keyMethodName);
}
catch (final NoSuchMethodException e) {
final String message =
String.format(
Messages.getString(METHOD_NOT_FOUND),
keyMethodName,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
try {
for (final V value : coll) {
Object object;
object = method.invoke(value);
@SuppressWarnings("unchecked")
final K key = (K) object;
map.put(key, value);
}
}
catch (final Exception e) {
final String message =
String.format(
Messages.getString(METHOD_CALL_FAILED),
method,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
return map;
}
First of all
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
set-file-data="fileToUpload = value;" _x000D_
type="file" id="my_file" />
_x000D_
1.2 create own directive,
.directive("fileModel",function() {_x000D_
return {_x000D_
restrict: 'EA',_x000D_
scope: {_x000D_
setFileData: "&"_x000D_
},_x000D_
link: function(scope, ele, attrs) {_x000D_
ele.on('change', function() {_x000D_
scope.$apply(function() {_x000D_
var val = ele[0].files[0];_x000D_
scope.setFileData({ value: val });_x000D_
});_x000D_
});_x000D_
}_x000D_
}_x000D_
})
_x000D_
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';
Then create separate function in controller to handle form submit call. like for e.g below code:
In service function handle "responseType" param purposely so that server should not throw "byteerror".
transformRequest, to modify request format with attached identity.
withCredentials : false, for HTTP authentication information.
in controller:_x000D_
_x000D_
// code this accordingly, so that your file object _x000D_
// will be picked up in service call below._x000D_
fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
.service('fileUpload', ['$http', 'ajaxService',_x000D_
function($http, ajaxService) {_x000D_
_x000D_
this.uploadFileToUrl = function(data) {_x000D_
var data = {}; //file object _x000D_
_x000D_
var fd = new FormData();_x000D_
fd.append('file', data.file);_x000D_
_x000D_
$http.post("endpoint server path to whom sending file", fd, {_x000D_
withCredentials: false,_x000D_
headers: {_x000D_
'Content-Type': undefined_x000D_
},_x000D_
transformRequest: angular.identity,_x000D_
params: {_x000D_
fd_x000D_
},_x000D_
responseType: "arraybuffer"_x000D_
})_x000D_
.then(function(response) {_x000D_
var data = response.data;_x000D_
var status = response.status;_x000D_
console.log(data);_x000D_
_x000D_
if (status == 200 || status == 202) //do whatever in success_x000D_
else // handle error in else if needed _x000D_
})_x000D_
.catch(function(error) {_x000D_
console.log(error.status);_x000D_
_x000D_
// handle else calls_x000D_
});_x000D_
}_x000D_
}_x000D_
}])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
in every version of bootstrap,you can do it manually
this do most things that you want for rtl
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.
If you have cloned using HTTPS (recommended) then:-
git config --global credential.helper cache
and then
git config --global credential.helper 'cache --timeout=2592000'
timeout=2592000 (30 Days in seconds) to enable caching for 30 days (or whatever suites you).
Now run a simple git command that requires your username and password.
Enter your credentials once and now caching is enabled for 30 Days.
Try again with any git command and now you don't need any credentials.
For more info :- Caching your GitHub password in Git
Note : You need Git 1.7.10 or newer to use the credential helper. On system restart, we might have to enter the password again.
Update #1:
If you are receiving this error git: 'credential-cache' is not a git command. See 'get --help'
then replace git config --global credential.helper 'cache --timeout=2592000'
with git config --global credential.helper 'store --file ~/.my-credentials'
Update #2:
If you keep getting the prompt of username and password and getting this issue:
Logon failed, use ctrl+c to cancel basic credential prompt.
Reinstalling the latest version of git worked for me.
It seems that RouteParams
no longer exists, and is replaced by ActivatedRoute
. ActivatedRoute
gives us access to the matrix URL notation Parameters. If we want to get Query string ?
paramaters we need to use Router.RouterState
. The traditional query string paramaters are persisted across routing, which may not be the desired result. Preserving the fragment is now optional in router 3.0.0-rc.1.
import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
private queryParamaterValue: string;
private matrixParamaterValue: string;
private querySub: any;
private matrixSub: any;
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.router.routerState.snapshot.queryParams["queryParamaterName"];
this.querySub = this.router.routerState.queryParams.subscribe(queryParams =>
this.queryParamaterValue = queryParams["queryParameterName"];
);
this.route.snapshot.params["matrixParameterName"];
this.route.params.subscribe(matrixParams =>
this.matrixParamterValue = matrixParams["matrixParameterName"];
);
}
ngOnDestroy() {
if (this.querySub) {
this.querySub.unsubscribe();
}
if (this.matrixSub) {
this.matrixSub.unsubscribe();
}
}
}
We should be able to manipulate the ?
notation upon navigation, as well as the ;
notation, but I only gotten the matrix notation to work yet. The plnker that is attached to the latest router documentation shows it should look like this.
let sessionId = 123456789;
let navigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
In Angular 6, with your router you can use:
RouterModule.forRoot(routes, { useHash: false })
Switch your false and true returns? I think if you put those as a function in the visibility area, then false will show it and true will not show it.
This is what I quickly wrote for myself:
public static class XmlDocumentExtensions
{
public static void IterateThroughAllNodes(
this XmlDocument doc,
Action<XmlNode> elementVisitor)
{
if (doc != null && elementVisitor != null)
{
foreach (XmlNode node in doc.ChildNodes)
{
doIterateNode(node, elementVisitor);
}
}
}
private static void doIterateNode(
XmlNode node,
Action<XmlNode> elementVisitor)
{
elementVisitor(node);
foreach (XmlNode childNode in node.ChildNodes)
{
doIterateNode(childNode, elementVisitor);
}
}
}
To use it, I've used something like:
var doc = new XmlDocument();
doc.Load(somePath);
doc.IterateThroughAllNodes(
delegate(XmlNode node)
{
// ...Do something with the node...
});
Maybe it helps someone out there.
I have used below command to remove white space in Oracle
My Table Name is - NG_CAP_SENDER_INFO_MTR
My Column Name is - SENINFO_FROM
UPDATE NG_CAP_SENDER_INFO_MTR SET SENINFO_FROM = TRIM(SENINFO_FROM);
Already Answer on StackOverflow LTRIM RTRIM
And its working fine
Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.
you can use ExecuteScalar()
in place of ExecuteNonQuery()
to get a single result
use it like this
Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));
It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
As you want only one row in return, remove this use of SqlDataReader
from your code
using (SqlDataReader reader = command.ExecuteReader())
{
// iterate your results here
Console.WriteLine(String.Format("{0}",reader["id"]));
}
because it will again execute your command and effect your page performance.
I think it's possible to express functional programming in an imperative fashion:
if... else
/ switch
statements There are huge problems with such approach:
Functional programming, treating functions/ methods like objects and embracing statelessness, was born to solve those problems I believe.
Example of usages: frontend applications like Android, iOS or web apps' logics incl. communication with backend.
Other challenges when simulating functional programming with imperative/ procedural code:
I also believe that at the end of the day, functional code will get translated into assembly or machine code which is imperative/ procedural by the compilers. However, unless you write assembly, as humans writing code with high level/ human-readable language, functional programming is the more appropriate way of expression for the listed scenarios
So you want to:
Inspired by this answer, here's the adapted version of your script:
#!/usr/bin/env bash
different_user=deploy
useradd -m -s /bin/bash "$different_user"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo
echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
echo "Current user: $(id)"
echo "Current directory: $(pwd)"
EOF
echo
echo "Switched back to $(whoami)"
different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"
When you run it, you should get the following:
Current user: root
Current directory: /root
Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy
Switched back to root
deploy home directory: /home/deploy
Using Next.js 9 or above you can get query parameters:
With router
:
import { useRouter } from 'next/router'
const Index = () => {
const router = useRouter()
const {id} = router.query
return(<div>{id}</div>)
}
With getInitialProps
:
const Index = ({id}) => {
return(<div>{id}</div>)
}
Index.getInitialProps = async ({ query }) => {
const {id} = query
return {id}
}
There's one issue with using self.title = @"title";
If you're using Navigation Bar along with Tab bar, the above line also changes the label for the Tab Bar Item. To avoid this, use what @testing suggested
self.navigationItem.title = @"MyTitle";
I figured it out. The below works in converting it to a 24 hr date format.
select date_parse('7/22/2016 6:05:04 PM','%m/%d/%Y %h:%i:%s %p')
How about keeping all .php-files except for index.php above the web root? No need for any rewrite rules or programmatic kludges.
Adding the includes-folder to your include path will then help to keep things simple, no need to use absolute paths etc.
Change a permission property in your /system/etc/permission/platform.xml
and group need to mentioned as like below.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<group android:gid="sdcard_rw" />
<group android:gid="media_rw" />
</uses-permission>
If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
UPDATE: With API level 17+, you can use getRealSize
:
Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);
If you want the available window size, you can use getDecorView
to calculate the available area by subtracting the decor view size from the real display size:
Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);
Rect windowSize = new Rect();
ctivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowSize);
int width = displaySize.x - Math.abs(windowSize.width());
int height = displaySize.y - Math.abs(windowSize.height());
return new Point(width, height);
getRealMetrics
may also work (requires API level 17+), but I haven't tried it yet:
DisplayMetrics metrics = new DisplayMetrics();
activity.GetWindowManager().getDefaultDisplay().getRealMetrics(metrics);
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
Without changing directory:
import os
path = '/path/to/files/'
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)
print time_sorted_list
# if you want just the filenames sorted, simply remove the dir from each
sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]
print sorted_filename_list
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
As for now there is no proper solution, as @spro says.
However, if you have an in-flight response and are using ReadableStream, you can close the stream to cancel the request.
fetch('http://example.com').then((res) => {
const reader = res.body.getReader();
/*
* Your code for reading streams goes here
*/
// To abort/cancel HTTP request...
reader.cancel();
});
For deleting a dynamic array in VBA use the instruction Erase
.
Example:
Dim ArrayDin() As Integer
ReDim ArrayDin(10) 'Dynamic allocation
Erase ArrayDin 'Erasing the Array
Hope this help!
Here an implementation that uses a System.Threading.Timer
. Maybe a bit much for its purpose.
private static bool StartProcess(string filePath, string processName)
{
if (!File.Exists(filePath))
throw new InvalidOperationException($"Unknown filepath: {(string.IsNullOrEmpty(filePath) ? "EMPTY PATH" : filePath)}");
var isRunning = false;
using (var resetEvent = new ManualResetEvent(false))
{
void Callback(object state)
{
if (!IsProcessActive(processName)) return;
isRunning = true;
// ReSharper disable once AccessToDisposedClosure
resetEvent.Set();
}
using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
{
Process.Start(filePath);
WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
}
}
return isRunning;
}
private static bool StopProcess(string processName)
{
if (!IsProcessActive(processName)) return true;
var isRunning = true;
using (var resetEvent = new ManualResetEvent(false))
{
void Callback(object state)
{
if (IsProcessActive(processName)) return;
isRunning = false;
// ReSharper disable once AccessToDisposedClosure
resetEvent.Set();
}
using (new Timer(Callback, null, 0, TimeSpan.FromSeconds(0.5).Milliseconds))
{
foreach (var process in Process.GetProcessesByName(processName))
process.Kill();
WaitHandle.WaitAny(new WaitHandle[] { resetEvent }, TimeSpan.FromSeconds(9));
}
}
return isRunning;
}
private static bool IsProcessActive(string processName)
{
return Process.GetProcessesByName(processName).Any();
}
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
I typically have a secrets.py
that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>
. This way you can rely on the operating systems in-built file security system without re-inventing your own.
Using Base64
encoding/decoding is also another way to obfuscate the password though not completely secure
More here - Hiding a password in a python script (insecure obfuscation only)
I've had issues with this recently, which seem to be fixed in the latest Eclipse.
eclipse-java 4.11.0,2019-03:R -> 4.12.0,2019-06:R
Another trap of note is making sure you're not decorating controllers with the Consume Attribute as below:
[Produces("application/json")]
[Consumes("application/json")]
public class MyController : Controller
This will fail with a 415 Unsupported Media Type if the upload is NOT JSON.
A "friend of mine" was recently caught out by this like so:
public class MyFileUploadController : MyCustomController {
}
[Produces("application/json")]
[Consumes("application/json")]
public class MyCustomController : ControllerBase {
}
You can try ng-file-upload angularjs plugin (instead of ng-upload).
It's fairly easy to setup and deal with angularjs specifics. It also supports progress, cancel, drag and drop and is cross browser.
html
<!-- Note: MUST BE PLACED BEFORE angular.js-->
<script src="ng-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-file-upload.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directives and service.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
data: {myObj: $scope.myModelObj},
file: file,
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).then(function(response) {
var data = response.data;
// file is uploaded successfully
console.log(data);
});
}
};
}];
feof()
indicates if one has tried to read past the end of file. That means it has little predictive effect: if it is true, you are sure that the next input operation will fail (you aren't sure the previous one failed BTW), but if it is false, you aren't sure the next input operation will succeed. More over, input operations may fail for other reasons than the end of file (a format error for formatted input, a pure IO failure -- disk failure, network timeout -- for all input kinds), so even if you could be predictive about the end of file (and anybody who has tried to implement Ada one, which is predictive, will tell you it can complex if you need to skip spaces, and that it has undesirable effects on interactive devices -- sometimes forcing the input of the next line before starting the handling of the previous one), you would have to be able to handle a failure.
So the correct idiom in C is to loop with the IO operation success as loop condition, and then test the cause of the failure. For instance:
while (fgets(line, sizeof(line), file)) {
/* note that fgets don't strip the terminating \n, checking its
presence allow to handle lines longer that sizeof(line), not showed here */
...
}
if (ferror(file)) {
/* IO failure */
} else if (feof(file)) {
/* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
/* format error (not possible with fgets, but would be with fscanf) */
}
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
The correct path shouldn't end with "/", I had it wrong that caused the trouble
Right way:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.
Having that in mind, we have so many ways to solve this
Using str.replace
,
>>> "it is icy".replace("i", "")
't s cy'
Using str.translate
,
>>> "it is icy".translate(None, "i")
't s cy'
Using Regular Expression,
>>> import re
>>> re.sub(r'i', "", "it is icy")
't s cy'
Using comprehension as a filter,
>>> "".join([char for char in "it is icy" if char != "i"])
't s cy'
Using filter
function
>>> "".join(filter(lambda char: char != "i", "it is icy"))
't s cy'
Timing comparison
def findreplace(m_string, char):
m_string = list(m_string)
for k in m_string:
if k == char:
del(m_string[m_string.index(k)])
return "".join(m_string)
def replace(m_string, char):
return m_string.replace("i", "")
def translate(m_string, char):
return m_string.translate(None, "i")
from timeit import timeit
print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")
Result
1.64474582672
0.29278588295
0.311302900314
str.replace
and str.translate
methods are 8 and 5 times faster than the accepted answer.
Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re
is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.
Another option is to use the package require-dir which let's you do the following. It supports recursion as well.
var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');
Write an expect
script.
Here is an example:
#!/usr/bin/expect
#If it all goes pear shaped the script will timeout after 20 seconds.
set timeout 20
#First argument is assigned to the variable name
set name [lindex $argv 0]
#Second argument is assigned to the variable user
set user [lindex $argv 1]
#Third argument is assigned to the variable password
set password [lindex $argv 2]
#This spawns the telnet program and connects it to the variable name
spawn telnet $name
#The script expects login
expect "login:"
#The script sends the user variable
send "$user "
#The script expects Password
expect "Password:"
#The script sends the password variable
send "$password "
#This hands control of the keyboard over to you (Nice expect feature!)
interact
To run:
./myscript.expect name user password
For simple animations you can use an animated gif. I'm using one in this README file for instance.
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
Personally, I use this function which I created and put in my profile script ...\Documents\WindowsPowerShell\….profile
, feel free to use it. As I am from the UK, I prefer to go to .co.uk
where possible, if you are from another area, you can add your own country code.
# Function taking parameter add (address) and opens in edge.
Function edge {
param($add)
if (-not ($add -contains "https://www." -or $add -contains "http://www.")) {
if ($add[0] -eq "w" -and $add[1] -eq "w" -and $add[2] -eq "w") {
$add = "https://" + $add
} else {
$add = "https://www." + $add
}
}
# If no domain, tries to add .co.uk, if fails uses .com
if (-not ($add -match ".co" -or $add -match ".uk" -or $add -match ".com")) {
try {
$test = $add + ".co.uk"
$HTTP_Request = [System.Net.WebRequest]::Create($test)
$HTTP_Response = $HTTP_Request.GetResponse()
$add = $add + ".co.uk"
} catch{
$add = $add + ".com"
}
}
Write-Host "Taking you to $add"
start microsoft-edge:$add
}
Then you just have to call: edge google
in powershell to go to https://www.google.co.uk
Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.
We can always use array of strings for multiline strings like following.
{
"singleLine": "Some singleline String",
"multiline": ["Line one", "line Two", "Line Three"]
}
And we can easily iterate array to display content in multi line fashion.