For case when your interval's end it's date without hours like "from 2017-01-01 to whole day of 2017-01-16" it's better to adjust interval's to 23 hours 59 minutes and 59 seconds like:
end = end.Add(time.Duration(23*time.Hour) + time.Duration(59*time.Minute) + time.Duration(59*time.Second))
if now.After(start) && now.Before(end) {
...
}
When you do a cmp a,b
, the flags are set as if you had calculated a - b
.
Then the jmp
-type instructions check those flags to see if the jump should be made.
In other words, the first block of code you have (with my comments added):
cmp al,dl ; set flags based on the comparison
jg label1 ; then jump based on the flags
would jump to label1
if and only if al
was greater than dl
.
You're probably better off thinking of it as al > dl
but the two choices you have there are mathematically equivalent:
al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0 (cancel the terms on the right hand side)
You need to be careful when using jg
inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.
See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JO | Jump if overflow | | OF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNO | Jump if not overflow | | OF = 0 |
+--------+------------------------------+-------------+--------------------+
| JS | Jump if sign | | SF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNS | Jump if not sign | | SF = 0 |
+--------+------------------------------+-------------+--------------------+
| JE/ | Jump if equal | | ZF = 1 |
| JZ | Jump if zero | | |
+--------+------------------------------+-------------+--------------------+
| JNE/ | Jump if not equal | | ZF = 0 |
| JNZ | Jump if not zero | | |
+--------+------------------------------+-------------+--------------------+
| JP/ | Jump if parity | | PF = 1 |
| JPE | Jump if parity even | | |
+--------+------------------------------+-------------+--------------------+
| JNP/ | Jump if no parity | | PF = 0 |
| JPO | Jump if parity odd | | |
+--------+------------------------------+-------------+--------------------+
| JCXZ/ | Jump if CX is zero | | CX = 0 |
| JECXZ | Jump if ECX is zero | | ECX = 0 |
+--------+------------------------------+-------------+--------------------+
Then the unsigned ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JB/ | Jump if below | unsigned | CF = 1 |
| JNAE/ | Jump if not above or equal | | |
| JC | Jump if carry | | |
+--------+------------------------------+-------------+--------------------+
| JNB/ | Jump if not below | unsigned | CF = 0 |
| JAE/ | Jump if above or equal | | |
| JNC | Jump if not carry | | |
+--------+------------------------------+-------------+--------------------+
| JBE/ | Jump if below or equal | unsigned | CF = 1 or ZF = 1 |
| JNA | Jump if not above | | |
+--------+------------------------------+-------------+--------------------+
| JA/ | Jump if above | unsigned | CF = 0 and ZF = 0 |
| JNBE | Jump if not below or equal | | |
+--------+------------------------------+-------------+--------------------+
And, finally, the signed ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JL/ | Jump if less | signed | SF <> OF |
| JNGE | Jump if not greater or equal | | |
+--------+------------------------------+-------------+--------------------+
| JGE/ | Jump if greater or equal | signed | SF = OF |
| JNL | Jump if not less | | |
+--------+------------------------------+-------------+--------------------+
| JLE/ | Jump if less or equal | signed | ZF = 1 or SF <> OF |
| JNG | Jump if not greater | | |
+--------+------------------------------+-------------+--------------------+
| JG/ | Jump if greater | signed | ZF = 0 and SF = OF |
| JNLE | Jump if not less or equal | | |
+--------+------------------------------+-------------+--------------------+
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
In WPF it seems this code,
System.Windows.Forms.MessageBox.Show("Test");
is replaced with:
System.Windows.MessageBox.Show("Test");
You can set it to NULL
.
> Data$genome <- NULL
> head(Data)
chr region
1 chr1 CDS
2 chr1 exon
3 chr1 CDS
4 chr1 exon
5 chr1 CDS
6 chr1 exon
As pointed out in the comments, here are some other possibilities:
Data[2] <- NULL # Wojciech Sobala
Data[[2]] <- NULL # same as above
Data <- Data[,-2] # Ian Fellows
Data <- Data[-2] # same as above
You can remove multiple columns via:
Data[1:2] <- list(NULL) # Marek
Data[1:2] <- NULL # does not work!
Be careful with matrix-subsetting though, as you can end up with a vector:
Data <- Data[,-(2:3)] # vector
Data <- Data[,-(2:3),drop=FALSE] # still a data.frame
It's not too hard.
Things to take into consideration:
Animated gifs:
If you are looking for animated gifs you can generate them:
AjaxLoad - Ajax Loading gif generator
Another way of doing it:
Another way that I have found that works quite well is the async dialog control that I found on the code project
Just to add that if your truth value can vary, for instance if it is an input from different programming languages or from different types, a more robust method would be:
flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support
And a more performant variant would be (set lookup is O(1)):
TRUTHS = set(['True','true',1,'T','t','1'])
flag = value in truths
cvc-elt.1: Cannot find the declaration of element 'Root'. [7]
Your schemaLocation
attribute on the root element should be xsi:schemaLocation
, and you need to fix it to use the right namespace.
You should probably change the targetNamespace
of the schema and the xmlns
of the document to http://myNameSpace.com
(since namespaces are supposed to be valid URIs, which Test.Namespace
isn't, though urn:Test.Namespace
would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.
(though it still won't validate as your <element2>
contains an <element3>
in the document where the schema expects item
)
You can put this inside your jquery code or it can stand alone:
window.onload = prep;
function prep(){
document.getElementById('somediv').onclick = function(){
document.getElementById('inputField').value ='';
}
}
This could happen if you are using reflection to GetProperty
of an object which is null.
You may use the typescript getter method for this scenario. Like this
public get height() {
return window.innerHeight;
}
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
Print the value
console.log(this.height, this.width);
You won't need any event handler to check for resizing of window, this method will check for size every time automatically.
On one of my sites I had to make a custom search by a lot of data some of it from custom fields here is how my $args look like for one of the options:
$args = array(
'meta_query' => $meta_query,
'tax_query' => array(
$query_tax
),
'posts_per_page' => 10,
'post_type' => 'ad_listing',
'orderby' => $orderby,
'order' => $order,
'paged' => $paged
);
where "$meta_query" is:
$key = "your_custom_key"; //custom_color for example
$value = "blue";//or red or any color
$query_color = array('key' => $key, 'value' => $value);
$meta_query[] = $query_color;
and after that:
query_posts($args);
so you would probably get more info here: http://codex.wordpress.org/Class_Reference/WP_Query and you can search for "meta_query" in the page to get to the info
.btn{
font-size: 20px;
color:black;
}
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
Take a look at strcasecmp()
in strings.h
.
Try this:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
Source: https://www.ndchost.com/wiki/apache/redirect-http-to-https
(I tried so many different blocks of code, this 3 liner worked flawlessly)
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
Use the below attribute in tag to open it in next tab
target="_blank"
The Wikipedia newline article might help you out. Here is an excerpt:
The different newline conventions often cause text files that have been transferred between systems of different types to be displayed incorrectly. For example, files originating on Unix or Apple Macintosh systems may appear as a single long line on some programs running on Microsoft Windows. Conversely, when viewing a file originating from a Windows computer on a Unix system, the extra CR may be displayed as ^M or at the end of each line or as a second line break.
jQuery Mobile doesn't seem to have a css class to center elements (I searched through its css).
But you can write your own additional css.
Try creating your own:
.center-button{
margin: 0 auto;
}
example HTML:
<div data-role="button" class="center-button">button text</div>
and see what happens. You might need to set text-align to center in the wrapping tag, so this might work better:
.center-wrapper{
text-align: center;
}
.center-wrapper * {
margin: 0 auto;
}
example HTML:
<div class="center-wrapper">
<div data-role="button">button text</div>
</div>
Are you putting this line inside the class declaration? In that case you should remove the JSONDeserializer::
.
When implementing the suggestions posted here, I had trouble with the text encoding. It seems the encoding of the XmlWriterSettings
is ignored, and always overridden by the encoding of the stream. When using a StringBuilder
, this is always the text encoding used internally in C#, namely UTF-16.
So here's a version which supports other encodings as well.
IMPORTANT NOTE: The formatting is completely ignored if your XMLDocument
object has its preserveWhitespace
property enabled when loading the document. This had me stumped for a while, so make sure not to enable that.
My final code:
public static void SaveFormattedXml(XmlDocument doc, String outputPath, Encoding encoding)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = "\r\n";
settings.NewLineHandling = NewLineHandling.Replace;
using (MemoryStream memstream = new MemoryStream())
using (StreamWriter sr = new StreamWriter(memstream, encoding))
using (XmlWriter writer = XmlWriter.Create(sr, settings))
using (FileStream fileWriter = new FileStream(outputPath, FileMode.Create))
{
if (doc.ChildNodes.Count > 0 && doc.ChildNodes[0] is XmlProcessingInstruction)
doc.RemoveChild(doc.ChildNodes[0]);
// save xml to XmlWriter made on encoding-specified text writer
doc.Save(writer);
// Flush the streams (not sure if this is really needed for pure mem operations)
writer.Flush();
// Write the underlying stream of the XmlWriter to file.
fileWriter.Write(memstream.GetBuffer(), 0, (Int32)memstream.Length);
}
}
This will save the formatted xml to disk, with the given text encoding.
Try this:
def date = Date.parse("E MMM dd H:m:s z yyyy", dateStr)
Here are the patterns to format the dates
If trying to build phpredis
on a Linux box you might need to give it time to complete modifying the file permissions, with a sleep
command, before running the file:
chmod a+x /usr/bin/php/scripts/phpize \
&& sleep 1 \
&& /usr/bin/php/scripts/phpize
If you faced this issue with your Flutter project while building in Release mode - that's what helped me:
ios
and build_ios
from your project folder.ios
module by executing flutter create .
from your project folder.open Xcode and:
execute pod install
from your project folder
flutter pub get
from your project foldernow open your Xcode and build or archive it: Product > Build (or Archive)
Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.
For example:
$ echo "asd" | wc -l
Will return 1
and
$ echo -n "asd" | wc -l
Will return 0
So what I often use is grep <anything> -c
$ echo "asd" | grep "^.*$" -c
1
$ echo -n "asd" | grep "^.*$" -c
1
This is closer to reality than what wc -l
will return.
System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
reader.BaseStream.Position = 0;
string requestFromPost = reader.ReadToEnd();
Using java 8 this can be done with
`int[][] destination=Arrays.stream(source)
.map(a -> Arrays.copyOf(a, a.length))
.toArray(int[][]::new);
There are multiple answers based on what you are doing with the string.
1) Using the string as an id (will not be modified). Passing it in by const reference is probably the best idea here: (std::string const&)
2) Modifying the string but not wanting the caller to see that change. Passing it in by value is preferable: (std::string)
3) Modifying the string but wanting the caller to see that change. Passing it in by reference is preferable: (std::string &)
4) Sending the string into the function and the caller of the function will never use the string again. Using move semantics might be an option (std::string &&)
If you'r using LINUX, first let's check apache's user, since in some distros it can be different:
egrep -i '^user|^group' /etc/httpd/conf/httpd.conf
Let's say the result is "http". Do the folowwing, just remember change path_to_folder to folders path:
chown -R http:http path_to_folder
chmod -R g+rw path_to_folder
Try this (subquery):
SELECT * FROM terms WHERE id IN
(SELECT term_id FROM terms_relation WHERE taxonomy = "categ")
Or you can try this (JOIN):
SELECT t.* FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
If you want to receive all fields from two tables:
SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at
FROM terms AS t
INNER JOIN terms_relation AS tr
ON t.id = tr.term_id AND tr.taxonomy = "categ"
Ok, so here was my process:
keytool -list -v -keystore permanent.jks
- got me the alias.
keytool -export -alias alias_name -file certificate_name -keystore permanent.jks
- got me the certificate to import.
Then I could import it with the keytool:
keytool -import -alias alias_name -file certificate_name -keystore keystore location
As @Christian Bongiorno says the alias can't already exist in your keystore.
In this case you use -1.
The best way for me is this:
Dictionary<int, int> copy= new Dictionary<int, int>(yourListOrDictionary);
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
i founded this tool to auto generate wsdl to android code,
http://www.wsdl2code.com/Example.aspx
public void callWebService(){
SampleService srv1 = new SampleService();
Request req = new Request();
req.companyId = "1";
req.userName = "userName";
req.password = "pas";
Response response = srv1.ServiceSample(req);
}
The error indicates that the two tables have the 1 or more column names that have the same column name.
Anyone with the same error who doesn't want to provide a suffix can rename the columns instead. Also make sure the index of both DataFrames match in type and value if you don't want to provide the on='mukey'
setting.
# rename example
df_a = df_a.rename(columns={'a_old': 'a_new', 'a2_old': 'a2_new'})
# set the index
df_a = df_a.set_index(['mukus'])
df_b = df_b.set_index(['mukus'])
df_a.join(df_b)
There's a static method in ToolStripRenderer
class, named CreateDisabledImage
.
Its usage is as simple as:
Bitmap c = new Bitmap("filename");
Image d = ToolStripRenderer.CreateDisabledImage(c);
It uses a little bit different matrix than the one in the accepted answer and additionally multiplies it by a transparency of value 0.7, so the effect is slightly different than just grayscale, but if you want to just get your image grayed, it's the simplest and best solution.
Don't use quotes with <<EOF
:
var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF
Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).
As suggested by this answer:
[link](url){:target="_blank"}
Works for jekyll or more specifically kramdown, which is a superset of markdown, as part of Jekyll's (default) configuration. But not for plain markdown. ^_^
If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.
<div ng-app="">
Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
<select id="transferTo" ng-disabled="checked">
<option>Tech1</option>
<option>Tech2</option>
</select>
</div>
Use System.Random:
Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer
' Create a random number generator
Dim Generator As System.Random = New System.Random()
' Get a random number >= MyMin and <= MyMax
My1stRandomNumber = Generator.Next(MyMin, MyMax + 1) ' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value
' Get another random number (don't create a new generator, use the same one)
My2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)
You don't need the executable for setuptools.
You can download the source code, unpack it, traverse to the downloaded directory and run python setup.py install
in the command prompt
You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.
I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.
So, you may get a chance with:
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)
As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.
SmsListenerClass
public class SmsListener extends BroadcastReceiver {
static final String ACTION =
"android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION)) {
Log.e("RECEIVED", ":-" + "SMS_ARRIVED");
StringBuilder buf = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
SmsMessage message = null;
for (int i = 0; i < messages.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
message = messages[i];
buf.append("Received SMS from ");
buf.append(message.getDisplayOriginatingAddress());
buf.append(" - ");
buf.append(message.getDisplayMessageBody());
}
MainActivity inst = MainActivity.instance();
inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());
}
Log.e("RECEIVED:", ":" + buf.toString());
Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();
}
}
Activity
@Override
public void onStart() {
super.onStart();
inst = this;
}
public static MainActivity instance() {
return inst;
}
public void updateList(final String msg_from, String msg_body) {
tvMessage.setText(msg_from + " :- " + msg_body);
sendSMSMessage(msg_from, msg_body);
}
protected void sendSMSMessage(String phoneNo, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Manifest
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<receiver android:name=".SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Simply create this folder:
C:\Users\xxxxx\android-sdk\tools
and then from Window -> Preferences -> Android
, put this path:
C:\Users\xxxxx\android-sdk
A common error that is the cause of this is when you add
@Model SampleModel
at the top of the page instead of
@model SampleModel
In SQL Server 2016 you can wrap array with [ ] and pass it as JSON see http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/09/08/passing-arrays-to-t-sql-procedures-as-json.aspx
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)
modify list of host names for your system:
C:\Windows\System32\drivers\etc\hosts
Make sure that you have the following entry:
127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem
(you may need to change modify permission to modify this file)
This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.
I know this is an old question, but here is an alternative approach that I have found more useful in some situations. I believe the master.dbo.fn_varbintohexstr function has been available in SQL Server at least since SQL2K. Adding it here just for completeness. Some readers may also find it instructive to look at the source code of this function.
declare @source varbinary(max);
set @source = 0x21232F297A57A5A743894A0E4A801FC3;
select varbin_source = @source
,string_result = master.dbo.fn_varbintohexstr (@source)
If you take a look at the result of valeur <= 0.6
, you can see what’s causing this ambiguity:
>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)
So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?
That’s exactly what numpy.any
and numpy.all
do. The former requires at least one true value, the latter requires that all values are true:
>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False
you can use a formatstring
DateTime time = DateTime.Now;
String format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));
I was stumped by this. Once I got passed the 255 problem... I ended up with a mysterious error code 1. This is the foo to get that resolved:
pssh -x '-tt' -h HOSTFILELIST -P "sudo yum -y install glibc"
-P means write the output out as you go and is optional. But the -x '-tt' trick is what forces a psuedo tty to be allocated.
You can get a clue what the error code 1 means this if you try:
ssh AHOST "sudo yum -y install glibc"
You may see:
[slc@bastion-ci ~]$ ssh MYHOST "sudo yum -y install glibc"
sudo: sorry, you must have a tty to run sudo
[slc@bastion-ci ~]$ echo $?
1
Notice the return code for this is 1, which is what pssh is reporting to you.
I found this -x -tt trick here. Also note that turning on verbose mode (pssh --verbose) for these cases does nothing to help you.
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
Using btoa
with unescape
and encodeURIComponent
didn't work for me. Replacing all the special characters with XML/HTML entities and then converting to the base64 representation was the only way to solve this issue for me. Some code:
base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
}));
You also have to include the FormID in your call to addMessage().
FacesContext.getCurrentInstance().addMessage("myform:newPassword1", new FacesMessage("Error: Your password is NOT strong enough."));
This should do the trick.
Regards.
iOS 4 has ditched the "Rate on Delete" function.
For the time being the only way to rate an application is via iTunes.
Edit: Links can be generated to your applications via iTunes Link Maker. This site has a tutorial.
You maybe want to know what is not CGI, and the answer is a MODULE for your web server (if I suppose you are runnig Apache). AND THAT'S THE BIG DIFERENCE, because CGI needs and external program, thread, whatever to instantiate a PERL, PHP, C app server where when you run as a MODULE that program is the web server (apache) per-se.
Because of all this there is a lot of performance, security, portability issues that come into play. But it's good to know what is not CGI first, to understand what it is.
Installing homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.github.com/gist/323731)"
And then installing postgresql
brew install postgresql
gave me this lovely bit of output:
checking for pg_config... yes
ahhh yeahhhhh
Vanilla JS solution:
var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));
Note that dispatchEvent
doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).
So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for:
typeof document.body.dispatchEvent === 'function'
.
If you know the values are 0 or 1, you could do flipval ^= 1
.
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
Another scenario that you can get the [: too many arguments
or [: a: binary operator expected
errors is if you try to test for all arguments "$@"
if [ -z "$@" ]
then
echo "Argument required."
fi
It works correctly if you call foo.sh
or foo.sh arg1
. But if you pass multiple args like foo.sh arg1 arg2
, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ]
, which is not a valid syntax.
The correct way to check for existence of arguments is [ "$#" -eq 0 ]
. ($#
is the number of arguments).
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);
Why do most answers here assume that all data needs to be deleted, reformatted, and then restart Hadoop? How do we know namenode is not progressing, but taking lots of time. It will do this when there is a large amount of data in HDFS. Check progress in logs before assuming anything is hung or stuck.
$ [kadmin@hadoop-node-0 logs]$ tail hadoop-kadmin-namenode-hadoop-node-0.log
...
016-05-13 18:16:44,405 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 117/141 transactions completed. (83%)
2016-05-13 18:16:56,968 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 121/141 transactions completed. (86%)
2016-05-13 18:17:06,122 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 122/141 transactions completed. (87%)
2016-05-13 18:17:38,321 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 123/141 transactions completed. (87%)
2016-05-13 18:17:56,562 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 124/141 transactions completed. (88%)
2016-05-13 18:17:57,690 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader: replaying edit log: 127/141 transactions completed. (90%)
This was after nearly an hour of waiting on a particular system. It is still progressing each time I look at it. Have patience with Hadoop when bringing up the system and check logs before assuming something is hung or not progressing.
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.
in Laravel 5.4
use this method:
Session::put('variableName', $value);
A simplification to FrinkTheBrave's response:
[System.IO.File]::WriteAllText("c:\temp\myFile.txt", $myContent)
If you have set the default browser in windows then you can do this:
open_google = webbrowser.get('windows-default').open('https://google.com')
// OR
open_google = webbrowser.open('https://google.com')
Another simpler way seems to be:
new = pd.DataFrame([old.A, old.B, old.C]).transpose()
where old.column_name
will give you a series.
Make a list of all the column-series you want to retain and pass it to the DataFrame constructor. We need to do a transpose to adjust the shape.
In [14]:pd.DataFrame([old.A, old.B, old.C]).transpose()
Out[14]:
A B C
0 4 10 100
1 5 20 50
One of the important things to take into account is the "zoom" level of your projection (for Google Maps in particular).
As Google explains it:
At zoom level 1, the map consists of 4 256x256 pixels tiles, resulting in a pixel space from 512x512. At zoom level 19, each x and y pixel on the map can be referenced using a value between 0 and 256 * 2^19
( See https://developers.google.com/maps/documentation/javascript/maptypes?hl=en#MapCoordinates)
To factor in the "zoom" value, I recommend the simple and effective deltaLonPerDeltaX and deltaLatPerDeltaY functions below. While x-pixels and longitudes are strictly proportional, this is not the case for y-pixels and latitudes, for which the formula requires the initial latitude.
// Adapted from : http://blog.cppse.nl/x-y-to-lat-lon-for-google-maps
window.geo = {
glOffset: Math.pow(2,28), //268435456,
glRadius: Math.pow(2,28) / Math.PI,
a: Math.pow(2,28),
b: 85445659.4471,
c: 0.017453292519943,
d: 0.0000006705522537,
e: Math.E, //2.7182818284590452353602875,
p: Math.PI / 180,
lonToX: function(lon) {
return Math.round(this.glOffset + this.glRadius * lon * this.p);
},
XtoLon: function(x) {
return -180 + this.d * x;
},
latToY: function(lat) {
return Math.round(this.glOffset - this.glRadius *
Math.log((1 + Math.sin(lat * this.p)) /
(1 - Math.sin(lat * this.p))) / 2);
},
YtoLat: function(y) {
return Math.asin(Math.pow(this.e,(2*this.a/this.b - 2*y/this.b)) /
(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1) -
1/(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1)
) / this.c;
},
deltaLonPerDeltaX: function(deltaX, zoom) {
// 2^(7+zoom) pixels <---> 180 degrees
return deltaX * 180 / Math.pow(2, 7+zoom);
},
deltaLatPerDeltaY: function(deltaY, zoom, startLat) {
// more complex because of the curvature, we calculte it by difference
var startY = this.latToY(startLat),
endY = startY + deltaY * Math.pow(2, 28-7-zoom),
endLat = this.YtoLat(endY);
return ( endLat - startLat ); // = deltaLat
}
}
Suggest replacing this:
char str[1024];
char tmp = '.';
strcat(str, tmp);
with this:
char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()
strcat(str, tmp); //
Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.
The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.
Here is a good article about fluid vs. flex.
I used a combination of the answers from rohancragg, Mukul Goel, and NullSoulException from above. However I had an additional error:
ORA-01157: cannot identify/lock data file string - see DBWR trace file
To which I found the answer here: http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html
Incase the above post gets deleted I am including the commands here as well.
C:\>sqlplus sys/sys as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Tue Apr 30 19:07:16 2013
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to an idle instance.
SQL> startup
ORACLE instance started.
Total System Global Area 778387456 bytes
Fixed Size 1384856 bytes
Variable Size 520097384 bytes
Database Buffers 251658240 bytes
Redo Buffers 5246976 bytes
Database mounted.
ORA-01157: cannot identify/lock data file 11 – see DBWR trace file
ORA-01110: data file 16: 'E:\oracle\app\nimish.garg\oradata\orcl\test_ts.dbf'
SQL> select NAME from v$datafile where file#=16;
NAME
--------------------------------------------------------------------------------
E:\ORACLE\APP\NIMISH.GARG\ORADATA\ORCL\TEST_TS.DBF
SQL> alter database datafile 16 OFFLINE DROP;
Database altered.
SQL> alter database open;
Database altered.
Thanks everyone you saved my day!
Fissh
Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.
cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));
wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
wp_enqueue_script('custom-js');
$wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );
and in custom.js
alert(wnm_custom.template_url);
A friend function is not a member function, so the problem is that you declare operator<<
as a friend of A
:
friend ostream& operator<<(ostream&, A&);
then try to define it as a member function of the class logic
ostream& logic::operator<<(ostream& os, A& a)
^^^^^^^
Are you confused about whether logic
is a class or a namespace?
The error is because you've tried to define a member operator<<
taking two arguments, which means it takes three arguments including the implicit this
parameter. The operator can only take two arguments, so that when you write a << b
the two arguments are a
and b
.
You want to define ostream& operator<<(ostream&, const A&)
as a non-member function, definitely not as a member of logic
since it has nothing to do with that class!
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a.number;
}
Use the constants defined in the math package:
const (
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory
, you can install the package manually.
You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.
Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.
Hope this helps others.
To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.
class general_function_handler(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, type=None):
return self.__class__(self.func.__get__(obj, type))
def __call__(self, *args, **kwargs):
try:
retval = self.func(*args, **kwargs)
except Exception, e :
logging.warning('Exception in %s' % self.func)
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
logging.exception(message)
sys.exit(1) # exit on all exceptions for now
return retval
This can be called on a class method or a standalone function with the decorator:
@general_function_handler
See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/
A simple solution is the library factoextra
. You can change the clustering method and the method for calculate the best number of groups. For example if you want to know the best number of clusters for a k- means:
library(factoextra)
fviz_nbclust(mtcars, kmeans, method = "wss") +
geom_vline(xintercept = 3, linetype = 2)+
labs(subtitle = "Elbow method")
Finally, we get a graph like:
You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
The above assumes that you have a folder called CSS
in the root of your website like this:
http://www.website.com/CSS/Style.css
git fsck --unreachable | grep commit
should show the sha1, although the list it returns might be quite large. git show <sha1>
will show if it is the commit you want.
git cherry-pick -m 1 <sha1>
will merge the commit onto the current branch.
Update with Java 9+ with takeWhile
:
MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
// doing something.
if (...) { // want to break;
ongoing.setFalse();
}
});
I am using intellij CE to create the WAR, and deploying the war externally using tomcat deployment manager. This works for testing the application however I still couldnt find the way to debug it.
I was able to trigger an SDK download like this:
I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.
I solved it by using os.walk()
, recursively calling my function and using shutil.move()
on files which I wanted to overwrite and folders which did not exist.
It works like shutil.move()
, but with the benefit that existing files are only overwritten, but not deleted.
import os
import shutil
def moverecursively(source_folder, destination_folder):
basename = os.path.basename(source_folder)
dest_dir = os.path.join(destination_folder, basename)
if not os.path.exists(dest_dir):
shutil.move(source_folder, destination_folder)
else:
dst_path = os.path.join(destination_folder, basename)
for root, dirs, files in os.walk(source_folder):
for item in files:
src_path = os.path.join(root, item)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.move(src_path, dst_path)
for item in dirs:
src_path = os.path.join(root, item)
moverecursively(src_path, dst_path)
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;
public void clickOnSubmitButton() {
submitButton.click();
}
I came to the same problem and tried all methods on internet, and finally worked it out by accident. May you could try this(see in the picture)
Before sometime I also had the same problem. I have tried replacing the .dll
file but no result. After some debugging I found the solution.
I had this in my php.ini
file:
extension_dir = "ext"
And I'm getting mbstring extension missing
error. So I tried putting the full path for the extension directory and it works for me. like:
extension_dir = "C:\php\ext"
Hope this will help.
Cheers,
Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:
$("*[attr-name]")
Hope that helps somebody who happens to land on this page looking for the same thing that I was :).
Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):
$("[attr-name]")
git branch -a
- All branches.
git branch -r
- Remote branches only.
git branch -l
or git branch
- Local branches only.
ResourceManager
shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:
Assuming a project namespace: UberSoft.WidgetPro
And your resx contains:
You can just use:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
If you have some given list, and want to iterate over its items and indices, you can use enumerate()
:
for index, item in enumerate(my_list):
print index, item
If you only need the indices, you can use range()
:
for i in range(len(my_list)):
print i
Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.
EXEC sp_addrolemember 'db_ddladmin', 'username_here';
did the trick
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
Did you dispatch the event correctly?
function simulateKeyEvent(character) {
var evt = document.createEvent("KeyboardEvent");
(evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
0, 0, 0, 0,
0, character.charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
If you use jQuery, you could do:
function simulateKeyPress(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}
I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:
background: no-repeat center center fixed\0/; /* IE8 HACK */
This has solved the frozen links problem for me.
There is a known bug with specifying default command timeout within the EF connection string.
http://bugs.mysql.com/bug.php?id=56806
Remove the value from the connection string and set it on the data context object itself. This will work if you remove the conflicting value from the connection string.
this.context.Database.SetCommandTimeout(180);
this.context.Database.CommandTimeout = 180;
((IObjectContextAdapter)this.context).ObjectContext.CommandTimeout = 180;
this.context.CommandTimeout = 180;
Use numpy.full
. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.
import cv2
import numpy as np
gray_img = np.full((100, 100, 3), 127, np.uint8)
blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)
full_layer = np.full((100, 100), 255, np.uint8)
# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer
cv2.imshow('2x2_grid', np.vstack([
np.hstack([gray_img, blue_img]),
np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')
Well, file_exists
does not say if a file exists, it says if a path exists. ???????
So, to check if it is a file then you should use is_file
together with file_exists
to know if there is really a file behind the path, otherwise file_exists
will return true
for any existing path.
Here is the function i use :
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
The default behavior of google drive is to scan files for viruses if the file is to big it will prompte the user and notifies him that the file could not be scanned.
At the moment the only workaround I found is to share the file with the web and create a web resource.
Quote from the google drive help page:
With Drive, you can make web resources — like HTML, CSS, and Javascript files — viewable as a website.
To host a webpage with Drive:
- Open Drive at drive.google.com and select a file.
- Click the Share button at the top of the page.
- Click Advanced in the bottom right corner of the sharing box.
- Click Change....
- Choose On - Public on the web and click Save.
- Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
- Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
Anyone can now view your webpage.
Found here: https://support.google.com/drive/answer/2881970?hl=en
So for example when you share a file on google drive publicly the sharelink looks like this:
https://drive.google.com/file/d/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U/view?usp=sharing
Then you copy the file id and create a googledrive.com linke that look like this:
https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U
There is no direct option available. You cant't do db.collection("CollectionName").count()
.
Below are the two ways by which you can find the count of number of documents within a collection.
db.collection("CollectionName").get().subscribe(doc=>{
console.log(doc.size)
})
By using above code your document reads will be equal to the size of documents within a collection and that is the reason why one must avoid using above solution.
db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
console.log(doc.count)
})
Above we created a document with name counts to store all the count information.You can update the count document in the following way:-
w.r.t price (Document Read = 1) and fast data retrieval the above solution is good.
I found this question when searching for You are in 'detached HEAD' state.
After analyzing what I had done to get here, as compared with what I had done in the past, I discovered that I had made a mistake.
My normal flow is:
git checkout master
git fetch
git checkout my-cool-branch
git pull
This time I did:
git checkout master
git fetch
git checkout origin/my-cool-branch
# You are in 'detached HEAD' state.
The problem is that I accidentally did:
git checkout origin/my-cool-branch
Rather than:
git checkout my-cool-branch
The fix (in my situation) was simply to run the above command and then continue the flow:
git checkout my-cool-branch
git pull
I resolved this by making sure my project shared the same .Net Framework version as the projects/libraries it depended on.
It turned out the libraries (projects within the solution) used .Net 4.6.1 and my project was using 4.5.2
I had the same issue, I solved this with the following steps:
Install the MySql (DMG) from this link
If the mysql package comes with the file name "mysql-5.7.13...." and "MySql.prefPane" then your life is really easy. Just click on "mysql-5.7.13...." and follow the instructions.
After the installation is done, click on "MySql.prefPane" and checkout "Only for this user" in the popup. We use "MySql.prefPane" to start the mysql server as this is really imp because without this you will end up having errors.
Click on Start MySql Server in the next dialog box.
OR
If you don't see "MySql.prefPane" in the package then follow these steps:
Click on package "mysql-5.7.13...." and this will show you one password as soon as installation is done. That password is use to start the connection. You can change it. I will let you know in a while.
After installation save the password (this is really important - you'll need it later), open terminal.
$ cd /usr/local/mysql/bin/
$ ./mysql -u root -h localhost -p
And then type the password from above. This should start mysql>
To change the password:
$ cd /usr/local/mysql/bin/
$ ./mysqladmin -u root -p password 'new_password'
Enter Password: <type new password here>
$ ./mysql -u root -h localhost -p
... and log in with the new password.
After this you can go to MySql workbench and test connection
. It should connect.
I encountered the same problem and finally found out that the <tx:annotaion-driven />
was not defined within the [dispatcher]-servlet.xml
where component-scan element enabled @service
annotated class.
Simply put <tx:annotaion-driven />
with component-scan element together, the problem disappeared.
I believe the best way to do this is to use the LocalTimezone
class defined in the datetime.tzinfo
documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):
Assuming Local
is an instance of LocalTimezone
t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)
then str(local_t)
gives:
'2009-07-11 04:44:59.193982+10:00'
which is what you want.
(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)
I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.
Google Closure Compiler generally achieves smaller files than YUI Compressor, particularly if you use the advanced mode, which looks worryingly meddlesome to me but has worked well on the one project I've used it on:
Several big projects use UglifyJS, and I've been very impressed with it since switching.
.then() is chainable and will wait for previous .then() to resolve.
.success() and .error() can be chained, but they will all fire at once (so not much point to that)
.success() and .error() are just nice for simple calls (easy makers):
$http.post('/getUser').success(function(user){
...
})
so you don't have to type this:
$http.post('getUser').then(function(response){
var user = response.data;
})
But generally i handler all errors with .catch():
$http.get(...)
.then(function(response){
// successHandler
// do some stuff
return $http.get('/somethingelse') // get more data
})
.then(anotherSuccessHandler)
.catch(errorHandler)
If you need to support <= IE8 then write your .catch() and .finally() like this (reserved methods in IE):
.then(successHandler)
['catch'](errorHandler)
Working Examples:
Here's something I wrote in more codey format to refresh my memory on how it all plays out with handling errors etc:
You need to do a few things:
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLE_NAME'
AND COLUMN_NAME = N'LOWER_LIMIT')
BEGIN
DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
FROM sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
IF @@ROWCOUNT = 0
BEGIN
PRINT 'DELETED Constraint on column LOWER_LIMIT'
BREAK
END
EXEC (@sql)
END;
ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
PRINT 'DELETED column LOWER_LIMIT'
END
ELSE
PRINT 'Column LOWER_LIMIT does not exist'
GO
Escape it: someString.replace(/\//g, "-");
Just for reference if anyone is still struggling with mongorestore.
You have to run monogorestore in terminal/command prompt and not in mongo console.
$ mongorestore -d db_name /path_to_mongo_dump/
for more details you can visit official documentations
https://docs.mongodb.com/manual/reference/program/mongorestore/
This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
If you'r using python 3.0+ then configure your project as below
Setting
STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
Main Urls
from django.conf import settings
from django.conf.urls.static import static
urlspatterns=[
........
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I had the same problem. The "osql -L" command displayed only a list of servers but without instance names (only the instance of my local SQL Sever was displayed). With Wireshark, sqlbrowser.exe (which can by found in the shared folder of your SQL installation) I found a solution for my problem.
The local instance is resolved by registry entry. The remote instances are resolved by UDP broadcast (port 1434) and SMB. Use "sqlbrowser.exe -c" to list the requests.
My configuration uses 1 physical and 3 virtual network adapters. If I used the "osql -L" command the sqlbrowser displayed a request from one of the virtual adaptors (which is in another network segment), instead of the physical one. osql selects the adpater by its metric. You can see the metric with command "route print". For my configuration the routing table showed a lower metric for teh virtual adapter then for the physical. So I changed the interface metric in the network properties by deselecting automatic metric in the advanced network settings. osql now uses the physical adapter.
There is something wrong in your setDelimiter()
function. You don't want to double quote the delimiters, do you?
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\\" + c[0] + "\\" + c[1];
System.out.println("Delimiter string is: " + this.delimiter);
}
However, as other users have said, it's better to use the Pattern.quote() method to escape your delimiter if your requirements permit.
You could speed up the initialization and simplify the code by using the the Parallel class (.NET 4 and newer):
public static void PopulateByteArray(byte[] byteArray, byte value)
{
Parallel.For(0, byteArray.Length, i => byteArray[i] = value);
}
Of course you can create the array at the same time:
public static byte[] CreateSpecialByteArray(int length, byte value)
{
var byteArray = new byte[length];
Parallel.For(0, length, i => byteArray[i] = value);
return byteArray;
}
Try This one. It will generate id according to your wish.
function id()
{
// add limit
$id_length = 20;
// add any character / digit
$alfa = "abcdefghijklmnopqrstuvwxyz1234567890";
$token = "";
for($i = 1; $i < $id_length; $i ++) {
// generate randomly within given character/digits
@$token .= $alfa[rand(1, strlen($alfa))];
}
return $token;
}
I have tried so many solutions from this post and ended up with the below solution. This is full proof solution unless you need to drop shadow on a clear color view.
- (void)addShadowWithRadius:(CGFloat)shadowRadius withOpacity:(CGFloat)shadowOpacity withOffset:(CGSize)shadowOffset withColor:(UIColor *)shadowColor withCornerradius:(CGFloat)cornerRadius
{
UIView *viewShadow = [[UIView alloc]initWithFrame:self.frame];
viewShadow.backgroundColor = [UIColor whiteColor];
viewShadow.layer.shadowColor = shadowColor.CGColor;
viewShadow.layer.shadowOffset = shadowOffset;
viewShadow.layer.shadowRadius = shadowRadius;
viewShadow.layer.shadowOpacity = shadowOpacity;
viewShadow.layer.cornerRadius = cornerRadius;
viewShadow.layer.masksToBounds = NO;
[self.superview insertSubview:viewShadow belowSubview:self];
[viewShadow setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:viewShadow attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:viewShadow attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:viewShadow attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:viewShadow attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[self.superview addConstraint:[NSLayoutConstraint constraintWithItem:viewShadow attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:viewShadow attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
[self layoutIfNeeded];
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = YES;
}
It simple with apply function in R
f <- apply(f,2,toupper)
No need to check if the column is character or any other type.
Using .innerText
should work.
document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt");
for(String str: arr) {
writer.write(str + System.lineSeparator());
}
writer.close();
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
I discovered SqlBulkCopy is an easy way to do this, and does not require a stored procedure to be written in SQL Server.
Here is an example of how I implemented it:
// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.
using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
// my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
foreach (DataColumn col in table.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = destinationTableName;
bulkCopy.WriteToServer(table);
}
If I can offer another solution that has the added benefit of type checking, warnings if you are missing an enum value in your conversion, readability, and brevity.
For your given example: typedef enum { value1, value2, value3 } myValue;
you can do this:
NSString *NSStringFromMyValue(myValue type) {
const char* c_str = 0;
#define PROCESS_VAL(p) case(p): c_str = #p; break;
switch(type) {
PROCESS_VAL(value1);
PROCESS_VAL(value2);
PROCESS_VAL(value3);
}
#undef PROCESS_VAL
return [NSString stringWithCString:c_str encoding:NSASCIIStringEncoding];
}
As a side note. It is a better approach to declare your enums as so:
typedef NS_ENUM(NSInteger, MyValue) {
Value1 = 0,
Value2,
Value3
}
With this you get type-safety (NSInteger
in this case), you set the expected enum offset (= 0
).
It uses indentation
def func():
funcbody
if cond:
ifbody
outofif
outof_func
Go to node_modules/@vue/cli-service/lib/options.js
At the bottom inside the "devServer" unblock the codes
Now give your desired port number in the "port" :)
devServer: {
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 3000, // default port 8080
https: false,
hotOnly: false,
proxy: null, // string | Object
before: app => {}
}
ES6 way:
I use destructuring assignment for array to get first
and remaining rest
elements and then I'll take last five of the rest
with slice method:
const cutOffFirstAndLastFive = (array) => {_x000D_
const [first, ...rest] = array;_x000D_
return rest.slice(-5);_x000D_
}_x000D_
_x000D_
cutOffFirstAndLastFive([1, 55, 77, 88]);_x000D_
_x000D_
console.log(_x000D_
'Tests:',_x000D_
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),_x000D_
JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),_x000D_
JSON.stringify(cutOffFirstAndLastFive([1]))_x000D_
);
_x000D_
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String
private String capitalize(String txt){
List<String> finalTxt=new ArrayList<>();
if(txt.contains("_")){
txt=txt.replace("_"," ");
}
if(txt.contains(" ") && txt.length()>1){
String[] tSS=txt.split(" ");
for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }
}
if(finalTxt.size()>0){
txt="";
for(String s:finalTxt){ txt+=s+" "; }
}
if(txt.endsWith(" ") && txt.length()>1){
txt=txt.substring(0, (txt.length()-1));
return txt;
}
txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
return txt;
}
If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.
This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.
There is a very nice workaround using Range.createContextualFragment
.
/**
* Like React's dangerouslySetInnerHTML, but also with JS evaluation.
* Usage:
* <div ref={setDangerousHtml.bind(null, html)}/>
*/
function setDangerousHtml(html, el) {
if(el === null) return;
const range = document.createRange();
range.selectNodeContents(el);
range.deleteContents();
el.appendChild(range.createContextualFragment(html));
}
This works for arbitrary HTML and also retains context information such as document.currentScript
.
It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga
faulthandler.enable()
// bad code goes here
or
$ python3 -q -X faulthandler
>>> /// bad cod goes here
I have also faced this problem.Double check the result in the error window.
In my case, a tailing \
was crashing xcopy (as I was using $(TargetDir)
). In my case $(SolutionDir)..\bin
. If you're using any other output, this needs to be adjusted.
Also note that start xcopy
does not fix it, if the error is gone after compiling. It might have just been suppressed by the command line and no file has actually been copied!
You can btw manually execute your xcopy commands in a command shell. You will get more details when executing them there, pointing you in the right direction.
Based on @dave1010 answer but with updated https
links.
Numbered marker:
https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000
Text marker:
https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker
Swift 5 and above:
let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")
defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")
defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")
let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")
let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()
let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")
let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()
:)
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
What worked for me was
git reset HEAD app/views/data/landingpage.js.erb
git restore app/views/data/landingpage.js.erb
where the file I wanted to restore was app/views/data/landingpage.js.erb
The file needs be writable by the camera, as Praveen pointed out.
In my usage I wanted to store the file in internal storage. I did this with:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()!=null)){
try{
cacheFile = createTempFile("img",".jpg",getCacheDir());
cacheFile.setWritavle(true,false);
}catch(IOException e){}
if(cacheFile != null){
i.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(cacheFile));
startActivityForResult(i,REQUEST_IMAGE_CAPTURE);
}
}
Here cacheFile
is a global file used to refer to the file which is written.
Then in the result method the returned intent is null.
Then the method for processing the intent looks like:
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode != RESULT_OK){
return;
}
if(requestCode == REQUEST_IMAGE_CAPTURE){
try{
File output = getImageFile();
if(output != null && cacheFile != null){
copyFile(cacheFile,output);
//Process image file stored at output
cacheFile.delete();
cacheFile=null;
}
}catch(IOException e){}
}
}
Here getImageFile()
is a utility method to name and create the file in which the image should be stored, and copyFile()
is a method to copy a file.
rcedit is relative new and works well from the command line: https://github.com/atom/rcedit
$ rcedit "path-to-exe-or-dll" --set-version-string "Comments" "This is an exe"
$ rcedit "path-to-exe-or-dll" --set-file-version "10.7"
$ rcedit "path-to-exe-or-dll" --set-product-version "10.7"
There's also an NPM module which wraps it from JavaScript and a Grunt task in case you're using Grunt.
pthread_self()
function will give the thread id of current thread.
pthread_t pthread_self(void);
The pthread_self()
function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np()
to return an integral identifier for the thread.
NOTE:
pthread_id_np_t tid;
tid = pthread_getthreadid_np();
is significantly faster than these calls, but provides the same behavior.
pthread_id_np_t tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
Here is updated version from Darrelk answer. It is implemented using C# extension methods. It does not allocate memory (new Random()) every time this method is called.
public static class RandomExtensionMethods
{
public static double NextDoubleRange(this System.Random random, double minNumber, double maxNumber)
{
return random.NextDouble() * (maxNumber - minNumber) + minNumber;
}
}
Usage (make sure to import the namespace that contain the RandomExtensionMethods class):
var random = new System.Random();
double rx = random.NextDoubleRange(0.0, 1.0);
double ry = random.NextDoubleRange(0.0f, 1.0f);
double vx = random.NextDoubleRange(-0.005f, 0.005f);
double vy = random.NextDoubleRange(-0.005f, 0.005f);
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
<div runat="server">
is mapped to a HtmlGenericControl
.
Try using BtnventCss.Attributes.Add("class", "hom_but_a");
public class SystemDateTest {
String stringDate;
public static void main(String[] args) {
SystemDateTest systemDateTest = new SystemDateTest();
// format date into String
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
System.out.println(systemDateTest.getStringDate());
}
public Date getDate() {
return new Date();
}
public String getStringDate() {
return stringDate;
}
public void setStringDate(String stringDate) {
this.stringDate = stringDate;
}
}
If you have source as a string like "abcd"
and want to produce a list like this:
{ "a.a" },
{ "b.b" },
{ "c.c" },
{ "d.d" }
then call:
List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList();
After ten years, you can read this training explanation on the official documentation.
Ok, adding to the answers stated you might be also looking for
IEnumerable<string> m_oEnum = Enumerable.Empty<string>();
or
IEnumerable<string> m_oEnum = new string[]{};
jQuery uses a .call(...)
method to assign the current node to this
inside the function you pass as the parameter.
EDIT:
Don't be afraid to look inside jQuery's code when you have a doubt, it's all in clear and well documented Javascript.
ie: the answer to this question is around line 574,
callback.call( object[ name ], name, object[ name ] ) === false
You have to wrap your Javascript-Code with $(document).ready(function(){});
Look this JSfiddle.
JS Code:
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
For python version 2.x you can simply use
pip install pillow
But for python version 3.X you need to specify
(sudo) pip3 install pillow
when you enter pip in bash hit tab and you will see what options you have
Just wrote a script to do this without too much typing while maintaining portability as setting ~
to be %userprofile%
needs a manual setup on each Windows PC while cloning and setting the directory as part of the PATH
is mechanical.
if you want secure encryption:
for python 2, you should use keyczar http://www.keyczar.org/
for python 3, until keyczar is available, i have written simple-crypt http://pypi.python.org/pypi/simple-crypt
both these will use key strengthening which makes them more secure than most other answers here. and since they're so easy to use you might want to use them even when security is not critical...
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
Full thanks must go to Felix Kling for his excellent answer which I have gratefully used in my code. I offer a small enhancement of a boolean return value to report success or failure:
function recurse_copy($src, $dst) {
$dir = opendir($src);
$result = ($dir === false ? false : true);
if ($result !== false) {
$result = @mkdir($dst);
if ($result === true) {
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' ) && $result) {
if ( is_dir($src . '/' . $file) ) {
$result = recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
$result = copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
}
return $result;
}
Here are different options for this:
First: without jQuery:
var lis = document.querySelectorAll('ul > li');
var contents = [].map.call(lis, function (li) {
return li.innerHTML;
}).reverse().forEach(function (content, i) {
lis[i].innerHTML = content;
});
... and with jQuery:
You can use this:
$($("ul > li").get().reverse()).each(function (i) {
$(this).text( 'Item ' + (++i));
});
Demo here
Another way, using also jQuery with reverse is:
$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
$(this).text( 'Item ' + (++i));
});
This demo here.
One more alternative is to use the length
(count of elements matching that selector) and go down from there using the index
of each iteration. Then you can use this:
var $li = $("ul > li");
$li.each(function (i) {
$(this).text( 'Item ' + ($li.length - i));
});
This demo here
One more, kind of related to the one above:
var $li = $("ul > li");
$li.text(function (i) {
return 'Item ' + ($li.length - i);
});
Demo here
maybe you should try installing VC++ runtime as explained here.
There's a fairly good chance you're missing the correct VC++ runtime for the version of PHP you're running.
If you're running PHP 5.5.x you need to ensure the VC++11 runtime is installed:
http://www.microsoft.com/en-us/download/details.aspx?id=30679
Make sure you download and install the x86 version (vcredist_x86.exe), PHP on Windows isn't 64 bit yet.
If you're running PHP 5.4.x then you need to install the VC++9 runtime:
http://www.microsoft.com/en-us/download/details.aspx?id=5582
Another option based on this answer: https://stackoverflow.com/a/29269316/451710
This allows you to execute multiple commands (e.g cd
) in the same process.
import subprocess
commands = '''
pwd
cd some-directory
pwd
cd another-directory
pwd
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
print(out.decode('utf-8'))
Have a look at http://bootboxjs.com/
Very easy to use:
bootbox.confirm("Are you sure?", function(result) {
Example.show("Confirm result: "+result);
});
Yes, if your Column annotation has the runtime retention
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
....
}
you can do something like this
for (Field f: MyClass.class.getFields()) {
Column column = f.getAnnotation(Column.class);
if (column != null)
System.out.println(column.columnName());
}
UPDATE : To get private fields use
Myclass.class.getDeclaredFields()
Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.
Vanilla JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden
) and enumerated attributes (contenteditable=""
).
There are 2 possibilities.
You really don't have Label
property.
You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance
If your property is not public, you will need to use BindingFlags.NonPublic
or some other combination of flags which fits your use case. Read the referenced API docs to find the details.
EDIT:
ooops, just noticed you call GetProperty
on typeof(MyClass)
. typeof(MyClass)
is Type
which for sure has no Label
property.
Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.
The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...
I think the best equivalent to PHP's var_dump($foo, $bar)
is combine print
with vars
:
print vars(foo),vars(bar)
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabricated. I've used software that generates its license file based on your network adapter MAC address, so it's considered a fairly reliable way to distinguish between computers.
For a field separator of any number 2
through 5
or letter a
or #
or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:
awk -F'[2-5a# ]{2,6}' ...
I am sure variations of this exist using ( ) and parameters
$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change LIMIT 1 to LIMIT any number you want
This will show you the last INSERTED row first.
static class Constants
{
public const int MIN_LENGTH = 5;
public const int MIN_WIDTH = 5;
public const int MIN_HEIGHT = 6;
}
// elsewhere
public CBox()
{
length = Constants.MIN_LENGTH;
width = Constants.MIN_WIDTH;
height = Constants.MIN_HEIGHT;
}
There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.
Crude, maybe, but it definitely should work.
This message from git
means that you have made three commits in your local repo, and have not published them to the master
repository. The command to run for that is git push {local branch name} {remote branch name}
.
The command git pull
(and git pull --rebase
) are for the other situation when there are commit on the remote repo that you don't have in your local repo. The --rebase
option means that git
will move your local commit aside, synchronise with the remote repo, and then try to apply your three commit from the new state. It may fail if there is conflict, but then you'll be prompted to resolve them. You can also abort the rebase
if you don't know how to resolve the conflicts by using git rebase --abort
and you'll get back to the state before running git pull --rebase
.
Try float
property. Here's an example: http://jsfiddle.net/mLmHR/
You can also invoke cmake itself to do this in a cross-platform way:
cmake -E env EnvironmentVariableName="Hello World" cmake ..
env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
Run command in a modified environment.
Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make
, one CMakeLists.txt
was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).
So I transfer those user defined environment variables in my projects into a CMake cached variable:
cmake_minimum_required(VERSION 2.6)
project(PrintEnv NONE)
if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")
set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")
endif()
message("EnvironmentVariableName = ${EnvironmentVariableName}")
Reference
For loop is not officially supported yet by SQL server. Already there is answer on achieving FOR Loop's different ways. I am detailing answer on ways to achieve different types of loops in SQL server.
DECLARE @cnt INT = 0;
WHILE @cnt < 10
BEGIN
PRINT 'Inside FOR LOOP';
SET @cnt = @cnt + 1;
END;
PRINT 'Done FOR LOOP';
If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.
DECLARE @X INT=1;
WAY: --> Here the DO statement
PRINT @X;
SET @X += 1;
IF @X<=10 GOTO WAY;
DECLARE @X INT = 1;
WAY: -- Here the REPEAT statement
PRINT @X;
SET @X += 1;
IFNOT(@X > 10) GOTO WAY;
Just use the Cells function and loop thru columns. Cells(Row,Column)
when you create a job in nohup it will tell you the process ID !
nohup sh test.sh &
the output will show you the process ID like
25013
you can kill it then :
kill 25013
Escaping characters is different for tags and attributes.
For tags:
< <
> > (only for compatibility, read below)
& &
For attributes:
" "
' '
From Character Data and Markup:
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.
To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " ' ", and the double-quote character (") as " " ".
The ps
solution was nearly what I needed and with some bash thrown in does exactly what the original question asked for: to see per-core usage of specific processes
This shows per-core usage of multi-threaded processes too.
Use like: cpustat `pgrep processname` `pgrep otherprocessname` ...
#!/bin/bash
pids=()
while [ $# != 0 ]; do
pids=("${pids[@]}" "$1")
shift
done
if [ -z "${pids[0]}" ]; then
echo "Usage: $0 <pid1> [pid2] ..."
exit 1
fi
for pid in "${pids[@]}"; do
if [ ! -e /proc/$pid ]; then
echo "Error: pid $pid doesn't exist"
exit 1
fi
done
while [ true ]; do
echo -e "\033[H\033[J"
for pid in "${pids[@]}"; do
ps -p $pid -L -o pid,tid,psr,pcpu,comm=
done
sleep 1
done
Note: These stats are based on process lifetime, not the last X seconds, so you'll need to restart your process to reset the counter.
If you are using Bootstrap 4:
<ol class="font-weight-bold">
<li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
<li><span class="font-weight-light">Curabitur aliquet quam id dui posuere blandit.</span></li>
</ol>
You can drop index duplicates with 'drop_duplicates':
df.loc[df.index.drop_duplicates(keep='first')]
xsv is more than a viewer. I recommend it for most CSV task on the command line, especially when dealing with large datasets.
I suggest it would probably be a good idea to describe "having a prototype assignment in a constructor" as a Javascript anti-pattern. Think about it. It is way too risky.
What you're actually doing there on creation of the second object (i.e. b) is redefining that prototype function for all objects that use that prototype. This will effectively reset the value for object a in your example. It will work if you want a shared variable and if you happen to create all of the object instances up front, but it feels way too risky.
I found a bug in some Javascript I was working on recently that was due to this exact anti-pattern. It was trying to set a drag and drop handler on the particular object being created but was instead doing it for all instances. Not good.
Doug Crockford's solution is the best.
The easiest way to animate Visibility
changes is use Transition API
which available in support (androidx) package. Just call TransitionManager.beginDelayedTransition
method then change visibility of the view. There are several default transitions like Fade
, Slide
.
import androidx.transition.TransitionManager;
import androidx.transition.Transition;
import androidx.transition.Fade;
private void toggle() {
Transition transition = new Fade();
transition.setDuration(600);
transition.addTarget(R.id.image);
TransitionManager.beginDelayedTransition(parent, transition);
image.setVisibility(show ? View.VISIBLE : View.GONE);
}
Where parent
is parent ViewGroup
of animated view. Result:
Here is result with Slide
transition:
import androidx.transition.Slide;
Transition transition = new Slide(Gravity.BOTTOM);
It is easy to write custom transition if you need something different. Here is example with CircularRevealTransition
which I wrote in another answer. It shows and hide view with CircularReveal animation.
Transition transition = new CircularRevealTransition();
android:animateLayoutChanges="true"
option does same thing, it just uses AutoTransition as transition.
Swift 5: The Codable protocol can be used instead of NSKeyedArchiever.
struct User: Codable {
let id: String
let mail: String
let fullName: String
}
The Pref struct is custom wrapper around the UserDefaults standard object.
struct Pref {
static let keyUser = "Pref.User"
static var user: User? {
get {
if let data = UserDefaults.standard.object(forKey: keyUser) as? Data {
do {
return try JSONDecoder().decode(User.self, from: data)
} catch {
print("Error while decoding user data")
}
}
return nil
}
set {
if let newValue = newValue {
do {
let data = try JSONEncoder().encode(newValue)
UserDefaults.standard.set(data, forKey: keyUser)
} catch {
print("Error while encoding user data")
}
} else {
UserDefaults.standard.removeObject(forKey: keyUser)
}
}
}
}
So you can use it this way:
Pref.user?.name = "John"
if let user = Pref.user {...
We must to stopPropagation()
In order to avoid Clicks triggers event too many times.
$(this).find('#cameraImageView').on('click', function(evt) {
evt.stopPropagation();
console.log("Camera click event.");
});
It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. This method does not accept any arguments.
We can use event.isPropagationStopped()
to determine if this method was ever called (on that event object).
This method works for custom events triggered with trigger(), as well.Note that this will not prevent other handlers on the same element from running.
I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.
http://www.tohtml.com/ created syntax highlighted HTML code for lots of languages. It might be what you're looking for.
For completeness, here's how to do it with std::regex
.
#include <regex>
#include <string>
int main()
{
const std::string s = "example string";
const std::string r = std::regex_replace(s, std::regex("x"), "y");
}