All answers above are incomplete, the problem here lies in linker ld
rather than compiler collect2: ld returned 1 exit status
. When you are compiling your fib.c
to object:
$ gcc -c fib.c
$ nm fib.o
0000000000000028 T fibo
U floor
U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
U pow
U printf
Where nm
lists symbols from object file. You can see that this was compiled without an error, but pow
, floor
, and printf
functions have undefined references, now if I will try to link this to executable:
$ gcc fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Im getting similar output you get. To solve that, I need to tell linker where to look for references to pow
, and floor
, for this purpose I will use linker -l
flag with m
which comes from libm.so
library.
$ gcc fib.o -lm
$ nm a.out
0000000000201010 B __bss_start
0000000000201010 b completed.7697
w __cxa_finalize@@GLIBC_2.2.5
0000000000201000 D __data_start
0000000000201000 W data_start
0000000000000620 t deregister_tm_clones
00000000000006b0 t __do_global_dtors_aux
0000000000200da0 t
__do_global_dtors_aux_fini_array_entry
0000000000201008 D __dso_handle
0000000000200da8 d _DYNAMIC
0000000000201010 D _edata
0000000000201018 B _end
0000000000000722 T fibo
0000000000000804 T _fini
U floor@@GLIBC_2.2.5
00000000000006f0 t frame_dummy
0000000000200d98 t __frame_dummy_init_array_entry
00000000000009a4 r __FRAME_END__
0000000000200fa8 d _GLOBAL_OFFSET_TABLE_
w __gmon_start__
000000000000083c r __GNU_EH_FRAME_HDR
0000000000000588 T _init
0000000000200da0 t __init_array_end
0000000000200d98 t __init_array_start
0000000000000810 R _IO_stdin_used
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
0000000000000800 T __libc_csu_fini
0000000000000790 T __libc_csu_init
U __libc_start_main@@GLIBC_2.2.5
00000000000006fa T main
U pow@@GLIBC_2.2.5
U printf@@GLIBC_2.2.5
0000000000000660 t register_tm_clones
00000000000005f0 T _start
0000000000201010 D __TMC_END__
You can now see, functions pow
, floor
are linked to GLIBC_2.2.5
.
Parameters order is important too, unless your system is configured to use shared librares by default, my system is not, so when I issue:
$ gcc -lm fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status
Note -lm
flag before object file. So in conclusion, add -lm
flag after all other flags, and parameters, to be sure.
I had the same problem, which went away after I listed my library last: gcc prog.c -lm
I had this issue recently. In my case, I had my IDE set to choose which compiler (C or C++) to use on each file according to its extension, and I was trying to call a C function (i.e. from a .c
file) from C++ code.
The .h
file for the C function wasn't wrapped in this sort of guard:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
I could've added that, but I didn't want to modify it, so I just included it in my C++ file like so:
extern "C" {
#include "legacy_C_header.h"
}
(Hat tip to UncaAlby for his clear explanation of the effect of extern "C".)
Unspecialized templates must have their definitions visible to all translation units that use them. That means you can't separate the definition of a template
to an implementation file. If you must separate the implementation, the usual workaround is to have an impl
file which you include at the end of the header that
declares the template. A common situation is:
template<class T>
struct X
{
void foo();
};
int main()
{
X<int> x;
x.foo();
}
//differentImplementationFile.cpp
template<class T>
void X<T>::foo()
{
}
To fix this, you must move the definition of X::foo
to the header file or some place visible to the translation unit that uses it.
Specialized templates can be implemented in an implementation file and the implementation doesn't have to be visible, but the specialization must be previously declared.
For further explanation and another possible solution (explicit instantiation) see this question and answer.
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
The declaration and definition of insertLike
are different
In your header file:
void insertLike(const char sentence[], const int lengthTo, const int length,
const char writeTo[]);
In your 'function file':
void insertLike(const char sentence[], const int lengthTo, const int length,
char writeTo[]);
C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.
In this case, insertLike
which takes const char*
as its fourth parameter and insertLike
which takes char *
as its fourth parameter are different functions.
Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.
myQueue.hpp:
template <class T>
class QueueA {
int size;
...
public:
template <class T> T dequeue() {
// implementation here
}
bool isEmpty();
...
}
myQueue.cpp:
// implementation of regular methods goes like this:
template <class T> bool QueueA<T>::isEmpty() {
return this->size == 0;
}
main()
{
QueueA<char> Q;
...
}
I suppose you have imported math.h with #include <math.h>
So the only other reason I can see is a missing linking information. You must link your code with the -lm
option.
If you're simply trying to compile one file with gcc, just add -lm
to your command line, otherwise, give some informations about your building process.
I was getting this error because my cpp files was not added in the CMakeLists.txt file
What I have found is that sometimes the library that the linker complains about is not the one causing the problem. Possibly there is a clever way to work out where the problem is but this is what I do:
@peter karasev: I have come across the same problem with a gcc 4.8.2 cmake project on CentOS7. The order of the libraries in "target_link_libraries" section is important. I guess cmake just passes the list on to the linker as-is, i.e. it doesn't try and work out the correct order. This is reasonable - when you think about it cmake can't know what the correct order is until the linking is successfully completed.
DateTime dateForButton = DateTime.Now.AddDays(-1);
Caseless enums can also be be used.
Advantage - They cannot be instantiated.
enum API {
enum Endpoint {
static let url1 = "url1"
static let url2 = "url2"
}
enum BaseURL {
static let dev = "dev"
static let prod = "prod"
}
}
It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport)
and __declspec(dllexport)
. Other uses (some Microsoft-only) are documented in the MSDN.
Try this:
for(String str: myList) {
if(str.trim().equals("A"))
return true;
}
return false;
You need to use str.equals
or str.equalsIgnoreCase
instead of contains
because contains
in string
works not the same as contains
in List
List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true
Here is a nice widget/plugin library which has ellipsis built in: http://www.codeitbetter.co.uk/widgets/ellipsis/ All you need to do it reference the library and call the following:
<script type="text/javascript">
$(document).ready(function () {
$(".ellipsis_10").Ellipsis({
numberOfCharacters: 10,
showLessText: "less",
showMoreText: "more"
});
});
</script>
<div class="ellipsis_10">
Some text here that's longer than 10 characters.
</div>
CGI is a mechanism whereby an external program is called by the web server in order to handle a request, with environment variables and standard input being used to feed the request data to the program. The exact language the external program is written in does not matter, although it is easier to write CGI programs in some languages versus others.
Since CGI scripts need execute permissions, httpd by default only allows CGI programs in the cgi-bin
directory to be run for (possibly now misguided) security purposes.
Most PHP scripts run in the web server process via mod_php
. This is not CGI.
CGI is slow since the program (and related interpreter) must be started up per request. Modern alternatives are embedded execution, used by mod_php, and long-running processes, used by FastCGI. A given language may have its own way of implementing those mechanisms, so be sure to ask around before resorting to CGI.
var myPopup = window.open(...); myPopup.addEventListener('load', myFunction, false);
If you care about IE, use the following as the second line instead:
myPopup[myPopup.addEventListener ? 'addEventListener' : 'attachEvent']( (myPopup.attachEvent ? 'on' : '') + 'load', myFunction, false );
As you can see, supporting IE is quite cumbersome and should be avoided if possible. I mean, if you need to support IE because of your audience, by all means, do so.
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country
in another function as return value, (string)
, taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
Eric's answer is great, but you really don't need that timeout. If you're using jQuery, you can just wait for the page to load. So I'd suggest changing the code to:
// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
$(window).on("hashchange", function () {
offsetAnchor();
});
// Let the page finish loading.
$(document).ready(function() {
offsetAnchor();
});
This also gets us rid of that arbitrary factor.
Using server request time to Add days. Working as expected.
25/08/19 => 27/09/19
$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));
Here '+2 days' to add any number of days.
(This is paraphrased from the MS Access help files. I'm sure XL has something similar.) Basically, TimerInterval is a form-level property. Once set, use the sub Form_Timer to carry out your intended action.
Sub Form_Load()
Me.TimerInterval = 1000 '1000 = 1 second
End Sub
Sub Form_Timer()
'Do Stuff
End Sub
To set a FOREIGN KEY in Table B you must set a KEY in the table A.
In table A:
INDEX id
(id
)
And then in the table B,
CONSTRAINT `FK_id` FOREIGN KEY (`id`) REFERENCES `table-A` (`id`)
I know that in SQL 2012 (may work in other versions) you can do the following:
That will give you a list of the top 1000 tables and then you can order it by data size etc.
simply do the select
:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))
To check for ssl support in Python 2.6+:
try:
import ssl
except ImportError:
print "error: no ssl support"
To connect via https:
import urllib2
try:
response = urllib2.urlopen('https://example.com')
print 'response headers: "%s"' % response.info()
except IOError, e:
if hasattr(e, 'code'): # HTTPError
print 'http error code: ', e.code
elif hasattr(e, 'reason'): # URLError
print "can't connect, reason: ", e.reason
else:
raise
// C#
bool isEven = ((i % 2) == 0);
You should give the content to InfoWindow from jQuery object.
var $infoWindowContent = $("<div class='infowin-content'>Content goes here</div>");
var infoWindow = new google.maps.InfoWindow();
infowindow.setContent($infoWindowContent[0]);
Use snprintf
, it is more portable than itoa
.
itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.
Example of sprintf
char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);
Example of snprintf
char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);
Both functions are similar to fprintf
, but output is written into an array rather than to a stream. The difference between sprintf
and snprintf
is that snprintf
guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer
.
Here is a little sub that may just interest some people who need to specify the browser. (but its not as good as a 12" pizza sub!) :P
Private Sub NavigateWebURL(ByVal URL As String, Optional browser As String = "default")
If Not (browser = "default") Then
Try
'// try set browser if there was an error (browser not installed)
Process.Start(browser, URL)
Catch ex As Exception
'// use default browser
Process.Start(URL)
End Try
Else
'// use default browser
Process.Start(URL)
End If
End Sub
Call: will open www.google.com in Firefox if it is installed on that PC.
NavigateWebURL("http://www.google.com", "Firefox") '// safari Firefox chrome etc
Call: will open www.google.com in default browser.
NavigateWebURL("http://www.google.com", "default")
OR
NavigateWebURL("http://www.google.com")
Just give any name to the DataTable Like:
DataTable dt = new DataTable();
dt = SecondDataTable.Copy();
dt .TableName = "New Name";
DataSet.Tables.Add(dt );
A general answer
select * from [dbo].[SplitString]('1,2',',') -- Will work
but
select [dbo].[SplitString]('1,2',',') -- will not work and throws this error
The accepted answer above did not work for me, because it ordered the weeks by alphabetical order, not chronological order:
2012/1
2012/10
2012/11
...
2012/19
2012/2
Here's my solution to count and group by week:
SELECT CONCAT(YEAR(date), '/', WEEK(date)) AS week_name,
YEAR(date), WEEK(date), COUNT(*)
FROM column_name
GROUP BY week_name
ORDER BY YEAR(DATE) ASC, WEEK(date) ASC
Generates:
YEAR/WEEK YEAR WEEK COUNT
2011/51 2011 51 15
2011/52 2011 52 14
2012/1 2012 1 20
2012/2 2012 2 14
2012/3 2012 3 19
2012/4 2012 4 19
You need to declare @font-face
like this in your stylesheet
@font-face {
font-family: 'Awesome-Font';
font-style: normal;
font-weight: 400;
src: local('Awesome-Font'), local('Awesome-Font-Regular'), url(path/Awesome-Font.woff) format('woff');
}
Now if you want to apply this font to a paragraph simply use it like this..
p {
font-family: 'Awesome-Font', Arial;
}
I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud
claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)
For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)
For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).
OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud
claim in ID Tokens. (openid-connect-core-1.0)
aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
furthermore OIDC specifies the azp
claim that is used in conjunction with aud
when aud
has more than one value.
azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
This is the Kotlin version of the function posted by VVB. I used it in the ListView Adapter to implement the "go to next row first EditText when Enter key is pressed on the last EditText of current row" feature in the getView().
In the ListViewAdapter class, fun getView(), add lastEditText.setOnKeyListner as below:
lastEditText.setOnKeyListener { v, keyCode, event ->
var setOnKeyListener = false
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
try {
val nextRow = getViewByPosition(position + 1, parent as ListView) as LinearLayout
val nextET = nextRow.findViewById(R.id.firstEditText) as EditText
nextET.isFocusableInTouchMode = true
nextET.requestFocus()
} catch (e: Exception) {
// do nothing
}
setOnKeyListener = true
}
setOnKeyListener
}
add the fun getViewByPosition() after fun getView() as below:
private fun getViewByPosition(pos: Int, listView: ListView): View? {
val firstListItemPosition: Int = listView.firstVisiblePosition
val lastListItemPosition: Int = firstListItemPosition + listView.childCount - 1
return if (pos < firstListItemPosition || pos > lastListItemPosition) {
listView.adapter.getView(pos, null, listView)
} else {
val childIndex = pos + listView.headerViewsCount - firstListItemPosition
listView.getChildAt(childIndex)
}
}
in your receiving intent use as
Intent intent = getActivity().getIntent();
((TextView)view.findViewById(R.id.hello)).setText(intent.getStringExtra("Hello"));
and in your send intent
Intent intent = new Intent(getActivity(),Main2Activity.class);
intent.putExtra("Hello","Nisar");
getActivity().startActivity(intent);
remember both are in fragments
This code works for me. Is this what you are trying to do?
<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button id="addfiles" >Add files</button>
<script language="javascript" type="text/javascript">
$("#addfiles").click(function(){
$("#fileinput").click();
});
</script>
"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.
And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:
private void MainForm_Shown(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
Hide();
}
Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :
methods: {
validation(attr){
switch(attr) {
case 'email':
const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return re.test(this.form.email);
case 'password':
return this.form.password.length > 4
}
},
...
}
Which you'll be using like :
<b-form-input
id="email"
v-model="form.email"
type="email"
:state="validation('email')"
required
placeholder="Enter email"
></b-form-input>
Just keep in mind that you will still miss the caching specific to computed.
Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.
The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.
Roll your own with @Clockworks solution, or in Atom, choose the menu option Atom > Install Shell Commands. This creates two symlinks in /usr/local/bin
apm -> /Applications/Atom.app/Contents/Resources/app/apm/node_modules/.bin/apm
atom -> /Applications/Atom.app/Contents/Resources/app/atom.sh
The atom
command lets you do exactly what you're asking. apm
is the command line package manager.
You can implement a SoapExtension that logs the full request and response to a log file. You can then enable the SoapExtension in the web.config, which makes it easy to turn on/off for debugging purposes. Here is an example that I have found and modified for my own use, in my case the logging was done by log4net but you can replace the log methods with your own.
public class SoapLoggerExtension : SoapExtension
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Stream oldStream;
private Stream newStream;
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override System.IO.Stream ChainStream(System.IO.Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
Log(message, "AfterSerialize");
CopyStream(newStream, oldStream);
newStream.Position = 0;
break;
case SoapMessageStage.BeforeDeserialize:
CopyStream(oldStream, newStream);
Log(message, "BeforeDeserialize");
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
public void Log(SoapMessage message, string stage)
{
newStream.Position = 0;
string contents = (message is SoapServerMessage) ? "SoapRequest " : "SoapResponse ";
contents += stage + ";";
StreamReader reader = new StreamReader(newStream);
contents += reader.ReadToEnd();
newStream.Position = 0;
log.Debug(contents);
}
void ReturnStream()
{
CopyAndReverse(newStream, oldStream);
}
void ReceiveStream()
{
CopyAndReverse(newStream, oldStream);
}
public void ReverseIncomingStream()
{
ReverseStream(newStream);
}
public void ReverseOutgoingStream()
{
ReverseStream(newStream);
}
public void ReverseStream(Stream stream)
{
TextReader tr = new StreamReader(stream);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
TextWriter tw = new StreamWriter(stream);
stream.Position = 0;
tw.Write(strReversed);
tw.Flush();
}
void CopyAndReverse(Stream from, Stream to)
{
TextReader tr = new StreamReader(from);
TextWriter tw = new StreamWriter(to);
string str = tr.ReadToEnd();
char[] data = str.ToCharArray();
Array.Reverse(data);
string strReversed = new string(data);
tw.Write(strReversed);
tw.Flush();
}
private void CopyStream(Stream fromStream, Stream toStream)
{
try
{
StreamReader sr = new StreamReader(fromStream);
StreamWriter sw = new StreamWriter(toStream);
sw.WriteLine(sr.ReadToEnd());
sw.Flush();
}
catch (Exception ex)
{
string message = String.Format("CopyStream failed because: {0}", ex.Message);
log.Error(message, ex);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
public class SoapLoggerExtensionAttribute : SoapExtensionAttribute
{
private int priority = 1;
public override int Priority
{
get { return priority; }
set { priority = value; }
}
public override System.Type ExtensionType
{
get { return typeof (SoapLoggerExtension); }
}
}
You then add the following section to your web.config where YourNamespace and YourAssembly point to the class and assembly of your SoapExtension:
<webServices>
<soapExtensionTypes>
<add type="YourNamespace.SoapLoggerExtension, YourAssembly"
priority="1" group="0" />
</soapExtensionTypes>
</webServices>
For those late-comers that are looking for a solution that "just works":
#include <utility>
#include <iostream>
template< typename T >
class Y {
template< bool cond, typename U >
using resolvedType = typename std::enable_if< cond, U >::type;
public:
template< typename U = T >
resolvedType< true, U > foo() {
return 11;
}
template< typename U = T >
resolvedType< false, U > foo() {
return 12;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
Compile with:
g++ -std=gnu++14 test.cpp
Running gives:
./a.out
11
The static keyword is used in C to restrict the visibility of a function or variable to its translation unit. Translation unit is the ultimate input to a C compiler from which an object file is generated.
Check this: Linkage | Translation unit
Thanks to both of you. This worked perfectly for me.
$("input[type='text'][id*=" + strID + "]:visible").each(function() {
this.value=strVal;
});
Use eqnarray
and \nonumber
example:
\begin{eqnarray}
sample = R(s,\pi(s),s') + \gamma V^{\pi} (s') \nonumber \\
\label{eq:temporal-difference}
V^{\pi}_{k+1}(s) = (1-\alpha)V^{\pi}(s) - \alpha[sample]
\end{eqnarray}
This works like champ on mac os or windows.
Remove workbench.xmi located at workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi. Then start your Eclipse or ADT. This will not erase your workspace or repository.
Remove workbench.xmi cmd:
rm workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi.
Great answer from atrain, but maybe better solution to catch exceptions is to utilize own HandlerExceptionResolver and catch
@Override
public ModelAndView resolveException(
HttpServletRequest aReq,
HttpServletResponse aRes,
Object aHandler,
Exception anExc
){
// ....
if(anExc instanceof MethodArgumentNotValidException) // do your handle error here
}
Then you're able to keep your handler as clean as possible. You don't need BindingResult, Model and SomeFormBean in myHandlerMethod anymore.
Usage:
String remoteCommandOutput = exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1");
String remoteShellOutput = shell("ssh://user:pass@host/work/dir/path", "ls");
shell("ssh://user:pass@host/work/dir/path", "ls", System.out);
shell("ssh://user:pass@host", System.in, System.out);
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
Implementation:
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Thread.sleep;
import static org.apache.commons.io.FilenameUtils.getFullPath;
import static org.apache.commons.io.FilenameUtils.getName;
import static org.apache.commons.lang3.StringUtils.trim;
import com.google.common.collect.ImmutableMap;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Map;
import java.util.Properties;
public final class SshUtils {
private static final Logger LOG = LoggerFactory.getLogger(SshUtils.class);
private static final String SSH = "ssh";
private static final String FILE = "file";
private SshUtils() {
}
/**
* <pre>
* <code>
* sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
* sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
* </code>
*
* <pre>
*
* @param fromUri
* file
* @param toUri
* directory
*/
public static void sftp(String fromUri, String toUri) {
URI from = URI.create(fromUri);
URI to = URI.create(toUri);
if (SSH.equals(to.getScheme()) && FILE.equals(from.getScheme()))
upload(from, to);
else if (SSH.equals(from.getScheme()) && FILE.equals(to.getScheme()))
download(from, to);
else
throw new IllegalArgumentException();
}
private static void upload(URI from, URI to) {
try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", to);
FileInputStream fis = new FileInputStream(new File(from))) {
LOG.info("Uploading {} --> {}", from, session.getMaskedUri());
ChannelSftp channel = session.getChannel();
channel.connect();
channel.cd(to.getPath());
channel.put(fis, getName(from.getPath()));
} catch (Exception e) {
throw new RuntimeException("Cannot upload file", e);
}
}
private static void download(URI from, URI to) {
File out = new File(new File(to), getName(from.getPath()));
try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", from);
OutputStream os = new FileOutputStream(out);
BufferedOutputStream bos = new BufferedOutputStream(os)) {
LOG.info("Downloading {} --> {}", session.getMaskedUri(), to);
ChannelSftp channel = session.getChannel();
channel.connect();
channel.cd(getFullPath(from.getPath()));
channel.get(getName(from.getPath()), bos);
} catch (Exception e) {
throw new RuntimeException("Cannot download file", e);
}
}
/**
* <pre>
* <code>
* shell("ssh://user:pass@host", System.in, System.out);
* </code>
* </pre>
*/
public static void shell(String connectUri, InputStream is, OutputStream os) {
try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri))) {
shell(session, is, os);
}
}
/**
* <pre>
* <code>
* String remoteOutput = shell("ssh://user:pass@host/work/dir/path", "ls")
* </code>
* </pre>
*/
public static String shell(String connectUri, String command) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
shell(connectUri, command, baos);
return baos.toString();
} catch (RuntimeException e) {
LOG.warn(baos.toString());
throw e;
}
}
/**
* <pre>
* <code>
* shell("ssh://user:pass@host/work/dir/path", "ls", System.out)
* </code>
* </pre>
*/
public static void shell(String connectUri, String script, OutputStream out) {
try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri));
PipedOutputStream pipe = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(pipe);
PrintWriter pw = new PrintWriter(pipe)) {
if (session.getWorkDir() != null)
pw.println("cd " + session.getWorkDir());
pw.println(script);
pw.println("exit");
pw.flush();
shell(session, in, out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void shell(SessionHolder<ChannelShell> session, InputStream is, OutputStream os) {
try {
ChannelShell channel = session.getChannel();
channel.setInputStream(is, true);
channel.setOutputStream(os, true);
LOG.info("Starting shell for " + session.getMaskedUri());
session.execute();
session.assertExitStatus("Check shell output for error details.");
} catch (InterruptedException | JSchException e) {
throw new RuntimeException("Cannot execute script", e);
}
}
/**
* <pre>
* <code>
* System.out.println(exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1"));
* </code>
*
* <pre>
*
* @param connectUri
* @param command
* @return
*/
public static String exec(String connectUri, String command) {
try (SessionHolder<ChannelExec> session = new SessionHolder<>("exec", URI.create(connectUri))) {
String scriptToExecute = session.getWorkDir() == null
? command
: "cd " + session.getWorkDir() + "\n" + command;
return exec(session, scriptToExecute);
}
}
private static String exec(SessionHolder<ChannelExec> session, String command) {
try (PipedOutputStream errPipe = new PipedOutputStream();
PipedInputStream errIs = new PipedInputStream(errPipe);
InputStream is = session.getChannel().getInputStream()) {
ChannelExec channel = session.getChannel();
channel.setInputStream(null);
channel.setErrStream(errPipe);
channel.setCommand(command);
LOG.info("Starting exec for " + session.getMaskedUri());
session.execute();
String output = IOUtils.toString(is);
session.assertExitStatus(IOUtils.toString(errIs));
return trim(output);
} catch (InterruptedException | JSchException | IOException e) {
throw new RuntimeException("Cannot execute command", e);
}
}
public static class SessionHolder<C extends Channel> implements Closeable {
private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
private static final int DEFAULT_PORT = 22;
private static final int TERMINAL_HEIGHT = 1000;
private static final int TERMINAL_WIDTH = 1000;
private static final int TERMINAL_WIDTH_IN_PIXELS = 1000;
private static final int TERMINAL_HEIGHT_IN_PIXELS = 1000;
private static final int DEFAULT_WAIT_TIMEOUT = 100;
private String channelType;
private URI uri;
private Session session;
private C channel;
public SessionHolder(String channelType, URI uri) {
this(channelType, uri, ImmutableMap.of("StrictHostKeyChecking", "no"));
}
public SessionHolder(String channelType, URI uri, Map<String, String> props) {
this.channelType = channelType;
this.uri = uri;
this.session = newSession(props);
this.channel = newChannel(session);
}
private Session newSession(Map<String, String> props) {
try {
Properties config = new Properties();
config.putAll(props);
JSch jsch = new JSch();
Session newSession = jsch.getSession(getUser(), uri.getHost(), getPort());
newSession.setPassword(getPass());
newSession.setUserInfo(new User(getUser(), getPass()));
newSession.setDaemonThread(true);
newSession.setConfig(config);
newSession.connect(DEFAULT_CONNECT_TIMEOUT);
return newSession;
} catch (JSchException e) {
throw new RuntimeException("Cannot create session for " + getMaskedUri(), e);
}
}
@SuppressWarnings("unchecked")
private C newChannel(Session session) {
try {
Channel newChannel = session.openChannel(channelType);
if (newChannel instanceof ChannelShell) {
ChannelShell channelShell = (ChannelShell) newChannel;
channelShell.setPtyType("ANSI", TERMINAL_WIDTH, TERMINAL_HEIGHT, TERMINAL_WIDTH_IN_PIXELS, TERMINAL_HEIGHT_IN_PIXELS);
}
return (C) newChannel;
} catch (JSchException e) {
throw new RuntimeException("Cannot create " + channelType + " channel for " + getMaskedUri(), e);
}
}
public void assertExitStatus(String failMessage) {
checkState(channel.getExitStatus() == 0, "Exit status %s for %s\n%s", channel.getExitStatus(), getMaskedUri(), failMessage);
}
public void execute() throws JSchException, InterruptedException {
channel.connect();
channel.start();
while (!channel.isEOF())
sleep(DEFAULT_WAIT_TIMEOUT);
}
public Session getSession() {
return session;
}
public C getChannel() {
return channel;
}
@Override
public void close() {
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
public String getMaskedUri() {
return uri.toString().replaceFirst(":[^:]*?@", "@");
}
public int getPort() {
return uri.getPort() < 0 ? DEFAULT_PORT : uri.getPort();
}
public String getUser() {
return uri.getUserInfo().split(":")[0];
}
public String getPass() {
return uri.getUserInfo().split(":")[1];
}
public String getWorkDir() {
return uri.getPath();
}
}
private static class User implements UserInfo, UIKeyboardInteractive {
private String user;
private String pass;
public User(String user, String pass) {
this.user = user;
this.pass = pass;
}
@Override
public String getPassword() {
return pass;
}
@Override
public boolean promptYesNo(String str) {
return false;
}
@Override
public String getPassphrase() {
return user;
}
@Override
public boolean promptPassphrase(String message) {
return true;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public void showMessage(String message) {
// do nothing
}
@Override
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}
}
I have fixed this issue by unchecking 'Connect Hardware Keyboard'. Please refer to the image below to fix this issue
The author of this article claims that it would be best to avoid installing Ruby from the local packet manager, but to use RVM instead.
You can easily switch between different Ruby versions:
rvm use 1.9.3
etc.
imread
is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use imageio.imread
instead.
import imageio
im = imageio.imread('astronaut.png')
im.shape # im is a numpy array
(512, 512, 3)
imageio.imwrite('imageio:astronaut-gray.jpg', im[:, :, 0])
just use the core https module with the https.request function. Example for a POST
request (GET
would be similar):
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
When we make a dump file with mysqldump
, what it contains is a big SQL script for recreating the databse contents. So we restore it by using starting up MySQL’s command-line client:
mysql -uroot -p
(where root
is our admin user name for MySQL), and once connected to the database we need commands to create the database and read the file in to it:
create database new_db;
use new_db;
\. dumpfile.sql
Details will vary according to which options were used when creating the dump file.
Instead of removing and re-adding, you can do this:
git remote set-url origin git://new.url.here
See this question: How to change the URI (URL) for a remote Git repository?
To remove remote use this:
git remote remove origin
You can try this
$scope.$watch('tags ',function(){
$scope.tags = $filter('lowercase')($scope.tags);
});
For MySql 8 you can use following script:
SET GLOBAL validate_password.LENGTH = 4;
SET GLOBAL validate_password.policy = 0;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.special_char_count = 0;
SET GLOBAL validate_password.check_user_name = 0;
ALTER USER 'user'@'localhost' IDENTIFIED BY 'pass';
FLUSH PRIVILEGES;
No they can't. But:
template<typename T>
class Foo {
public:
template<typename P>
void f(const P& p) {
((T*)this)->f<P>(p);
}
};
class Bar : public Foo<Bar> {
public:
template<typename P>
void f(const P& p) {
std::cout << p << std::endl;
}
};
int main() {
Bar bar;
Bar *pbar = &bar;
pbar -> f(1);
Foo<Bar> *pfoo = &bar;
pfoo -> f(1);
};
has much the same effect if all you want to do is have a common interface and defer implementation to subclasses.
GuestureDetecter Works Well on Most Devices, I would like to know how the time between two clicks can be customized on double click event, i wasn't able to do that. I updated the above code by "Bughi" "DoubleClickListner", added a timer using handler that executes a code after a specific delay on single click, and if double click is performed before that delay it cancels the timer and single click task and only execute double click task. Code is working Fine Makes it perfect to use as double click listner:
private Timer timer = null; //at class level;
private int DELAY = 500;
view.setOnClickListener(new DoubleClickListener() {
@Override
public void onSingleClick(View v) {
final Handler handler = new Handler();
final Runnable mRunnable = new Runnable() {
public void run() {
processSingleClickEvent(v); //Do what ever u want on single click
}
};
TimerTask timertask = new TimerTask() {
@Override
public void run() {
handler.post(mRunnable);
}
};
timer = new Timer();
timer.schedule(timertask, DELAY);
}
@Override
public void onDoubleClick(View v) {
if(timer!=null)
{
timer.cancel(); //Cancels Running Tasks or Waiting Tasks.
timer.purge(); //Frees Memory by erasing cancelled Tasks.
}
processDoubleClickEvent(v);//Do what ever u want on Double Click
}
});
Use sed's substitution: sed 's/"//g'
s/X/Y/
replaces X with Y.
g
means all occurrences should be replaced, not just the first one.
Your strcpy line attempts to store 9 bytes, not 8, because of the NUL terminator. It invokes undefined behaviour.
The call to free may or may not crash. The memory "after" the 4 bytes of your allocation might be used for something else by your C or C++ implementation. If it is used for something else, then scribbling all over it will cause that "something else" to go wrong, but if it isn't used for anything else, then you could happen to get away with it. "Getting away with it" might sound good, but is actually bad, since it means your code will appear to run OK, but on a future run you might not get away with it.
With a debugging-style memory allocator, you might find that a special guard value has been written there, and that free checks for that value and panics if it doesn't find it.
Otherwise, you might find that the next 5 bytes includes part of a link node belonging to some other block of memory which hasn't been allocated yet. Freeing your block could well involved adding it to a list of available blocks, and because you've scribbled in the list node, that operation could dereference a pointer with an invalid value, causing a crash.
It all depends on the memory allocator - different implementations use different mechanisms.
You can add filters to top
while it is running, just press the o key and then type in a filter expression. For example, to monitor all java processes use the filter expression COMMAND=java
. You can add multiple filters by pressing the key again, you can filter by user with the u key, and you can clear all filters with the = key.
(df.groupby(['col5', 'col2']).size()
.sort_values(ascending=False)
.reset_index(name='count')
.drop_duplicates(subset='col2'))
col5 col2 count
0 3 A 3
1 1 D 3
2 5 B 2
6 3 C 1
Explanation
The result of the groupby size
method is a Series with col5
and col2
in the index. From here, you can use another groupby method to find the maximum value of each value in col2
but it is not necessary to do. You can simply sort all the values descendingly and then keep only the rows with the first occurrence of col2
with the drop_duplicates
method.
Based on your question:
My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?
Using the code you gave, you can do this:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import thread
def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(1024)
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
msg = raw_input('SERVER >> ')
#Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
clientsocket.send(msg)
clientsocket.close()
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print 'Got connection from', addr
while True:
c, addr = s.accept() # Establish connection with client.
thread.start_new_thread(on_new_client,(c,addr))
#Note it's (addr,) not (addr) because second parameter is a tuple
#Edit: (c,addr)
#that's how you pass arguments to functions when creating new threads using thread module.
s.close()
As Eli Bendersky mentioned, you can use processes instead of threads, you can also check python threading
module or other async sockets framework. Note: checks are left for you to implement how you want and this is just a basic framework.
One more solution REPLACE (CHAR(current date, ISO),'-','')
That SSL error is misleading. I am using Anaconda 3, conda version 4.6.11, have the most current version of openssl on a Windows 10 instance. I got the issue resolved by changing the security settings on the Anaconda3 folder to Full Control. Don't think this helped, but I also have modified the ..\Anaconda3\Lib\site-packages\certifi\cacert.pem file to include the company's SSL cert.
Hope this info helps you.
Contrary to what most are posting, this is NOT an IDE thing. It is a language thing. The #region is a C# statement.
Try something like that:
if (Request.Cookies["userId"] != null)
{
Response.Cookies["userId"].Expires = DateTime.Now.AddDays(-1);
}
But it also makes sense to use
Session.Abandon();
besides in many scenarios.
Semantically you are asking "insert Competitors where doesn't already exist":
INSERT Competitors (cName)
SELECT DISTINCT Name
FROM CompResults cr
WHERE
NOT EXISTS (SELECT * FROM Competitors c
WHERE cr.Name = c.cName)
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
If you are inserting into a single table, you can write your query like this (maybe only in MySQL):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
The modern solution is an input field of type "search"!
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp
Somewhere in your HTML you define a datalist for later reference:
<datalist id="mylist">
<option value="Option 1">
<option value="Option 2">
<option value="Option 3">
</datalist>
Then you can define your search input like this:
<input type="search" list="mylist">
Voilà. Very nice and easy.
Just use substring: "apple".substring(3);
will return le
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
Implemented with swift on Xcode 6.1
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.tableFooterView?.hidden = true
The second line of code does not cause any effect on presentation, you can use to check if is hidden or not.
Answer taken from this link Fail to hide empty cells in UITableView Swift
Write the telnet session inside a BAT Dos file and execute.
public class ListAdapter extends ArrayAdapter<Item> {
private int resourceLayout;
private Context mContext;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
Item p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.id);
TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
TextView tt3 = (TextView) v.findViewById(R.id.description);
if (tt1 != null) {
tt1.setText(p.getId());
}
if (tt2 != null) {
tt2.setText(p.getCategory().getId());
}
if (tt3 != null) {
tt3.setText(p.getDescription());
}
}
return v;
}
}
This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <Item>
. You need to override View getView(int position, View convertView, ViewGroup parent)
method.
R.layout.itemlistrow
defines the row of the ListView
.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="@+id/TableRow01"
android:layout_height="wrap_content">
<TextView android:textColor="#FFFFFF"
android:id="@+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="id" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp" />
</TableRow>
<TableRow android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:textColor="#FFFFFF"
android:id="@+id/categoryId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="categoryId"
android:layout_weight="1"
android:height="20sp" />
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textColor="#FFFFFF"
android:gravity="right"
android:id="@+id/description"
android:text="description"
android:height="20sp" />
</TableRow>
</TableLayout>
In the MainActivity
define ListView
like this,
ListView yourListView = (ListView) findViewById(R.id.itemListView);
// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>);
yourListView .setAdapter(customAdapter);
In my Notepad++ 7.2.2
, the Preferences
section it's a bit different.
The option is located at: Settings
/ Preferences
/ Language
/ Replace by space
as in the Screenshot.
Had to restart Android Studio after installing GIT for Windows.
Just to point out that if you throw a checked exception in a code and the catch is few levels above, you need to declare the exception in the signature of each method between you and the catch. So, encapsulation is broken because all functions in the path of throw must know about details of that exception.
You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.
Copied from MySQL documentation
As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.
You have to pass a function that accepts two parameters, compares them, and returns a number, so assuming you wanted to sort them by ID you would write...
objArray.sort(function(a,b) {
return a.id-b.id;
});
// objArray is now sorted by Id
The only difference between object literals and constructed objects are the properties inherited from the prototype.
var o = {
'a': 3, 'b': 4,
'doStuff': function() {
alert(this.a + this.b);
}
};
o.doStuff(); // displays: 7
You could make a struct factory.
function makeStruct(names) {
var names = names.split(' ');
var count = names.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[names[i]] = arguments[i];
}
}
return constructor;
}
var Item = makeStruct("id speaker country");
var row = new Item(1, 'john', 'au');
alert(row.speaker); // displays: john
You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:
Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..
#ftp server
$ftp = "ftp://example.com/"
$user = "XX"
$pass = "XXX"
$SetType = "bin"
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in $remotePickupDir){
$uri = New-Object System.Uri($ftp+$item.Name)
#$webclient.UploadFile($uri,$item.FullName)
$webclient.DownloadFile($uri,$item.FullName)
}
One issue with REPLACE
will be where city names contain the district name. You can use something like.
SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM dbo.tblOrtsteileGeo O
JOIN dbo.Cities C
ON C.foo = O.foo
WHERE O.GKZ = '06440004'
Array.isArray
is the way to go about this. For example:
var arr = ['tuna', 'chicken', 'pb&j'];
var obj = {sandwich: 'tuna', chips: 'cape cod'};
// Returns true
Array.isArray(arr);
// Return false
Array.isArray(obj);
A one-liner using regex, get all \g
starting characters of words \b[a-zA-Z]
, and apply .toUpperCase()
const textString = "Convert string to title case with Javascript.";
const converted = textString.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
console.log(converted)
_x000D_
I have Android Studio version 3.1.2, it shows project full path when you click Build tab in bottom-left location of the studio.
In the newer apache poi versions:
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
For me, adding the foreground
to CardView
didn't work (reason unknown :/)
Adding the same to it's child layout did the trick.
CODE:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:focusable="true"
android:clickable="true"
card_view:cardCornerRadius="@dimen/card_corner_radius"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:id="@+id/card_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:padding="@dimen/card_padding">
</LinearLayout>
</android.support.v7.widget.CardView>
The advice here about removing the nbproject directory is not quite the whole story.
What Netbeans seems to do (and we are guessing at reverse engineering here) is to look for an xml file which has opening and closing project tags in it. This it concludes is evidence of an already existing project. Now if your files have an nbproject directory there, that will contain a project.xml file which contains the said tags. So removing that will do what you want.
But, my files don't have a nbproject directory but still NetBeans tells me there is an existing project maybe in memory. The reason is: my files include a file called pom.xml and that contains the said project tags in the xml (it was created by an entirely different system). Once that xml file is removed, then NetBeans will create an html project for me importing my code.
In sum: look through any xml files in you existing code, and be wary of project tags.
The reason reset
and revert
tend to come up a lot in the same conversations is because different version control systems use them to mean different things.
In particular, people who are used to SVN or P4 who want to throw away uncommitted changes to a file will often reach for revert
before being told that they actually want reset
.
Similarly, the revert
equivalent in other VCSes is often called rollback
or something similar - but "rollback" can also mean "I want to completely discard the last few commits", which is appropriate for reset
but not revert
. So, there's a lot of confusion where people know what they want to do, but aren't clear on which command they should be using for it.
As for your actual questions about revert...
Okay, you're going to use git revert but how?
git revert first-bad-commit..last-bad-commit
And after running git revert do you have to do something else after? Do you have to commit the changes revert made or does revert directly commit to the repo or what??
By default, git revert
prompts you for a commit message and then commits the results. This can be overridden. I quote the man page:
--edit
With this option, git revert will let you edit the commit message prior to committing the revert. This is the default if you run the command from a terminal.
--no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.
This is useful when reverting more than one commits' effect to your index in a row.
In particular, by default it creates a new commit for each commit you're reverting. You can use revert --no-commit
to create changes reverting all of them without committing those changes as individual commits, then commit at your leisure.
In my case none of the posted solutions worked. I had to delete the project and make a fresh checkout from the SVN server. Lucky me the project was hosted in a version control system. Don't know what I'd do otherwise.
Yes regex can certainly be used to extract part of a string. Unfortunately different flavours of *nix and different tools use slightly different Regex variants.
This sed command should work on most flavours (Tested on OS/X and Redhat)
echo '12 BBQ ,45 rofl, 89 lol' | sed 's/^.*,\([0-9][0-9]*\).*$/\1/g'
You can find a few examples here:
// Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable contacts = ds.Tables["Contact"]; DataTable orders = ds.Tables["SalesOrderHeader"]; var query = contacts.AsEnumerable().Join(orders.AsEnumerable(), order => order.Field<Int32>("ContactID"), contact => contact.Field<Int32>("ContactID"), (contact, order) => new { ContactID = contact.Field<Int32>("ContactID"), SalesOrderID = order.Field<Int32>("SalesOrderID"), FirstName = contact.Field<string>("FirstName"), Lastname = contact.Field<string>("Lastname"), TotalDue = order.Field<decimal>("TotalDue") }); foreach (var contact_order in query) { Console.WriteLine("ContactID: {0} " + "SalesOrderID: {1} " + "FirstName: {2} " + "Lastname: {3} " + "TotalDue: {4}", contact_order.ContactID, contact_order.SalesOrderID, contact_order.FirstName, contact_order.Lastname, contact_order.TotalDue); }
Or just google for 'linq join method syntax'.
To upload an image simple drag and drop from ur desktop or from anywhere n u can achieve this by copying the image and pasting it on the text area using ctrl+v
I also had the similar requirement. Most of the examples on net are asking to create models and create forms which I did not wanna use. Here is my final code.
if request.method == 'POST':
file1 = request.FILES['file']
contentOfFile = file1.read()
if file1:
return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})
And in HTML to upload I wrote:
{% block content %}
<h1>File content</h1>
<form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
<input type="submit" value="Upload" />
</form>
{% endblock %}
Following is the HTML which displays content of file:
{% block content %}
<h3>File uploaded successfully</h3>
{{file.name}}
</br>content = {{contentOfFile}}
{% endblock %}
hsb.s = max != 0 ? 255 * delta / max : 0;
?
is a ternary operator. It works like an if
in conjunction with the :
!=
means not equals
So, the long form of this line would be
if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}
public static boolean isNull(String str) {
return str == null ? true : false;
}
public static boolean isNullOrBlank(String param) {
if (isNull(param) || param.trim().length() == 0) {
return true;
}
return false;
}
My current setup (on MVC3, but I think it still applies) relies on having an ErrorController
, so I use:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>
And the controller contains the following:
public class ErrorController : Controller
{
public ViewResult Index()
{
return View("Error");
}
public ViewResult NotFound()
{
Response.StatusCode = 404; //you may want to set this to 200
return View("NotFound");
}
}
And the views just the way you implement them. I tend to add a bit of logic though, to show the stack trace and error information if the application is in debug mode. So Error.cshtml looks something like this:
@model System.Web.Mvc.HandleErrorInfo
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Error";
}
<div class="list-header clearfix">
<span>Error</span>
</div>
<div class="list-sfs-holder">
<div class="alert alert-error">
An unexpected error has occurred. Please contact the system administrator.
</div>
@if (Model != null && HttpContext.Current.IsDebuggingEnabled)
{
<div>
<p>
<b>Exception:</b> @Model.Exception.Message<br />
<b>Controller:</b> @Model.ControllerName<br />
<b>Action:</b> @Model.ActionName
</p>
<div style="overflow:scroll">
<pre>
@Model.Exception.StackTrace
</pre>
</div>
</div>
}
</div>
Use env
.
For example, env FOO=BAR command
. Note that the environment variables will be restored/unchanged again when command
finishes executing.
Just be careful about about shell substitution happening, i.e. if you want to reference $FOO
explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env
.
$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR
For those of you who don't want to get rid of the bouncing but just to know when it stops (for example to start some calculation of screen distances), you can do the following (container is the overflowing container element):
const isBouncing = this.container.scrollTop < 0 ||
this.container.scrollTop + this.container.offsetHeight >
this.container.scrollHeight
// Without Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
variable = a;
}
};
Here compiler follows following steps to create an object of type MyClass
1. Type’s constructor is called first for “a”.
2. The assignment operator of “Type” is called inside body of MyClass() constructor to assign
variable = a;
And then finally destructor of “Type” is called for “a” since it goes out of scope.
Now consider the same code with MyClass() constructor with Initializer List
// With Initializer List
class MyClass {
Type variable;
public:
MyClass(Type a):variable(a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
}
};
With the Initializer List, following steps are followed by compiler:
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB
You can dowload the update here
Use below code
val textview = findViewById<TextView>(R.id.textview)
textview.setOnClickListener(clickListener)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener(clickListener)
clickListener code.
val clickListener = View.OnClickListener {view ->
when (view.getId()) {
R.id.textview -> firstFun()
R.id.button -> secondFun()
}
}
Look at this Howto in the MSDN Documentation: Run the Transact-SQL Debugger - it's not with PRINT statements, but maybe it helps you anyway to debug your code.
This YouTube video: SQL Server 2008 T-SQL Debugger shows the use of the Debugger.
=> Stored procedures are written in Transact-SQL. This allows you to debug all Transact-SQL code and so it's like debugging in Visual Studio with defining breakpoints and watching the variables.
You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.
You need $event.currentTarget
instead of $event.target
.
The given solution requires enough free HDD, the actual problem was the HDD memory shortage. So If you don't have an alternative server or free disk space, you need some other alternative.
I faced this error with my production server (Linode VPS) when I was running a bulk download into MySQL. Its not a proper solution but VERY QUICK FIX, which we often need in production to bring things UP FAST.
Right click in the query pane, select Query Options...
and in the Execution->General section (the default when you first open it) there is an Execution time-out
setting.
You can also use the local commandline php-cli:
* * * * * php /local/root/path/to/tasks.php > /dev/null
It is faster and decrease load for your webserver.
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
In Python3, csv.reader
expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs
module:
import csv
import codecs
ifile = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
print (row)
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
The manual page (or the online GNU manual) pretty much explains everything.
For each result, command {}
is executed. All occurences of {}
are replaced by the filename. ;
is prefixed with a slash to prevent the shell from interpreting it.
Each result is appended to command
and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:
the total number of invocations of the command will be much less than the number of matched files.
Note this quote from the manual page:
The command line is built in much the same way that xargs builds its command lines
That's why no characters are allowed between {}
and +
except for whitespace. +
makes find detect that the arguments should be appended to the command just like xargs
.
Luckily, the GNU implementation of mv
can accept the target directory as an argument, with either -t
or the longer parameter --target
. It's usage will be:
mv -t target file1 file2 ...
Your find
command becomes:
find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+
From the manual page:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.
A cleaner approach ( only for test environment) in httpcliet4.3.3 is as follows.
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
here's a short paragraph from this article How to Make Frames (Main Windows) - The Java Tutorials - Oracle that explains what setBounds method does in addition to some other similar methods:
The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
the parameters of setBounds are (int x, int y, int width, int height) x and y are define the position/location and width and height define the size/dimension of the frame.
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
Just want to add to the excellent answer of @Lin:
5) B. If you don't have SQL Management Studio, go to "SQL Server Object Explorer". If you cannot see your project db in the localdb "SQL Server Object Explorer", then click on "Add SQL server" button to add it to the list manually. Then you can delete the db from the list.
try
{
DataTable sheet1 = new DataTable("Excel Sheet");
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = @"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
This worked for me. Please try it and let me know for queries.
I got it!...hehe
protected DataTable RetrieveEmployeeSubInfo(string employeeNo)
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
try
{
cmd = new SqlCommand("RETRIEVE_EMPLOYEE", pl.ConnOpen());
cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception x)
{
MessageBox.Show(x.GetBaseException().ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cmd.Dispose();
pl.MySQLConn.Close();
}
return dt;
}
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
Use a JOIN
in the DELETE
statement.
DELETE p, pa
FROM pets p
JOIN pets_activities pa ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
Alternatively you can use...
DELETE pa
FROM pets_activities pa
JOIN pets p ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
...to delete only from pets_activities
See this.
For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS
, NOT EXISTS
, IN
, NOT IN
and etc. But the one above where you specify from which tables to delete with an alias before the FROM
clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS
in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.
I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them
What is ARIA?
If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.
ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.
And see this you tube video for ARIA live.
You could also do this:
#!/usr/bin/perl
use strict;
use warnings;
$^I = '.bak'; # create a backup copy
while (<>) {
s/<PREF>/ABCD/g; # do the replacement
print; # print to the modified file
}
Invoke the script with by
./script.pl input_file
You will get a file named input_file
, containing your changes, and a file named input_file.bak
, which is simply a copy of the original file.
Based on the great answers of @Nelson, @Barun and @Robert, here is a Bash script that generates random numbers.
/dev/urandom
which is much better than Bash's built-in $RANDOM
#!/usr/bin/env bash
digits=10
rand=$(od -A n -t d -N 2 /dev/urandom |tr -d ' ')
num=$((rand % 10))
while [ ${#num} -lt $digits ]; do
rand=$(od -A n -t d -N 1 /dev/urandom |tr -d ' ')
num="${num}$((rand % 10))"
done
echo $num
Above solutions not helped me, but I resolve same issue by next way
private setHeaders(params) {
const accessToken = this.localStorageService.get('token');
const reqData = {
headers: {
Authorization: `Bearer ${accessToken}`
},
};
if(params) {
let reqParams = {};
Object.keys(params).map(k =>{
reqParams[k] = params[k];
});
reqData['params'] = reqParams;
}
return reqData;
}
and send request
this.http.get(this.getUrl(url), this.setHeaders(params))
Its work with NestJS backend, with other I don't know.
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
private void BackupManager_Load(object sender, EventArgs e)
{
txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
}
private void btnDBBackup_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
{
BackUp();
}
else
{
MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtFileName.Focus();
return;
}
}
private void BackUp()
{
try
{
progressBar1.Value = 0;
for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
{
}
pl.DbName = "Inventry";
pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";
for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
{
}
bl.DbBackUp(pl);
for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
{
}
for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
{
}
for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
{
}
if (progressBar1.Value == progressBar1.Maximum)
{
MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
progressBar1.Value = 0;
}
}
Github has a zip endpoint that in my opinion is preferable to using the git protocol. The advantages are:
#egg=<project name>
You usually want requirements.txt entries to look like this, e.g. without the -e
prefix:
https://github.com/org/package/archive/1a58aa586efd4bca37f2cfb9d9348958986aab6c.zip
To install from main branch:
https://github.com/org/package/archive/main.zip
You simply add another @font-face
rule:
@font-face {
font-family: CustomFont;
src: url('CustomFont.ttf');
}
@font-face {
font-family: CustomFont2;
src: url('CustomFont2.ttf');
}
If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.
JPanel p=new JPanel();
GridBagLayout layout=new GridBagLayout();
p.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=0;
p2.add("",gbc);
I think I got the reason for the above error. It is the corporate proxy(virtual private network) provided in order to work in the client network. Without that connection I frequently faced the same problem be it maven build or npm install.
getrusage() can help you in determining the usage of current process or its child
Update: I can't remember an API. But all details will be in /proc/PID/stat, so if we could parse it, we can get the percentage.
EDIT: Since CPU % is not straight forward to calculate, You could use sampling kind of stuff here. Read ctime and utime for a PID at a point in time and read the same values again after 1 sec. Find the difference and divide by hundred. You will get utilization for that process for past one second.
(might get more complex if there are many processors)
The inplace
parameter:
df.dropna(axis='index', how='all', inplace=True)
in Pandas
and in general means:
1. Pandas creates a copy of the original data
2. ... does some computation on it
3. ... assigns the results to the original data.
4. ... deletes the copy.
As you can read in the rest of my answer's further below, we still can have good reason to use this parameter i.e. the inplace operations
, but we should avoid it if we can, as it generate more issues, as:
1. Your code will be harder to debug (Actually SettingwithCopyWarning stands for warning you to this possible problem)
2. Conflict with method chaining
Definitely yes. If we use pandas or any tool for handeling huge dataset, we can easily face the situation, where some big data can consume our entire memory. To avoid this unwanted effect we can use some technics like method chaining:
(
wine.rename(columns={"color_intensity": "ci"})
.assign(color_filter=lambda x: np.where((x.hue > 1) & (x.ci > 7), 1, 0))
.query("alcohol > 14 and color_filter == 1")
.sort_values("alcohol", ascending=False)
.reset_index(drop=True)
.loc[:, ["alcohol", "ci", "hue"]]
)
which make our code more compact (though harder to interpret and debug too) and consumes less memory as the chained methods works with the other method's returned values, thus resulting in only one copy of the input data. We can see clearly, that we will have 2 x original data memory consumption after this operations.
Or we can use inplace
parameter (though harder to interpret and debug too) our memory consumption will be 2 x original data, but our memory consumption after this operation remains 1 x original data, which if somebody whenever worked with huge datasets exactly knows can be a big benefit.
Avoid using inplace
parameter unless you don't work with huge data and be aware of its possible issues in case of still using of it.
Try setting the type of your parameter to [bool]
:
param
(
[int]$Turn = 0
[bool]$Unity = $false
)
switch ($Unity)
{
$true { "That was true."; break }
default { "Whatever it was, it wasn't true."; break }
}
This example defaults $Unity
to $false
if no input is provided.
Usage
.\RunScript.ps1 -Turn 1 -Unity $false
Runnable
is an interface defined as so:
interface Runnable {
public void run();
}
To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {
It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.
If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.
It should also be noted that Threads implement Runnable
, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable)
without overriding Thread's run
method.
egrep -o '^[^:]*:'
Try these various things
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar","foo"], "B":[0,1,1,1,1], "C":["A","A","B","A","A"]})
>>>df.drop_duplicates( "A" , keep='first')
or
>>>df.drop_duplicates( keep='first')
or
>>>df.drop_duplicates( keep='last')
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".
For the last enterprise application I worked on that needed to handle a notable amount of CSV -- a couple of months ago -- I used SuperCSV at sourceforge and found it simple, robust and problem-free.
Add:
#ifdef _WIN32
if (AttachConsole(ATTACH_PARENT_PROCESS)) {
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
#endif
at the top of main()
. This will enable output to the console only if the program is started in a console, and won't pop up a console window in other situations. If you want to create a console window to display messages when you run the app outside a console you can change the condition to:
if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
Below steps by sztupy worked for me
I went to Control Panel\Network and Internet\Network and Sharing Center and clicked on Change adapter settings
I clicked on Incoming Connections and right clicked on properties
The VPN click box at the bottom of the General tab was on, so I unchecked it
Under Users, I also unchecked a previous user I had allowed to copy some data weeks before
Then I clicked okay
Closed the control panel and restarted the XAMPP control panel
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
I just burned a solid 3 hours trying to solve the same problem. Specifically, I wanted to "replace" the entire document if it exists, or insert it otherwise. Here's the solution:
var contact = new Contact({
phone: request.phone,
status: request.status
});
// Convert the Model instance to a simple object using Model's 'toObject' function
// to prevent weirdness like infinite looping...
var upsertData = contact.toObject();
// Delete the _id property, otherwise Mongo will return a "Mod on _id not allowed" error
delete upsertData._id;
// Do the upsert, which works like this: If no Contact document exists with
// _id = contact.id, then create a new doc using upsertData.
// Otherwise, update the existing doc with upsertData
Contact.update({_id: contact.id}, upsertData, {upsert: true}, function(err{...});
I created an issue on the Mongoose project page requesting that info about this be added to the docs.
I like to use a util method that returns a collector for ArrayList
when that is what I want.
I think the solution using Collectors.toCollection(ArrayList::new)
is a little too noisy for such a common operation.
Example:
ArrayList<Long> result = sourceLongList.stream()
.filter(l -> l > 100)
.collect(toArrayList());
public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
return Collectors.toCollection(ArrayList::new);
}
With this answer I also want to demonstrate how simple it is to create and use custom collectors, which is very useful generally.
Below solution may be simpler:
df1.reset_index().groupby( [ "Name", "City"],as_index=False ).count()
Normally the dot matches any character except newlines.
So if .*
isn't working, set the "dot matches newlines, too" option (or use (?s).*
).
If you're using JavaScript, which doesn't have a "dotall" option, try [\s\S]*
. This means "match any number of characters that are either whitespace or non-whitespace" - effectively "match any string".
Another option that only works for JavaScript (and is not recognized by any other regex flavor) is [^]*
which also matches any string. But [\s\S]*
seems to be more widely used, perhaps because it's more portable.
Try adding --user-install
instead of using sudo
:
gem install mygem --user-install
Use net use
or New-PSDrive
to create a new drive:
New-PsDrive: create a new PsDrive only visible in PowerShell environment:
New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
Net use: create a new drive visible in all parts of the OS.
Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
A 'macroable' replacement to get the SQL query with the bindings.
Add below macro function in AppServiceProvider
boot()
method.
\Illuminate\Database\Query\Builder::macro('toRawSql', function(){
return array_reduce($this->getBindings(), function($sql, $binding){
return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
}, $this->toSql());
});
Add an alias for the Eloquent Builder. (Laravel 5.4+)
\Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
return ($this->getQuery()->toRawSql());
});
Then debug as usual. (Laravel 5.4+)
E.g. Query Builder
\Log::debug(\DB::table('users')->limit(1)->toRawSql())
E.g. Eloquent Builder
\Log::debug(\App\User::limit(1)->toRawSql());
Note: from Laravel 5.1 to 5.3, Since Eloquent Builder doesn't make use of the
Macroable
trait, cannot addtoRawSql
an alias to the Eloquent Builder on the fly. Follow the below example to achieve the same.
E.g. Eloquent Builder (Laravel 5.1 - 5.3)
\Log::debug(\App\User::limit(1)->getQuery()->toRawSql());
Trying cleaning AND rebuilding your project: In Android Studio, open up the Build tab at the top left and try both the Clean and Rebuild options.
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
In case you do have multiple inner/anonymous runnables passed to same handler, and you want to cancel all at same event use
handler.removeCallbacksAndMessages(null);
As per documentation,
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
BEST ANSWER 1:
ActionNameSelectorAttribute
mentioned in
ANSWER 2
Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor
Second Approach
Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.
Third Approach: Client Script
<button name="ClientCancel" type="button"
onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))"
style="display:none;"></a>
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
I'm sure you are using a old version. You must use the last version available at master branch:
I also came across the same error. Here is the fix: If you are using Cmake-GUI:
If you missed the 3rd step:
*** No rule to make target `install'. Stop.
error will occur.
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:
I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.
I had the same problem (different web app though) with the error message and it turned out to be the MIME-Type for .js files was text/x-js
instead of application/javascript
due to a duplicate entry in mime.types on the server that was responsible for serving the js files. It seems that this is happening if the header X-Content-Type-Options: nosniff
is set, which makes Firefox (and Chrome) block the content of the js files.
You can make it even simplier, if you want to avoid extra structures.
service:
mappings:
key1: value1
key2: value2
@Configuration
@EnableConfigurationProperties
public class ServiceConfigurationProperties {
@Bean
@ConfigurationProperties(prefix = "service.mappings")
public Map<String, String> serviceMappings() {
return new HashMap<>();
}
}
And then use it as usual, for example with a constructor:
public class Foo {
private final Map<String, String> serviceMappings;
public Foo(Map<String, String> serviceMappings) {
this.serviceMappings = serviceMappings;
}
}
this worked for me:
.fb-like.fb_edge_widget_with_comment.fb_iframe_widget {
height: 26px;
overflow: hidden;
width: 138px;
}
Use this code for Impersonation its tested in MVC.NET maybe for dot net core it required some change, If you want to dot net core let me know I will share.
public static class ImpersonationAuthenticationNew
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string usernamee, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
public static bool Login(string domain,string username, string password)
{
IntPtr token = IntPtr.Zero;
var IsSuccess = LogonUser(username, domain, password, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50, ref token);
if (IsSuccess)
{
using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
{
var xIdentity = WindowsIdentity.GetCurrent();
#region Start ImpersonationContext Scope
try
{
// TYPE YOUR CODE HERE
}
catch (Exception ex) { throw (ex); }
finally {
person.Undo();
CloseHandle(token);
return true;
}
#endregion
}
}
return false;
}
}
#region Enums
public enum LogonType
{
/// <summary>
/// This logon type is intended for users who will be interactively using the computer, such as a user being logged on
/// by a terminal server, remote shell, or similar process.
/// This logon type has the additional expense of caching logon information for disconnected operations;
/// therefore, it is inappropriate for some client/server applications,
/// such as a mail server.
/// </summary>
LOGON32_LOGON_INTERACTIVE = 2,
/// <summary>
/// This logon type is intended for high performance servers to authenticate plaintext passwords.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_NETWORK = 3,
/// <summary>
/// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
/// their direct intervention. This type is also for higher performance servers that process many plaintext
/// authentication attempts at a time, such as mail or Web servers.
/// The LogonUser function does not cache credentials for this logon type.
/// </summary>
LOGON32_LOGON_BATCH = 4,
/// <summary>
/// Indicates a service-type logon. The account provided must have the service privilege enabled.
/// </summary>
LOGON32_LOGON_SERVICE = 5,
/// <summary>
/// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
/// This logon type can generate a unique audit record that shows when the workstation was unlocked.
/// </summary>
LOGON32_LOGON_UNLOCK = 7,
/// <summary>
/// This logon type preserves the name and password in the authentication package, which allows the server to make
/// connections to other network servers while impersonating the client. A server can accept plaintext credentials
/// from a client, call LogonUser, verify that the user can access the system across the network, and still
/// communicate with other servers.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
/// <summary>
/// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
/// The new logon session has the same local identifier but uses different credentials for other network connections.
/// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
/// NOTE: Windows NT: This value is not supported.
/// </summary>
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
public enum LogonProvider
{
/// <summary>
/// Use the standard logon provider for the system.
/// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
/// is not in UPN format. In this case, the default provider is NTLM.
/// NOTE: Windows 2000/NT: The default security provider is NTLM.
/// </summary>
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
}
#endregion
Why don't you take a look to this answer
Including javascript files inside javascript files
In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.
To put the same text in a certain number of cells do the following:
You will find that all the highlighted cells now have the same data in them. Have a nice day.
Current version:
SQL Server Management Studio
Direct link: http://go.microsoft.com/fwlink/?LinkID=828615
Version Information
This release of SSMS uses the Visual Studio 2015 Isolated shell. The release number: 16.4.1 The build number for this release: 13.0.15900.1 Supported SQL Server versions This version of SSMS works with all supported versions of SQL Server (SQL Server 2008 - SQL Server 2016), and provides the greatest level of support for working with the latest cloud features in Azure SQL Database. There is no explicit block for SQL Server 2000 or SQL Server 2005, but some features may not work properly. Additionally, one SSMS 16.x release or SSMS 2016 can be installed side by side with previous versions of SSMS 2014 and earlier.
Older version of the answer for 2012
Installation steps:
Command: SQLEXPRWT_x64_ENU.exe /ACTION=INSTALL /FEATURES=TOOLS /QUIETSIMPLE /IAcceptSQLServerLicenseTerms
original answer was: https://dba.stackexchange.com/questions/14438/how-to-install-sql-server-2008-r2-profiler Now posted: http://blog.cpodesign.com/blog/sql-2012-installing-sql-profiler/
OnInit
was automatically implemented on my class while using the ng new ...
key phrase on angular CLI to generate the new component. So after I removed the implementation and removed the empty method that was generated, the problem is resolved.
public static function countDays($date1,$date2)
{
$date1 = strtotime($date1); // or your date as well
$date2 = strtotime($date2);
$datediff = $date1 - $date2;
return floor($datediff/(60*60*24));
}
public static function dateRange($date1,$date2)
{
$count = static::countDays($date1,$date2) + 1;
$dates = array();
for($i=0;$i<$count;$i++)
{
$dates[] = date("Y-m-d",strtotime($date2.'+'.$i.' days'));
}
return $dates;
}
The other answers that I have seen miss some permissions that are possible in the database. The first query in the code below will get the database level permission for everything that is not a system object. It generates the appropriate GRANT statements as well. The second query gets all the role meberships.
This has to be run for each database, but is too long to use with sp_MSforeachdb. If you want to do that you'd have to add it to the master database as a system stored procedure.
To cover all possibilities you'd also have to have a script that checks the server level permissions.
SELECT DB_NAME() AS database_name
, class
, class_desc
, major_id
, minor_id
, grantee_principal_id
, grantor_principal_id
, databasepermissions.type
, permission_name
, STATE
, state_desc
, granteedatabaseprincipal.name AS grantee_name
, granteedatabaseprincipal.type_desc AS grantee_type_desc
, granteeserverprincipal.name AS grantee_principal_name
, granteeserverprincipal.type_desc AS grantee_principal_type_desc
, grantor.name AS grantor_name
, granted_on_name
, permissionstatement + N' TO ' + QUOTENAME(granteedatabaseprincipal.name) + CASE
WHEN STATE = N'W'
THEN N' WITH GRANT OPTION'
ELSE N''
END AS permissionstatement
FROM (
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(CONVERT(NVARCHAR(MAX), DB_NAME())) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS AS permissionstatement
FROM sys.database_permissions
WHERE (sys.database_permissions.class = 0)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.schemas.name) + N'.' + QUOTENAME(sys.objects.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ' + QUOTENAME(sys.schemas.name) + N'.' + QUOTENAME(sys.objects.name) + COALESCE(N' (' + QUOTENAME(sys.columns.name) + N')', N'') AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.objects
ON sys.objects.object_id = sys.database_permissions.major_id
INNER JOIN sys.schemas
ON sys.schemas.schema_id = sys.objects.schema_id
LEFT OUTER JOIN sys.columns
ON sys.columns.object_id = sys.database_permissions.major_id
AND sys.columns.column_id = sys.database_permissions.minor_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 1)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.schemas.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON SCHEMA::' + QUOTENAME(sys.schemas.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.schemas
ON sys.schemas.schema_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 3)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(targetPrincipal.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ' + targetPrincipal.type_desc + N'::' + QUOTENAME(targetPrincipal.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.database_principals AS targetPrincipal
ON targetPrincipal.principal_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 4)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.assemblies.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ASSEMBLY::' + QUOTENAME(sys.assemblies.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.assemblies
ON sys.assemblies.assembly_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 5)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.types.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON TYPE::' + QUOTENAME(sys.types.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.types
ON sys.types.user_type_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 6)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.types.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON TYPE::' + QUOTENAME(sys.types.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.types
ON sys.types.user_type_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 6)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.xml_schema_collections.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON XML SCHEMA COLLECTION::' + QUOTENAME(sys.xml_schema_collections.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.xml_schema_collections
ON sys.xml_schema_collections.xml_collection_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 10)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.service_message_types.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON MESSAGE TYPE::' + QUOTENAME(sys.service_message_types.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.service_message_types
ON sys.service_message_types.message_type_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 15)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.service_contracts.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON CONTRACT::' + QUOTENAME(sys.service_contracts.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.service_contracts
ON sys.service_contracts.service_contract_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 16)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.services.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON SERVICE::' + QUOTENAME(sys.services.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.services
ON sys.services.service_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 17)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.remote_service_bindings.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON REMOTE SERVICE BINDING::' + QUOTENAME(sys.remote_service_bindings.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.remote_service_bindings
ON sys.remote_service_bindings.remote_service_binding_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 18)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.routes.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ROUTE::' + QUOTENAME(sys.routes.name COLLATE SQL_Latin1_General_CP1_CI_AS) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.routes
ON sys.routes.route_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 19)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.symmetric_keys.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ASYMMETRIC KEY::' + QUOTENAME(sys.symmetric_keys.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.symmetric_keys
ON sys.symmetric_keys.symmetric_key_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 24)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.certificates.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON CERTIFICATE::' + QUOTENAME(sys.certificates.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.certificates
ON sys.certificates.certificate_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 25)
UNION ALL
SELECT sys.database_permissions.class
, sys.database_permissions.class_desc
, sys.database_permissions.major_id
, sys.database_permissions.minor_id
, sys.database_permissions.grantee_principal_id
, sys.database_permissions.grantor_principal_id
, sys.database_permissions.type
, sys.database_permissions.permission_name
, sys.database_permissions.state
, sys.database_permissions.state_desc
, QUOTENAME(sys.asymmetric_keys.name) AS granted_on_name
, CASE
WHEN sys.database_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.database_permissions.state_desc
END + N' ' + sys.database_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' ON ASYMMETRIC KEY::' + QUOTENAME(sys.asymmetric_keys.name) AS permissionstatement
FROM sys.database_permissions
INNER JOIN sys.asymmetric_keys
ON sys.asymmetric_keys.asymmetric_key_id = sys.database_permissions.major_id
WHERE (sys.database_permissions.major_id >= 0)
AND (sys.database_permissions.class = 26)
) AS databasepermissions
INNER JOIN sys.database_principals AS granteedatabaseprincipal
ON granteedatabaseprincipal.principal_id = grantee_principal_id
LEFT OUTER JOIN sys.server_principals AS granteeserverprincipal
ON granteeserverprincipal.sid = granteedatabaseprincipal.sid
INNER JOIN sys.database_principals AS grantor
ON grantor.principal_id = grantor_principal_id
ORDER BY grantee_name, granted_on_name
SELECT roles.name AS role_name
, roles.principal_id
, roles.type AS role_type
, roles.type_desc AS role_type_desc
, roles.is_fixed_role AS role_is_fixed_role
, memberdatabaseprincipal.name AS member_name
, memberdatabaseprincipal.principal_id AS member_principal_id
, memberdatabaseprincipal.type AS member_type
, memberdatabaseprincipal.type_desc AS member_type_desc
, memberdatabaseprincipal.is_fixed_role AS member_is_fixed_role
, memberserverprincipal.name AS member_principal_name
, memberserverprincipal.type_desc member_principal_type_desc
, N'ALTER ROLE ' + QUOTENAME(roles.name) + N' ADD MEMBER ' + QUOTENAME(memberdatabaseprincipal.name) AS AddRoleMembersStatement
FROM sys.database_principals AS roles
INNER JOIN sys.database_role_members
ON sys.database_role_members.role_principal_id = roles.principal_id
INNER JOIN sys.database_principals AS memberdatabaseprincipal
ON memberdatabaseprincipal.principal_id = sys.database_role_members.member_principal_id
LEFT OUTER JOIN sys.server_principals AS memberserverprincipal
ON memberserverprincipal.sid = memberdatabaseprincipal.sid
ORDER BY role_name
, member_name
UPDATE: The following queries will retrieve server level permissions and memberships.
SELECT sys.server_permissions.class
, sys.server_permissions.class_desc
, sys.server_permissions.major_id
, sys.server_permissions.minor_id
, sys.server_permissions.grantee_principal_id
, sys.server_permissions.grantor_principal_id
, sys.server_permissions.type
, sys.server_permissions.permission_name
, sys.server_permissions.state
, sys.server_permissions.state_desc
, granteeserverprincipal.name AS grantee_principal_name
, granteeserverprincipal.type_desc AS grantee_principal_type_desc
, grantorserverprinicipal.name AS grantor_name
, CASE
WHEN sys.server_permissions.state = N'W'
THEN N'GRANT'
ELSE sys.server_permissions.state_desc
END + N' ' + sys.server_permissions.permission_name COLLATE SQL_Latin1_General_CP1_CI_AS + N' TO ' + QUOTENAME(granteeserverprincipal.name) AS permissionstatement
FROM sys.server_principals AS granteeserverprincipal
INNER JOIN sys.server_permissions
ON sys.server_permissions.grantee_principal_id = granteeserverprincipal.principal_id
INNER JOIN sys.server_principals AS grantorserverprinicipal
ON grantorserverprinicipal.principal_id = sys.server_permissions.grantor_principal_id
ORDER BY granteeserverprincipal.name
, sys.server_permissions.permission_name
SELECT roles.name AS server_role_name
, roles.principal_id
, roles.type AS role_type
, roles.type_desc AS role_type_desc
, roles.is_fixed_role AS role_is_fixed_role
, memberserverprincipal.name AS member_principal_name
, memberserverprincipal.principal_id AS member_principal_id
, memberserverprincipal.type AS member_principal_type
, memberserverprincipal.type_desc AS member_principal_type_desc
, memberserverprincipal.is_fixed_role AS member_is_fixed_role
, N'ALTER SERVER ROLE ' + QUOTENAME(roles.name) + N' ADD MEMBER ' + QUOTENAME(memberserverprincipal.name) AS AddRoleMembersStatement
FROM sys.server_principals AS roles
INNER JOIN sys.server_role_members
ON sys.server_role_members.role_principal_id = roles.principal_id
INNER JOIN sys.server_principals AS memberserverprincipal
ON memberserverprincipal.principal_id = sys.server_role_members.member_principal_id
WHERE roles.type = N'R'
ORDER BY server_role_name
, member_principal_name
I've used includes
from Lodash
which is really similar to the native.
My requirements included:
My solution in the end was to use SimpleJson(https://github.com/facebook-csharp-sdk/simple-json).
Although you can install it via a nuget package, I included just that single SimpleJson.cs file (with the MIT license) in my project and referenced it.
I hope this helps someone.
Simply add these to your ggplot:
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge'
could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.
When you use Date()
to calculate the difference in hours is necessary configure the SimpleDateFormat()
in UTC otherwise you get one hour error due to Daylight SavingTime.
A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor
, Math.ceil
, and Math.round
.
> ~~2.5
2
> ~~(-1.4)
-1
return string.Join(", ", strings.ToArray());
In .Net 4, there's a new overload for string.Join
that accepts IEnumerable<string>
. The code would then look like:
return string.Join(", ", strings);
an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));
this worked perfect.. hope this will help someone else too.. :)
You can do it faster without any imports just by using magics:
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
Notice that all env variable are strings, so no need to use "
. You can verify that env-variable is set up by running: %env <name_of_var>
. Or check all of them with %env
.
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
Called "Destructive Methods" They tend to change the original copy of the object you are referring to.
numbers=[1,0,10,5,8]
numbers.collect{|n| puts n*2} # would multiply each number by two
numbers #returns the same original copy
numbers.collect!{|n| puts n*2} # would multiply each number by two and destructs the original copy from the array
numbers # returns [nil,nil,nil,nil,nil]
You're looking for parentNode
, which Element
inherits from Node
:
parentDiv = pDoc.parentNode;
Handy References:
My version is PyCharm Professional edition 3.4, and the Adding a Path part is different.
You can go to "Preferences" --> "Project Interpreter". Choose the tool button at the right top corner.
Then choose "More..." --> "Show path for the selected interpreter" --> "Add". Then you can add a path.
When root (sudo) permissions are required, which is usually 90%+ when using scripts, the methods in previous answers always give you root
as the answer.
To get the current "logged in" user is just as simple, but it requires accessing different variables: $SUDO_UID
and $SUDO_USER
.
They can be echoed:
echo $SUDO_UID
echo $SUDO_USER
Or assigned, for example:
myuid=$SUDO_UID
myuname=$SUDO_USER
The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.
Imagine you are in a bank, trying to get some money out of your account. But it's dark; the bank is pitch black: there's no light and you can't see your hand in front of your face. You are surrounded by another 20 people. They all look the same. And everybody has the same voice. And everyone is a potential bad guy. In other words, HTTP is stateless.
This bank is a funny type of bank - for the sake of argument here's how things work:
The teller can't see or readily recognise you, remember, because the lights are all out. What if your teller gives your $10,000 withdrawal to someone else - the wrong person?! It's absolutely vital that the teller can recognise you as the one who made the withdrawal, so that you can get the money (or resource) that you asked for.
Solution:
When you first appear to the teller, he or she tells you something in secret:
"When ever you are talking to me," says the teller, "you should first identify yourlself as GNASHEU329 - that way I know it's you".
Nobody else knows the secret passcode.
So I decide to go to and chill out for 20 minutes and then later i go to the teller and say "I'd like to collect my withdrawal"
The teller asks me: "who are you??!"
"It's me, Mr George Banks!"
"Prove it!"
And then I tell them my passcode: GNASHEU329
"Certainly Mr Banks!"
That basically is how a session works. It allows one to be uniquely identified in a sea of millions of people. You need to identify yourself every time you deal with the teller.
If you got any questions or are unclear - please post comment and i will try to clear it up for you. The following is not strictly speaking, completely accurate in its terminology, but I hope it's helpful to you in understanding concepts.
The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.
[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
ControllerContext.RouteData.Values.Add("email", "[email protected]");
return RedirectToAction(nameof(ToAction));
// will redirect to /to/[email protected]
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
return RedirectToAction(nameof(ToAction));
// will redirect to /to/<whatever the email param says>
// no need to specify the route part explicitly
}
It stops and starts the services that IIS consists of.
You can think of it as closing the relevant program and starting it up again.
Sets don't have a join
method but you can use str.join
instead.
', '.join(set_3)
The str.join
method will work on any iterable object including lists and sets.
Note: be careful about using this on sets containing integers; you will need to convert the integers to strings before the call to join. For example
set_4 = {1, 2}
', '.join(str(s) for s in set_4)
Instead of
0 * * * * sh /my/script.sh
Use bash -l -c
0 * * * * bash -l -c 'sh /my/script.sh'
All you need to do is make an array of fields and then set it to the class you want like shown below.
Field fld[] = (class name).class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
For example if you did
Field fld[] = Integer.class.getDeclaredFields();
for(Field x : fld)
{System.out.println(x);}
you would get
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID
It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin
using the Join
syntax (at least in method call notation):
persons.LeftJoin(
phoneNumbers,
person => person.Id,
phoneNumber => phoneNumber.PersonId,
(person, phoneNumber) => new
{
Person = person,
PhoneNumber = phoneNumber?.Number
}
);
My code does nothing more than adding a GroupJoin
and a SelectMany
call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector
parameter to keep the whole tree translatable by LINQ-to-Entities.
public static class LeftJoinExtension
{
public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
this IQueryable<TOuter> outer,
IQueryable<TInner> inner,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<TOuter, TInner, TResult>> resultSelector)
{
MethodInfo groupJoin = typeof (Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
.MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
MethodInfo selectMany = typeof (Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
.MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));
var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});
MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);
var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
(t => t.ManyInners.DefaultIfEmpty());
ParameterExpression paramUser = resultSelector.Parameters.First();
ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");
LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());
MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);
return outer.Provider.CreateQuery<TResult>(exprSelectMany);
}
private class LeftJoinIntermediate<TOuter, TInner>
{
public TOuter OneOuter { get; set; }
public IEnumerable<TInner> ManyInners { get; set; }
}
private class Replacer : ExpressionVisitor
{
private readonly ParameterExpression _oldParam;
private readonly Expression _replacement;
public Replacer(ParameterExpression oldParam, Expression replacement)
{
_oldParam = oldParam;
_replacement = replacement;
}
public override Expression Visit(Expression exp)
{
if (exp == _oldParam)
{
return _replacement;
}
return base.Visit(exp);
}
}
}
Hoping to provide a more nuanced answer than any of the ones here, especially as some things have changed since this was originally asked ~4 years ago, and because many of the top-voted answers claiming that you have to set this up as two separate applications are not accurate.
You have two primary architecture options:
These might look something like this:
Option 1 (Client/Server Architecture):
Option 2 (Hybrid Architecture):
The decision between these two will depend on your / your team's experience, as well as the complexity of your UI. The first option is good if you have a lot of JS experience, want to keep your front-end / back-end developers separate, or want to write your entire application as a React single-page-app. The second option is generally better if you are more familiar with Django and want to move quickly while also using React for some parts of your app. I find it's a particularly good fit for full-stack solo-developers.
There is a lot more information in the series "Modern JavaScript for Django Developers", including choosing your architecture, integrating your JS build into a Django project and building a single-page React app.
Full disclosure, I'm the author of that series.
FileReader reads from files on the file system.
Perhaps you intended to use something like this to load a file from the class path
// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
.getResourceAsStream("config.txt");
Or you could extract the file from the jar before reading it.
If you are having 112 columns in one single table and you would like to insert data from source table, you could do as
create table employees as select * from source_employees where employee_id=100;
Or from sqlplus do as
copy from source_schema/password insert employees using select * from
source_employees where employee_id=100;
if(!strcmp(favoriteDairyProduct, "cheese"))
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
You can try:
ps | grep `echo $$` | awk '{ print $4 }'
Or:
echo $SHELL
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
or
form_for @user, :url => whatever_path
Absent of any other information, I'll assume the following XML:
<group>
<item>
<id>item 1</id>
<CategoryName>blue</CategoryName>
</item>
<item>
<id>item 2</id>
<CategoryName></CategoryName>
</item>
<item>
<id>item 3</id>
</item>
...
</group>
A sample use case would look like:
<xsl:for-each select="/group/item">
<xsl:if test="CategoryName">
<!-- will be instantiated for item #1 and item #2 -->
</xsl:if>
<xsl:if test="not(CategoryName)">
<!-- will be instantiated for item #3 -->
</xsl:if>
<xsl:if test="CategoryName != ''">
<!-- will be instantiated for item #1 -->
</xsl:if>
<xsl:if test="CategoryName = ''">
<!-- will be instantiated for item #2 -->
</xsl:if>
</xsl:for-each>
The certutil -repairstore command mentioned in other answers worked for me, but if your certificate is in the "Web Hosting" store and you don't want to move it, the real (internal) name of the "Web Hosting" store is "WebHosting", for anyone following the steps mentioned here.