Copy the mail as a document link (right click on the mail and you should get this option) and paste it in the new mail. This worked for me
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your [email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Try using download manager, which can help you download everything you want and save you time.
Check those to options:
Option 1 ->
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Option 2 ->
if(mWebview.getUrl().contains(".mp3") {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.Item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
' Delete the attachment.
objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
mongorestore
is the tool to use to import bson files that were dumped by mongodump
.
From the docs:
mongorestore takes the output from mongodump and restores it.
Example:
# On the server run dump, it will create 2 files per collection
# in ./dump directory:
# ./dump/my-collection.bson
# ./dump/my-collection.metadata.json
mongodump -h 127.0.0.1 -d my-db -c my-collection
# Locally, copy this structure and run restore.
# All collections from ./dump directory are picked up.
scp user@server:~/dump/**/* ./
mongorestore -h 127.0.0.1 -d my-db
Try make 2> file
. Compiler warnings come out on the standard error stream, not the standard output stream. If my suggestion doesn't work, check your shell manual for how to divert standard error.
Try this:
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your asking")) {
confirm_value.value = "Yes";
document.forms[0].appendChild(confirm_value);
}
else {
confirm_value.value = "No";
document.forms[0].appendChild(confirm_value);
}
}
In Button call function:
<asp:Button ID="btnReprocessar" runat="server" Text="Reprocessar" Height="20px" OnClick="btnReprocessar_Click" OnClientClick="Confirm()"/>
In class .cs call method:
protected void btnReprocessar_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
}
}
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
PS: For the record, it was actually the original question. It was already edited :)
In my case, one of the event handler task was pointing to old connection which was deleted, deleting the unused event handler task fixed the problem. I end up opening the package in XML format to understand that the problem is with event handler task!
Yes, the 3rd template parameter on map
specifies the comparator, which is a binary predicate. Example:
struct ByLength : public std::binary_function<string, string, bool>
{
bool operator()(const string& lhs, const string& rhs) const
{
return lhs.length() < rhs.length();
}
};
int main()
{
typedef map<string, string, ByLength> lenmap;
lenmap mymap;
mymap["one"] = "one";
mymap["a"] = "a";
mymap["fewbahr"] = "foobar";
for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
cout << it->first << "\n";
}
What onetrickpony
posted is okay, but if you want to have a more general solution, you can just use the code below.
Instead of selecting just the id
of the anchor, you can make it bit more standard-like and just selecting the attribute name
of the <a>
-Tag. This will save you from writing an extra id
tag. Just add the smoothscroll class to the navbar element.
What changed
1) $('#nav ul li a[href^="#"]')
to $('#nav.smoothscroll ul li a[href^="#"]')
2) $(this.hash)
to $('a[name="' + this.hash.replace('#', '') + '"]')
Final Code
/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
The way that setuptools
does it, it uses the pkg_resources.parse_version
function. It should be PEP440 compliant.
Example:
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""Example comparing two PEP440 formatted versions
"""
import pkg_resources
VERSION_A = pkg_resources.parse_version("1.0.1-beta.1")
VERSION_B = pkg_resources.parse_version("v2.67-rc")
VERSION_C = pkg_resources.parse_version("2.67rc")
VERSION_D = pkg_resources.parse_version("2.67rc1")
VERSION_E = pkg_resources.parse_version("1.0.0")
print(VERSION_A)
print(VERSION_B)
print(VERSION_C)
print(VERSION_D)
print(VERSION_A==VERSION_B) #FALSE
print(VERSION_B==VERSION_C) #TRUE
print(VERSION_C==VERSION_D) #FALSE
print(VERSION_A==VERSION_E) #FALSE
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.TrimSpace(" \t\n Hello, Gophers \n\t\r\n"))
}
Output: Hello, Gophers
And simply follow this link - https://golang.org/pkg/strings/#TrimSpace
Use (LocalDB)\MSSQLLocalDB as the server name
Another alternative:
Use the code from the unicodecsv package ...
https://pypi.python.org/pypi/unicodecsv/
>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True
This module is API compatible with the STDLIB csv module.
audio { display:none;}
_x000D_
<audio autoplay="true" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
_x000D_
In my case, I needed to get the total rows from a ResultSet and also access the ResultSet values ??if the total rows did not reach the limit of an XLS file.
For that, I had to make two adjustments to my code:
1) Change in object construction PreparedStatement
A default ResultSet object has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable. The following code fragment illustrates how to make a result set that is scrollable and insensitive to updates by others.
PreparedStatement ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
2) Get total rows. The following code fragment illustrates how:
ResultSet rs = ps.executeQuery();
rs.last();
int totalRowsResult = rs.getRow();
PS: If the number of records of the query result is too large, you may run out of memory on the Java server by getting an exception: java.lang.OutOfMemoryError: Java heap space. This exception will occur when executing the rs.last () method
3) Access again the ResultSet and you don't get the message: exhaused result set. So, vou need reset the result set to the top, using rs.first() or rs.absolute(1). The following code fragment illustrates how:
rs.first();
System.out.println(rs.getString(1));
If you are in Mac OS, you need to open the /usr/local/etc/rabbitmq/rabbitmq-env.conf
and
set NODE_IP_ADDRESS=
, it used to be 127.0.0.1. Then add another user as the accepted answer suggested.
After that, restart rabbitMQ, brew services restart rabbitmq
If I understand correctly you may be experiencing the problem because in order to be able to set the labels "text" property you actually have to use the "content" property.
so instead of:
Label output = null;
output = Label1;
output.Text = "hello";
try:
Label output = null;
output = Label1;
output.Content = "hello";
The Document is here (in Chinese)please click.
you can use
git stash list
git stash drop stash@{0}
//open and get the file handle
FILE* fh;
fopen_s(&fh, filename, "r");
//check if file exists
if (fh == NULL){
printf("file does not exists %s", filename);
return 0;
}
//read line by line
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, fh) != NULL) {
printf(line);
}
free(line); // dont forget to free heap memory
just after TouchableWithoutFeedback
or <TouchableHighlight>
insert a <View>
this way you won't get this error. why is that then @Pedram answer or other answers explains enough.
Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.
If you want repeatable fade animation you can do that by using CABasicAnimation
like below :
extension UIView {
enum AnimationKeyPath: String {
case opacity = "opacity"
}
func flash(animation: AnimationKeyPath ,withDuration duration: TimeInterval = 0.5, repeatCount: Float = 5){
let flash = CABasicAnimation(keyPath: animation.rawValue)
flash.duration = duration
flash.fromValue = 1 // alpha
flash.toValue = 0 // alpha
flash.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
flash.autoreverses = true
flash.repeatCount = repeatCount
layer.add(flash, forKey: nil)
}
}
// You can use it with all kind of UIViews e.g. UIButton, UILabel, UIImage, UIImageView, ...
imageView.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
titleLabel.flash(animation: .opacity, withDuration: 1, repeatCount: 5)
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
It can be retrieved using REST, see Version API :
curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v4/version
For authentication see Personal access tokens documentation.
In case you need HORIZONTAL SPLIT resize as well:
The command is the same for all splits, just the parameter changes:
-
+
instead of <
>
Examples:
Decrease horizontal size by 10 columns
:10winc -
Increase horizontal size by 30 columns
:30winc +
or within normal mode:
Horizontal splits
10 CTRL+w -
30 CTRL+w +
Vertical splits
10 CTRL+w < (decrease)
30 CTRL+w > (increase)
This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).
Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d
(and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.
You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb
.
Here's the breakdown of the fields:
address
(after the at
) - the location in memory the code is trying to access (it's likely that 10
and 11
are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0
)ip
- instruction pointer, ie. where the code which is trying to do this livessp
- stack pointererror
- An error code for page faults; see below for what this means on x86.
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
*/
I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.
In my case, that just fix my progressive increase of similar blocked threads:
ExecutorService::awaitTermination(x, TimeUnit)
and ExecutorService::shutdownNow()
(if necessary) in my finally clause.For information, I've used the following commands to detect thread count & list locked threads:
ps -u javaAppuser -L|wc -l
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log
cat threadPrint*.log |grep "pool-"|wc -l
All the cool kids are doing functional programming (hello React users) these days so I thought I would give the functional solution. In my view it's actually a lot nicer than the imperatival for
and each
loops that have been proposed thus far and with ES6 syntax it is quite elegant.
There's now a great way of doing this called findIndex
which takes a function that return true
/false
based on whether the array element matches (as always, check for browser compatibility though).
var index = peoples.findIndex(function(person) {
return person.attr1 == "john"
}
With ES6 syntax you get to write this:
var index = peoples.findIndex(p => p.attr1 == "john")
If you're looking for index
where peoples[index].attr1 == "john"
use:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Step 1
Use .map()
to get an array of values given a particular key:
var values = object_array.map(function(o) { return o.your_key; });
The line above takes you from here:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
To here:
var values = [ "bob", "john", "larry" ];
Step 2
Now we just use .indexOf()
to find the index of the key we want (which is, of course, also the index of the object we're looking for):
var index = values.indexOf(your_value);
Solution
We combine all of the above:
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");
Or, if you prefer ES6 syntax:
var index = peoples.map((o) => o.attr1).indexOf("john");
var peoples = [_x000D_
{ "attr1": "bob", "attr2": "pizza" },_x000D_
{ "attr1": "john", "attr2": "sushi" },_x000D_
{ "attr1": "larry", "attr2": "hummus" }_x000D_
];_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("john");_x000D_
console.log("index of 'john': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr1).indexOf("larry");_x000D_
console.log("index of 'larry': " + index);_x000D_
_x000D_
var index = peoples.map(function(o) { return o.attr1; }).indexOf("fred");_x000D_
console.log("index of 'fred': " + index);_x000D_
_x000D_
var index = peoples.map((o) => o.attr2).indexOf("pizza");_x000D_
console.log("index of 'pizza' in 'attr2': " + index);
_x000D_
check this quick reminder of file path
Here is all you need to know about relative file paths:
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
This is how I made it without extra css or jquery:
<div class="form-group">
<div class="input-group">
<label class="sr-only" for="extra3">Extra name 3</label>
<input type="text" id="extra3" class="form-control" placeholder="Extra name">
<span class="input-group-addon">
<label class="checkbox-inline">
Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
</label>
</span>
<span class="input-group-addon">
<label class="checkbox-inline">
Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
</label>
</span>
<span class="input-group-addon">
To be paid?
<select>
<option value="online">Online</option>
<option value="on spot">On Spot</option>
</select>
</span>
</div>
</div>
The rules (which did not change in C++11):
std
namespace is reserved. (You are allowed to add template specializations, though.) From the 2003 C++ Standard:
17.4.3.1.2 Global names [lib.global.names]
Certain sets of names and function signatures are always reserved to the implementation:
- Each name that contains a double underscore (
__
) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.- Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165
165) Such names are also reserved in namespace
::std
(17.4.3.1).
Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:
7.1.3 Reserved identifiers
Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
- All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
- Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
- All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
- Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.
No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.
If the program removes (with
#undef
) any macro definition of an identifier in the first group listed above, the behavior is undefined.154) The list of reserved identifiers with external linkage includes
errno
,math_errhandling
,setjmp
, andva_end
.
Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:
E
followed a digit or uppercase letter:
is
or to
followed by a lowercase letter
LC_
followed by an uppercase letter
f
or l
are reserved
SIG
followed by an uppercase letter are reserved
SIG_
followed by an uppercase letter are reserved
str
, mem
, or wcs
followed by a lowercase letter are reserved
PRI
or SCN
followed by any lowercase letter or X
are reserved
_t
are reserved
While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.
Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.
After doing research on this article I no longer end my identifiers with _t
as this is reserved by the POSIX standard.
The rule about any identifier ending with _t
surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.
CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.
This one worked for me
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
Button1_Click
End If
End Sub
Darwind code didn't show the keyboard.
This works for me:
_searchText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(_searchText, InputMethodManager.SHOW_IMPLICIT);
in case the keyboard is not showing, try to force:
imm.showSoftInput(_searchText, InputMethodManager.SHOW_FORCED);
To change package I have searched and tried many methods but some are very hard and some are outdated. While searching I found a website that discuss a very simple method that are tested and personally i have also used this. Link : https://www.geoclassifieds.in/2021/02/change-package-name-react-native.html
0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
Why not implement your own replace?
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.
Here is a revised and working version:
Date.prototype.getWeek = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
return 1 + Math.ceil(dayDiff / 7);
}
else { // jan 4th is on the next week (so next week is week 1)
return Math.ceil(dayDiff / 7);
}
};
Using getconf is indeed the most portable way, however the variable has different names in BSD and Linux to getconf, so you have to test both, as this gist suggests: https://gist.github.com/jj1bdx/5746298 (also includes a Solaris fix using ksh)
I personally use:
$ getconf _NPROCESSORS_ONLN 2>/dev/null || getconf NPROCESSORS_ONLN 2>/dev/null || echo 1
And if you want this in python you can just use the syscall getconf uses by importing the os module:
$ python -c 'import os; print os.sysconf(os.sysconf_names["SC_NPROCESSORS_ONLN"]);'
As for nproc
, it's part of GNU Coreutils, so not available in BSD by default. It uses sysconf() as well after some other methods.
I'd like to add my Python3 answer for completeness:
from io import BytesIO
from zipfile import ZipFile
import requests
def get_zip(file_url):
url = requests.get(file_url)
zipfile = ZipFile(BytesIO(url.content))
zip_names = zipfile.namelist()
if len(zip_names) == 1:
file_name = zip_names.pop()
extracted_file = zipfile.open(file_name)
return extracted_file
return [zipfile.open(file_name) for file_name in zip_names]
There are 3 ways I can think of:
The way that is easiest to explain is
:%s/phrase to delete//gc
but you can also (personally I use this second one more often) do a regular search for the phrase to delete
/phrase to delete
Vim will take you to the beginning of the next occurrence of the phrase.
Go into insert mode (hit i) and use the Delete key to remove the phrase.
Hit escape when you have deleted all of the phrase.
Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed
Continue hitting n and dot until you are done.
Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you
Count the number of characters you want to delete
Type that number in (with number keys)
Hit the x key - characters should get deleted
Continue through with n and dot like in the second method.
PS - And if you didn't know already you can do a capital n to move backwards through the search matches.
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
It always depends on what you need.
You should use operator[]
when you need direct access to elements in the vector (when you need to index a specific element in the vector). There is nothing wrong in using it over iterators. However, you must decide for yourself which (operator[]
or iterators) suits best your needs.
Using iterators would enable you to switch to other container types without much change in your code. In other words, using iterators would make your code more generic, and does not depend on a particular type of container.
initialize mysql before start on windows.
mysqld --initialize
I agree with this comment that using a table driven approach is often better.
In C# 1.0 this was not possible because it didn't have generics and anonymous delegates. New versions of C# have the scaffolding to make this work. Having a notation for object literals is also helps.
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
My site faces same issue too.
Using Facebook debug tool is no help at all. Fetch new data but not IMAGE CACHE.
I forced facebook to clear IMAGE CACHE by add www. into image url. In your case is remove www. and config web server redirect.
add/remove www. in image url should solve the problem
I wanted a more enhanced version so I ended up with a module which allows: UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately. Supports pyinstaller.
prototype:
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
winadmin.py
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7
import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3
# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"
wrconn = None
#fake logger for message sending
class fakelogger:
def __init__(self, xlogger=None):
self.lg = xlogger
def write(self, a):
global wrconn
if wrconn is not None:
wrconn.send(LOGTAG+a)
elif self.lg is not None:
self.lg.write(a)
else:
print(LOGTAG+a)
class Writer():
wzconn=None
counter = 0
def __init__(self, tport=6000,authkey=b'secret password'):
global wrconn
if wrconn is None:
address = ('localhost', tport)
try:
wrconn = Client(address, authkey=authkey)
except:
wrconn = None
wzconn = wrconn
self.wrconn = wrconn
self.__class__.counter+=1
def __del__(self):
self.__class__.counter-=1
if self.__class__.counter == 0 and wrconn is not None:
import time
time.sleep(0.1) # slows deletion but is enough to print stderr
wrconn.send('close')
wrconn.close()
def sendx(cls, mesg):
cls.wzconn.send(msg)
def sendw(self, mesg):
self.wrconn.send(msg)
#fake file to be passed as stdout and stderr
class connFile():
def __init__(self, thekind="out", tport=6000):
self.cnt = 0
self.old=""
self.vg=Writer(tport)
if thekind == "out":
self.kind=sys.__stdout__
else:
self.kind=sys.__stderr__
def write(self, *args, **kwargs):
global wrconn
global dbz
from io import StringIO # # Python2 use: from cStringIO import StringIO
mystdout = StringIO()
self.cnt+=1
__builtin__.print(*args, **kwargs, file=mystdout, end = '')
#handles "\n" wherever it is, however usually is or string or \n
if "\n" not in mystdout.getvalue():
if mystdout.getvalue() != "\n":
#__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
self.old += mystdout.getvalue()
else:
#__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
if wrconn is not None:
wrconn.send(dbz[1]+self.old)
else:
__builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
self.kind.flush()
self.old=""
else:
vv = mystdout.getvalue().split("\n")
#__builtin__.print("V:",vv, file=self.kind, end='')
for el in vv[:-1]:
if wrconn is not None:
wrconn.send(dbz[0]+self.old+el)
self.old = ""
else:
__builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
self.kind.flush()
self.old=""
self.old=vv[-1]
def open(self):
pass
def close(self):
pass
def flush(self):
pass
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print ("Admin check failed, assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
print("Unsupported operating system for this module: %s" % (os.name,))
exit()
#raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
def runAsAdmin(cmdLine=None, wait=True, hidden=False):
if os.name != 'nt':
raise (RuntimeError, "This function is only implemented on Windows.")
import win32api, win32con, win32process
from win32com.shell.shell import ShellExecuteEx
python_exe = sys.executable
arb=""
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif not isinstance(cmdLine, (tuple, list)):
if isinstance(cmdLine, (str)):
arb=cmdLine
cmdLine = [python_exe] + sys.argv
print("original user", arb)
else:
raise( ValueError, "cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
if len(arb) > 0:
params += " "+arb
cmdDir = ''
if hidden:
showCmd = win32con.SW_HIDE
else:
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=64,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = procInfo['hProcess']
return rc
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
global dbz
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
import getpass
uname = getpass.getuser()
if (tport> 0):
address = ('localhost', tport) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
rc = runAsAdmin(uname, wait=False, hidden=True)
if (tport> 0):
hr = win32event.WaitForSingleObject(rc, 40)
conn = listener.accept()
print ('connection accepted from', listener.last_accepted)
sys.stdout.flush()
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
else:
if msg.startswith(dbz[0]+LOGTAG):
if xlogger != None:
xlogger.write(msg[len(LOGTAG):])
else:
print("Missing a logger")
else:
print(msg)
sys.stdout.flush()
listener.close()
else: #no port connection, its silent
WaitForSingleObject(rc, INFINITE);
return False
else:
#redirect prints stdout on master, errors in error.txt
print("HIADM")
sys.stdout.flush()
if (tport > 0) and (redir):
vox= connFile(tport=tport)
sys.stdout=vox
if not errFile:
sys.stderr=vox
else:
vfrs=open("errFile.txt","w")
sys.stderr=vfrs
#print("HI ADMIN")
return True
def test():
rc = 0
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
sys.stdout.flush()
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print ("You are an admin!", os.getpid(), "params: ", sys.argv)
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
Even later:
As pointed out by @DzimitryM, percent()
has been "retired" in favor of label_percent()
, which is a synonym for the old percent_format()
function.
label_percent()
returns a function, so to use it, you need an extra pair of parentheses.
library(scales)
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
label_percent()(x)
## [1] "-100%" "0%" "10%" "56%" "100%" "10 000%"
Customize this by adding arguments inside the first set of parentheses.
label_percent(big.mark = ",", suffix = " percent")(x)
## [1] "-100 percent" "0 percent" "10 percent"
## [4] "56 percent" "100 percent" "10,000 percent"
An update, several years later:
These days there is a percent
function in the scales
package, as documented in krlmlr's answer. Use that instead of my hand-rolled solution.
Try something like
percent <- function(x, digits = 2, format = "f", ...) {
paste0(formatC(100 * x, format = format, digits = digits, ...), "%")
}
With usage, e.g.,
x <- c(-1, 0, 0.1, 0.555555, 1, 100)
percent(x)
(If you prefer, change the format from "f"
to "g"
.)
Expanding on Brian Camire's Answer:
Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
with CTRL+SHIFT+ENTER
will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:
=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))
Don't forget to press CTRL+SHIFT+ENTER
to treat the formula as an "array formula".
Perhaps something akin to:
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
Short and sweet.
With concerns to your error, the other answers use C-style file access, where you get a FILE*
with specific functions.
Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek()
will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof()
. Ergo, we just peek()
at the stream and see if it's eof()
, since an empty file has nothing to peek at.
Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:
std::ifstream file("filename");
if (!file)
{
// file is not open
}
if (is_empty(file))
{
// file is empty
}
// file is open and not empty
In Java 8
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import javax.xml.bind.DatatypeConverter;
Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
scanner.close();
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);
System.out.println(encoded.toLowerCase());
Why all this complicatedness?
sh 'env'
does what you need (under *nix)
mysql default port is 3306 can you try putting it and then try
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
All the answers are great, and it will do what you ask it too, but I believe the best way to delete this, and the best way for the garbage collector (if you are running node.js) is like this:
var json = { <your_imported_json_here> };
var key = "somekey";
json[key] = null;
delete json[key];
This way the garbage collector for node.js
will know that json['somekey']
is no longer required, and will delete it.
plt.figure(figsize=(15,10))
graph = sns.barplot(x='name_column_x_axis', y="name_column_x_axis", data = dataframe_name , color="salmon")
for p in graph.patches:
graph.annotate('{:.0f}'.format(p.get_height()), (p.get_x()+0.3, p.get_height()),
ha='center', va='bottom',
color= 'black')
Download the latest gradle from https://gradle.org/install and set the gradle path upto bin in your PATH variable and export path in the directory you are working in
example : export PATH=/home/abc/android-sdk-linux/tools:/home/abc/android-sdk-linux/platform-tools:/home/abc/android-sdk-linux/tools:/home/abc/android-sdk-linux/platform-tools:/home/abc/Downloads/gradle-4.4.1/bin
I spent my whole day resolve this and ultimately this solution worked for me,
You can justify the navbar contents by using:
@media (min-width: 768px){
.navbar-nav{
margin: 0 auto;
display: table;
table-layout: fixed;
float: none;
}
}
See this live: http://jsfiddle.net/panchroma/2fntE/
Good luck!
Brace expansion doesn't work, but *
, ?
and []
do. If you set shopt -s extglob
then you can also use extended pattern matching:
?()
- zero or one occurrences of pattern*()
- zero or more occurrences of pattern+()
- one or more occurrences of pattern@()
- one occurrence of pattern!()
- anything except the patternHere's an example:
shopt -s extglob
for arg in apple be cd meet o mississippi
do
# call functions based on arguments
case "$arg" in
a* ) foo;; # matches anything starting with "a"
b? ) bar;; # matches any two-character string starting with "b"
c[de] ) baz;; # matches "cd" or "ce"
me?(e)t ) qux;; # matches "met" or "meet"
@(a|e|i|o|u) ) fuzz;; # matches one vowel
m+(iss)?(ippi) ) fizz;; # matches "miss" or "mississippi" or others
* ) bazinga;; # catchall, matches anything not matched above
esac
done
This should only allow decimals > 0
^([0-9]\.\d+)|([1-9]\d*\.?\d*)$
More generic approuch
public virtual void Delete<T>(int id) where T : BaseEntity, new()
{
T instance = Activator.CreateInstance<T>();
instance.Id = id;
if (dbContext.Entry<T>(entity).State == EntityState.Detached)
{
dbContext.Set<T>().Attach(entity);
}
dbContext.Set<T>().Remove(entity);
}
To just get the index column names df.index.names
will work for both a single Index or MultiIndex as of the most recent version of pandas.
As someone who found this while trying to find the best way to get a list of index names + column names, I would have found this answer useful:
names = list(filter(None, df.index.names + df.columns.values.tolist()))
This works for no index, single column Index, or MultiIndex. It avoids calling reset_index() which has an unnecessary performance hit for such a simple operation. I'm surprised there isn't a built in method for this (that I've come across). I guess I run into needing this more often because I'm shuttling data from databases where the dataframe index maps to a primary/unique key, but is really just another column to me.
This is not possible. The java specification forbids the use of primitives in generics. However, you can create ArrayList<Integer>
and call add(i)
if i
is an int thanks to boxing.
Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.
const temp = [];
const t = {
name: "name",
etc: [
{
a: 0,
},
],
};
for (let i = 0; i < 3; i++) {
const bla = Object.assign({}, t);
bla.name = bla.name + i;
bla.etc[0].a = i;
temp.push(bla);
}
console.log(JSON.stringify(temp));
ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType()
, and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.
Check out this tutorial on how to use the RecyclerView to do what you are looking for.
customerList.Any(x=>x.Firstname == "John")
you also use this:
background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%;
I don't know your div-values, but let's assume you've got those.
height: auto;
max-width: 600px;
Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.
Chris
Disclaimer: I'm the author of jgeXml.
jgexml has Node.js based utility xsd2json
which does a transformation between an XML schema (XSD) and a JSON schema file.
As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.
A sample of the purchaseorder.xsd given in another answer is rendered as:
"PurchaseOrderType": {
"type": "object",
"properties": {
"shipTo": {
"$ref": "#/definitions/USAddress"
},
"billTo": {
"$ref": "#/definitions/USAddress"
},
"comment": {
"$ref": "#/definitions/comment"
},
"items": {
"$ref": "#/definitions/Items"
},
"orderDate": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
}
},
I have experienced the same situation I did the below as this much easier.
By passing commit-Id
you can reach to the particular commit you want to go:
git reset --hard {commit-id}
As you want to remove your last commit so you need to pass the commit-Id
where you need to move your pointer:
git reset --hard db0c078d5286b837532ff5e276dcf91885df2296
I just wanted to add a very subtle point about %%timeit. Given it runs the "magics" on the cell, you'll get error...
UsageError: Line magic function %%timeit
not found
...if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.
I know it's a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.
This is one of most confusing error messages that every VC++ programmers have seen time and time again. Let’s make things clarity first.
A. What is symbol? In short, a symbol is a name. It can be a variable name, a function name, a class name, a typedef name, or anything except those names and signs that belong to C++ language. It is user defined or introduced by a dependency library (another user-defined).
B. What is external?
In VC++, every source file (.cpp,.c,etc.) is considered as a translation unit, the compiler compiles one unit at a time, and generate one object file(.obj) for the current translation unit. (Note that every header file that this source file included will be preprocessed and will be considered as part of this translation unit)Everything within a translation unit is considered as internal, everything else is considered as external. In C++, you may reference an external symbol by using keywords like extern
, __declspec (dllimport)
and so on.
C. What is “resolve”? Resolve is a linking-time term. In linking-time, linker attempts to find the external definition for every symbol in object files that cannot find its definition internally. The scope of this searching process including:
This searching process is called resolve.
D. Finally, why Unresolved External Symbol? If the linker cannot find the external definition for a symbol that has no definition internally, it reports an Unresolved External Symbol error.
E. Possible causes of LNK2019: Unresolved External Symbol error. We already know that this error is due to the linker failed to find the definition of external symbols, the possible causes can be sorted as:
For example, if we have a function called foo defined in a.cpp:
int foo()
{
return 0;
}
In b.cpp we want to call function foo, so we add
void foo();
to declare function foo(), and call it in another function body, say bar()
:
void bar()
{
foo();
}
Now when you build this code you will get a LNK2019 error complaining that foo is an unresolved symbol. In this case, we know that foo() has its definition in a.cpp, but different from the one we are calling(different return value). This is the case that definition exists.
If we want to call some functions in a library, but the import library is not added into the additional dependency list (set from: Project | Properties | Configuration Properties | Linker | Input | Additional Dependency
) of your project setting. Now the linker will report a LNK2019 since the definition does not exist in current searching scope.
For Example you have the package "com.abc" and you have multiple packages inside it, You can use like
@ComponentScan("com.abc")
Yeah you can use reflections to access private variables. Altough not a good idea.
Check this out:
http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection
<div>
<div style="float:left;width:45%;" >
<span>source list</span>
<select size="10">
<option />
<option />
<option />
</select>
</div>
<div style="float:right;width:45%;">
<span>destination list</span>
<select size="10">
<option />
<option />
<option />
</select>
</div>
<div style="clear:both; font-size:1px;"></div>
</div>
Clear must be used so as to prevent the float bug (height warping of outer Div).
style="clear:both; font-size:1px;
This is quite simple:
Here's a working version of your code:
(async function(){
var response = await superagent.get('...')
console.log(response)
})()
To make a batch file for its current directory and sub directories:
cd %~dp0
attrib -h -r -s /s /d /l *.*
I tried most part of solutions, but they didn't work for my case, so I make a new function that work for most of cases and for any type of array:
import math
def chunkIt(seq, num):
seqLen = len(seq)
total_chunks = math.ceil(seqLen / num)
items_per_chunk = num
out = []
last = 0
while last < seqLen:
out.append(seq[last:(last + items_per_chunk)])
last += items_per_chunk
return out
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
In my case, my dataframe has the following characteristics
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
The first option data.index = pd.to_datetime(data.index)
returned
ParserError: String does not contain a date: ParserError: String does not contain a date:
The second option: data.index.to_datetime()
returned
AttributeError: 'Index' object has no attribute 'to_datetime'
It returned
Another option I have tested is. data.index = pd.to_datetime(data.index)
It returned: ParserError: String does not contain a date:
What could be my problem? Thanks
Since the column may be null in the database, the rs.getString() will throw a NullPointerException()
No.
rs.getString
will not throw NullPointer
if the column is present in the selected result set (SELECT query columns)
For a particular record if value for the 'comumn is null in db, you must do something like this -
String myValue = rs.getString("myColumn");
if (rs.wasNull()) {
myValue = ""; // set it to empty string as you desire.
}
You may want to refer to wasNull()
documentation -
From java.sql.ResultSet
boolean wasNull() throws SQLException;
* Reports whether
* the last column read had a value of SQL <code>NULL</code>.
* Note that you must first call one of the getter methods
* on a column to try to read its value and then call
* the method <code>wasNull</code> to see if the value read was
* SQL <code>NULL</code>.
*
* @return <code>true</code> if the last column value read was SQL
* <code>NULL</code> and <code>false</code> otherwise
* @exception SQLException if a database access error occurs or this method is
* called on a closed result set
*/
*::after {
content: none !important;
}
*::before {
content: none !important;
}
_x000D_
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
Anyone wants to use command line to sync projects with gradle files, please note:
Since Gradle 5.0,
The
--recompile-scripts
command-line option has been removed.
<<=
is like +=
, but for a left shift. x <<= 1
means x = x << 1
. That's why 90 >>= angle
doesn't parse. And, like others have said, Java doesn't have an elegant syntax for checking if a number is an an interval, so you have to do it the long way. It also can't do if (x == 0 || 1)
, and you're stuck writing it out the long way.
I am mostly posting this in case someone comes along and is not aware that VB2005 and VB2008 have update utilities that convert older VB versions to it's format. Especially since no one bothered to point that fact out.
Points taken, but maintenance of this VB6 product is unavoidable. It would also be costly in man-hours to replace the Sheridan controls with native ones. Simply developing on a 32-bit machine would be a better alternative than doing that. I would like to install everything on Win7 64-bit ideally. – CJ7
Have you tried utilizing the code upgrade functionality of VB Express 2005+?
If not, 1. Make a copy of your code - folder and all. 2. Import the project into VB express 2005. This will activate the update wizard. 3. Debug and get the app running. 4. Create a new installer utilizing MS free tool. 5. You now have a 32 bit application with a 32 bit installer.
Until you do this, you will never know how difficult or hard it will be to update and modernize the program. It is quite possible that the wizard will update the Sheridan controls to the VB 2005 controls. Again, you will not know if it does and how well it does it until you try it.
Alternatively, stick with the 32 Bit versions of Windows 7 and 8. I have Windows 7 x64 and a program that will not run. However, the program will run in Windows 7 32 bit as well as Windows 8 RC 32 bit. Under Windows 8 RC 32, I was prompted to enable 16 bit emulation which I did and the program rand quite fine afterwords.
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.
One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.
You can use reduce() - A functional way.
words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})
returns:
{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}
After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.
But it also works for the Select
option. See below for an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
None of these answers worked for me. I had to use the command line:
mysql -u root db_name < db_dump.sql
SET NAMES 'utf8';
SOURCE db_dump.sql;
Done!
The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined
)!
It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.
import web3 from './web3';
import xyz from './build/xyz.json';
const i = new web3.eth.Contract(
JSON.parse(xyz.interface),
'0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);
export default i;
which was misspelled as
JSON.parse(xyz.intereface)
which was returning nothing!
Have a look at the daemon tool from the libslack package:
On Mac OS X use a launchd script for shell daemon.
to switchto a frame:
driver.switchTo.frame("Frame_ID");
to switch to the default again.
driver.switchTo().defaultContent();
Using $_SERVER['HTTP_HOST']
gets me (subdomain.)maindomain.extension. It seems like the easiest solution to me.
If you're actually 'redirecting' through an iFrame, you could add a GET parameter which states the domain.
<iframe src="myserver.uk.com?domain=one.com"/>
And then you could set a session variable that persists this data throughout your application.
This might not apply to everyone case, but when extracting from xml i had this problem, which i solved with this.
function grab_xml(what){
var return_xml =null;
$.ajax({
type: "GET",
url: what,
success:function(xml){return_xml =xml;},
async: false
});
return(return_xml);
}
then get the xml:
var sector_xml=grab_xml("p/sector.xml");
var tt=$(sector_xml).find("pt");
Then I then made this function to extract xml line , when i need to read from an XML file, containing html tags.
function extract_xml_line(who){
var tmp = document.createElement("div");
tmp.appendChild(who[0]);
var tmp=$(tmp.innerHTML).html();
return(tmp);
}
and now to conclude:
var str_of_html= extract_xml_line(tt.find("intro")); //outputs the intro tag and whats inside it: helllo <b>in bold</b>
Please try the following code:
CREATE TABLE [dbo].[Department](
[Department_name] char(10) NULL
)
INSERT INTO [dbo].[Department]([Department_name]) VALUES ('Family Medicine')
--error will occur
ALTER TABLE [Department] ALTER COLUMN [Department_name] char(50)
INSERT INTO [dbo].[Department]([Department_name]) VALUES ('Family Medicine')
select * from [Department]
An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:
Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");
Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);
// This is not possible: It would throw an
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");
// This is still possible:
realMap.put("E", "F");
// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F".
In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.
Update:
As pointed out in a comment, an immutable map can also be created with the standard API using
Map<String, String> immutableMap =
Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap));
This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap
without having to add the dependency to Guava.
if some module you cant find, try with Static URI, for example:
var Mustache = require("/media/fabio/Datos/Express/2_required_a_module/node_modules/mustache/mustache.js");
This example, run on Ubuntu Gnome 16.04 of 64 bits, node -v: v4.2.6, npm: 3.5.2 Refer to: Blog of Ben Nadel
MSDN has an article Working With Large Value Types, which tries to explain how the import parts work, but it can get a bit confusing since it does 2 things simultaneously.
Here I am providing a simplified version, broken into 2 parts. Assume the following simple table:
CREATE TABLE [Thumbnail](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Data] [varbinary](max) NULL
CONSTRAINT [PK_Thumbnail] PRIMARY KEY CLUSTERED
(
[Id] ASC
) ) ON [PRIMARY]
If you run (in SSMS):
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
it will show, that the result looks like a table with one column named BulkColumn
. That's why you can use it in INSERT like:
INSERT [Thumbnail] ( Data )
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
The rest is just fitting it into an insert with more columns, which your table may or may not have. If you name the result of that select FOO
then you can use SELECT Foo.BulkColumn
and as
after that constants for other fields in your table.
The part that can get more tricky is how to export that data back into a file so you can check that it's still OK. If you run it on cmd line:
bcp "select Data from B2B.dbo.Thumbnail where Id=1"
queryout D:\T\TestImage1_out2.dds -T -L 1
It's going to start whining for 4 additional "params" and will give misleading defaults (which will result in a changed file). You can accept the first one, set the 2nd to 0 and then assept 3rd and 4th, or to be explicit:
Enter the file storage type of field Data [varbinary(max)]:
Enter prefix-length of field Data [8]: 0
Enter length of field Data [0]:
Enter field terminator [none]:
Then it will ask:
Do you want to save this format information in a file? [Y/n] y
Host filename [bcp.fmt]: C:\Test\bcp_2.fmt
Next time you have to run it add -f C:\Test\bcp_2.fmt
and it will stop whining :-)
Saves a lot of time and grief.
It works with Android Studio 1.2 + OpenCV-2.4.11-android-sdk (.zip), too.
Just do the following:
1) Follow the answer that starts with "You can do this very easily in Android Studio. Follow the steps below to add OpenCV in your project as library." by TGMCians.
2) Modify in the <yourAppDir>\libraries\opencv
folder your newly created build.gradle
to (step 4 in TGMCians' answer, adapted to OpenCV2.4.11-android-sdk and using gradle 1.1.0):
apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
}
}
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
minSdkVersion 8
targetSdkVersion 21
versionCode 2411
versionName "2.4.11"
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
aidl.srcDirs = ['src']
}
}
}
3) *.so files that are located in the directories "armeabi", "armeabi-v7a", "mips", "x86"
can be found under (default OpenCV-location): ..\OpenCV-2.4.11-android-sdk\OpenCV-android-sdk\sdk\native\libs
(step 9 in TGMCians' answer).
Enjoy and if this helped, please give a positive reputation. I need 50 to answer directly to answers (19 left) :)
Remember that char
is an integral type, and thus can be given an integer value, as well as a char constant.
char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);
You have a pointer to a char
. So as your system knows, on that memory address there is a char
value on sizeof(char)
space. When you cast it up to int*
, you will work with data of sizeof(int)
, so you will print your char and some memory-garbage after it as an integer.
This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):
Why does Node.js' fs.readFile() return a buffer instead of string?
Even if you as the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.
Even if Node knew it were to read a text file, it still would have no idea which character encoding is used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.
There are ways to guess the character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.
So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.
And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.
I pipe the output from the accepted answer into dialog
, to give me an interactive list:
#!/bin/bash
TMP_FILE=/tmp/selected-git-branch
eval `resize`
dialog --title "Recent Git Branches" --menu "Choose a branch" $LINES $COLUMNS $(( $LINES - 8 )) $(git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short) %(committerdate:short)') 2> $TMP_FILE
if [ $? -eq 0 ]
then
git checkout $(< $TMP_FILE)
fi
rm -f $TMP_FILE
clear
Save as (e.g.) ~/bin/git_recent_branches.sh
and chmod +x
it. Then git config --global alias.rb '!git_recent_branches.sh'
to give me a new git rb
command.
Recommended Reading: How I save 5h/week on Gradle builds!
According to this excellent post you should try to optimized the following:
For two char sequence as delimeters "AND" and "OR" this should be worked. Don't forget to trim while using.
String text ="ISTANBUL AND NEW YORK AND PARIS OR TOKYO AND MOSCOW";
String[] cities = text.split("AND|OR");
Result : cities = {"ISTANBUL ", " NEW YORK ", " PARIS ", " TOKYO ", " MOSCOW"}
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement
(btw I might want to use #someElement
because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
If you're looking to generate a single error message string that contains the ModelState
error messages you can use SelectMany
to flatten the errors into a single list:
if (!ModelState.IsValid)
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
Your div
variable is a string, not a DOM element object:
var div = '<div>top div</div>';
Strings don't have an appendChild
method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:
var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));
div.appendChild(element);
A slight modification beyond @udondan's answer. I like to reuse the registered variable names with the set_fact
to help keep the clutter to a minimum.
So if I were to register using the variable, psk
, I'd use that same variable name with creating the set_fact
.
- name: generate PSK
shell: openssl rand -base64 48
register: psk
delegate_to: 127.0.0.1
run_once: true
- set_fact:
psk={{ psk.stdout }}
- debug: var=psk
run_once: true
Then when I run it:
$ ansible-playbook -i inventory setup_ipsec.yml
PLAY [all] *************************************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************************
ok: [hostc.mydom.com]
ok: [hostb.mydom.com]
ok: [hosta.mydom.com]
TASK [libreswan : generate PSK] ****************************************************************************************************************************************************
changed: [hosta.mydom.com -> 127.0.0.1]
TASK [libreswan : set_fact] ********************************************************************************************************************************************************
ok: [hosta.mydom.com]
ok: [hostb.mydom.com]
ok: [hostc.mydom.com]
TASK [libreswan : debug] ***********************************************************************************************************************************************************
ok: [hosta.mydom.com] => {
"psk": "6Tx/4CPBa1xmQ9A6yKi7ifONgoYAXfbo50WXPc1kGcird7u/pVso/vQtz+WdBIvo"
}
PLAY RECAP *************************************************************************************************************************************************************************
hosta.mydom.com : ok=4 changed=1 unreachable=0 failed=0
hostb.mydom.com : ok=2 changed=0 unreachable=0 failed=0
hostc.mydom.com : ok=2 changed=0 unreachable=0 failed=0
I have implemented this way and it works.It is much easier than all that is reported.
We have two activities : one is the main and another is the secondary.
In secondary activity, which is where we want to end the main activity , define the following variable:
public static Activity ACTIVIDAD;
And then the following method:
public static void enlaceActividadPrincipal(Activity actividad)
{
tuActividad.ACTIVIDAD=actividad;
}
Then, in your main activity from the onCreate
method , you make the call:
actividadSecundaria.enlaceActividadPrincipal(this);
Now, you're in control. Now, from your secondary activity, you can complete the main activity. Finish calling the function, like this:
ACTIVIDAD.finish();
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
public class MyProp<T>
{
...
}
public class ClassThatUsesMyProp
{
public MyProp<String> SomeProperty { get; set; }
}
You can create a custom encoder that returns a list
when it encounters a set
. Here's an example:
>>> import json
>>> class SetEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, set):
... return list(obj)
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(set([1,2,3,4,5]), cls=SetEncoder)
'[1, 2, 3, 4, 5]'
You can detect other types this way too. If you need to retain that the list was actually a set, you could use a custom encoding. Something like return {'type':'set', 'list':list(obj)}
might work.
To illustrated nested types, consider serializing this:
>>> class Something(object):
... pass
>>> json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)
This raises the following error:
TypeError: <__main__.Something object at 0x1691c50> is not JSON serializable
This indicates that the encoder will take the list
result returned and recursively call the serializer on its children. To add a custom serializer for multiple types, you can do this:
>>> class SetEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, set):
... return list(obj)
... if isinstance(obj, Something):
... return 'CustomSomethingRepresentation'
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)
'[1, 2, 3, 4, 5, "CustomSomethingRepresentation"]'
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
Easiest Solution With Explanation (double checked solution) (faced the problem before)
Problem is:
1- I can't delete a branch
2- The terminal keep display a warning message that there are some commits that are not approved yet
3- knowing that I checked the master and branch and they are identical (up to date)
solution:
git checkout master
git merge branch_name
git checkout branch_name
git push
git checkout master
git branch -d branch_name
Explanation:
when your branch is connected to upstream remote branch (on Github, bitbucket or whatever), you need to merge (push) it into the master, and you need to push the new changes (commits) to the remote repo (Github, bitbucket or whatever) from the branch,
what I did in my code is that I switched to master, then merge the branch into it (to make sure they're identical on your local machine), then I switched to the branch again and pushed the updates or changes into the remote online repo using "git push".
after that, I switched to the master again, and tried to delete the branch, and the problem (warning message) disappeared, and the branch deleted successfully
strtok
:Since one of the suggested solutions uses strtok
, unfortunately it doesn't point out a potential memory issue (though it claims to be memory efficient). When using strtok
according to the manual, the:
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string.
It does this by loading the file into memory. If you're using large files, you need to flush them if you're done looping through the file.
<?php
function process($str) {
$line = strtok($str, PHP_EOL);
/*do something with the first line here...*/
while ($line !== FALSE) {
// get the next line
$line = strtok(PHP_EOL);
/*do something with the rest of the lines here...*/
}
//the bit that frees up memory
strtok('', '');
}
According to the manual, for the file upload part you can use the file
command:
//Create the array
$lines = file( $some_file );
foreach ( $lines as $line ) {
//do something here.
}
Try this and it will work like a charm. I was having the same error but this approach did the trick for me:
ssh USER@REMOTE "cat file"|xclip -i
It sounds like you want an image
button:
<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
Alternatively, you can use CSS to make the existing submit
button use your image as its background.
In any case, you don't want a separate <img />
element on the page.
If you are getting your gems from a public GitHub repository, you can use the shorthand
gem 'nokogiri', github: 'tenderlove/nokogiri'
For someone who'd not prefer to handle UserDefaults for some reasons, there's another option - NSKeyedArchiver & NSKeyedUnarchiver. It helps save objects into a file using archiver, and load archived file to original objects.
// To archive object,
let mutableData: NSMutableData = NSMutableData()
let archiver: NSKeyedArchiver = NSKeyedArchiver(forWritingWith: mutableData)
archiver.encode(object, forKey: key)
archiver.finishEncoding()
return mutableData.write(toFile: path, atomically: true)
// To unarchive objects,
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
let object = unarchiver.decodeObject(forKey: key)
}
I've write an simple utility to save/load objects in local storage, used sample codes above. You might want to see this. https://github.com/DragonCherry/LocalStorage
$(this).click(function(e) {
// does something
});
In reference to the above code
$(this)
is the element which as some variable.
click
is the event that needs to be performed.
the parameter e
is automatically passed from js to your function which holds the value of $(this)
value and can be used further in your code to do some operation.
For those having this problem on IIS servers.
Explanation: sometimes certificates carry an URL of an intermediate certificate instead of the actual certificate. Desktop browsers can DOWNLOAD the missing intermediate certificate using this URL. But older mobile browsers are unable to do that. So they throw this warning.
You need to
1) make sure all intermediate certificates are served by the server
2) disable unneeded certification paths in IIS - Under "Trusted Root Certification Authorities", you need to "disable all purposes" for the certificate that triggers the download.
PS. my colleague has wrote a blog post with more detailed steps: https://www.jitbit.com/maxblog/21-errcertauthorityinvalid-on-android-and-iis/
We can do it by simple means:
In FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);
In SecondActivity:
try {
Intent intent = getIntent();
String uid = intent.getStringExtra("uid");
String pwd = intent.getStringExtra("pwd");
} catch (Exception e) {
e.printStackTrace();
Log.e("getStringExtra_EX", e + "");
}
In .NET, the difference between Dictionary<,>
and HashTable
is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).
Do any of the following:
1- Update the play-services-maps library to the latest version:
com.google.android.gms:play-services-maps:16.1.0
2- Or include the following declaration within the <application>
element of AndroidManifest.xml
.
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
The problem is twofold:
.
in the routeBy default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers
: the default handler handles path="*."
. You won't find much documentation regarding the strange syntax in this path
attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0
.
Multiple solutions are possible, in my opinion in the order of 'correctness':
path="*."
attribute to path="*"
. It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!<system.webserver>
: <modules runAllManagedModulesForAllRequests="true">
:
in the routeAfter you've changed the above, by default, you'd get the following error:
A potentially dangerous Request.Path value was detected from the client (:).
You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>
, add the following: <httpRuntime requestPathInvalidCharacters="<,>,%,&,*,\,?" />
. I've removed the :
from the standard list of invalid characters.
Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:
?date=2012-12-31T22:00:00.000Z
..000
from every request. You'd still need to allow :
's (cfr point 2).Do you need to post the the form to an URL or do you only need to detect the submit-event? Because you can detect the submit-event by adding onsubmit="javascript:alert('I do also submit');"
<form action="javascript:alert('submitted');" method="post" id="testForm" onsubmit="javascript:alert('I do also submit');">...</form>
Not sure that this is what you are looking for though.
Worked for me
var myForm = document.getElementById("form");
var formData = new FormData(myForm),
obj = {};
for (var entry of formData.entries()){
obj[entry[0]] = entry[1];
}
console.log(obj);
Just to add a very simple solution, that was good enough for me, and I think addresses the OP's issue. I used the solution in this answer except with a regular Background
value instead of an image.
<Style x:Key="SomeButtonStyle" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
No re-templating beyond forcing the Background
to always be the Transparent
background from the templated button - mouseover no longer affects the background once this is done. Obviously replace Transparent
with any preferred value.
You can do this more simply using plot()
instead of plot_date()
.
First, convert your strings to instances of Python datetime.date
:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:
Process.Start("chrome.exe", "http://www.YourUrl.com");
This seem to work as expected for me, opening a new tab if Chrome is already open.
The Windows "AT" command is very similar to cron. It is available through the command line.
Based on the git documentation the best way is:
git remote -v
git remote set-url origin
where url-repository is the same URL that we get from the clone option.
Window function may solve that in one pass:
SELECT DISTINCT ON (address_id)
LAST_VALUE(purchases.address_id) OVER wnd AS address_id
FROM "purchases"
WHERE "purchases"."product_id" = 1
WINDOW wnd AS (
PARTITION BY address_id ORDER BY purchases.purchased_at DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
On your new AppDomain, try setting an AssemblyResolve event handler. That event gets called when a dependency is missing.
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
For people using IntelliJ, with these settings I was able to query from the shell (on windows).
Check your WEB-INF/web.xml file for the servlet Mapping.
There you go:
<i class="glyphicon glyphicon-search"></i>
More information:
http://getbootstrap.com/components/#glyphicons
Btw. you can use this conversion tool, this will also update the code for the icons:
Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)
<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">
<a id="toggle">click to toggle</a>
img {display: none;}
a {cursor: pointer; color: blue;}
$('#toggle').click(function() {
$('#tiger').toggle();
});
from urllib2 import Request, urlopen, HTTPError, URLError
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
page_open = urlopen(req)
except HTTPError, e:
print e.code
except URLError, e:
print e.reason
else:
print 'ok'
To answer the comment of unutbu:
Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source
I think the simplest way is:
Create a new list and add unique item.
Example:
class MyList{
int id;
string date;
string email;
}
List<MyList> ml = new Mylist();
ml.Add(new MyList(){
id = 1;
date = "2020/09/06";
email = "zarezadeh@gmailcom"
});
ml.Add(new MyList(){
id = 2;
date = "2020/09/01";
email = "zarezadeh@gmailcom"
});
List<MyList> New_ml = new Mylist();
foreach (var item in ml)
{
if (New_ml.Where(w => w.email == item.email).SingleOrDefault() == null)
{
New_ml.Add(new MyList()
{
id = item.id,
date = item.date,
email = item.email
});
}
}
You will need to devise an algorithm to extract the data in a usable format. Regardless of which PDF library you use, you will need to do this. Characters and graphics are drawn by a series of stateful drawing operations, i.e. move to this position on the screen and draw the glyph for character 'c'.
I suggest that you extend org.apache.pdfbox.pdfviewer.PDFPageDrawer
and override the strokePath
method. From there you can intercept the drawing operations for horizontal and vertical line segments and use that information to determine the column and row positions for your table. Then its a simple matter of setting up text regions and determining which numbers/letters/characters are drawn in which region. Since you know the layout of the regions, you'll be able to tell which column the extracted text belongs to.
Also, the reason you may not have spaces between text that is visually separated is that very often, a space character is not drawn by the PDF. Instead the text matrix is updated and a drawing command for 'move' is issued to draw the next character and a "space width" apart from the last one.
Good luck.
I added .table-responsive
to the table and it worked. From the docs
Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
REQUIREMENTS files.
Seriously, I use this in conjunction with virtualenv every day.
QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS
Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.
From Heroku's documentation https://devcenter.heroku.com/articles/python
You create a virtual environment, and set your shell to use it. (bash/*nix instructions)
virtualenv env
source env/bin/activate
Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.
pip install flask
Now you can dump the info about which packages are installed with
pip freeze > requirements.txt
If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:
pip install -r requirements.txt
Any time you can automate tedium like this is awesome.
It will be fixed 64 chars, so use char(64)
You can do it faster without any imports just by using magics:
%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
Notice that all env variable are strings, so no need to use "
. You can verify that env-variable is set up by running: %env <name_of_var>
. Or check all of them with %env
.
Actually, you can get PowerShell to run using .NET 4 without affecting other .NET applications. I needed to do so to use the new HttpWebRequest "Host" property, however changing the "OnlyUseLatestCLR" broke Fiddler as that could not be used under .NET 4.
The developers of PowerShell obviously foresaw this happening, and they added a registry key to specify what version of the Framework it should use. One slight issue is that you need to take ownership of the registry key before changing it, as even administrators do not have access.
Change the value of that key to the required version. Keep in mind though that some snapins may no longer load unless they are .NET 4 compatible (WASP is the only one I have had trouble with, but I don't really use it anyway). VMWare, SQL Server 2008, PSCX, Active Directory (Microsoft and Quest Software) and SCOM all work fine.
you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.
Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html
If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.
As of Ansible 2.0 there seems to be an option called strategy
on a playbook. When setting the strategy to free
, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.
It looks something like this (taken from the above link):
- hosts: all
strategy: free
tasks:
...
Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.
EDIT:
It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.
This includes specifying async
and poll
on a task. The following is taken from the 2nd link I mentioned:
- name: simulate long running op, allow to run for 45 sec, fire and forget
command: /bin/sleep 15
async: 45
poll: 0
I guess you can specify longer async
times if your task is lengthy. You can probably define your three concurrent task this way.
I need to call this method from a synchronously method.
It's possible with GenerateCodeAsync().Result
or GenerateCodeAsync().Wait()
, as the other answer suggests. This would block the current thread until GenerateCodeAsync
has completed.
However, your question is tagged with asp.net, and you also left the comment:
I was hoping for a simpler solution, thinking that asp.net handled this much easier than writing so many lines of code
My point is, you should not be blocking on an asynchronous method in ASP.NET. This will reduce the scalability of your web app, and may create a deadlock (when an await
continuation inside GenerateCodeAsync
is posted to AspNetSynchronizationContext
). Using Task.Run(...).Result
to offload something to a pool thread and then block will hurt the scalability even more, as it incurs +1 more thread to process a given HTTP request.
ASP.NET has built-in support for asynchronous methods, either through asynchronous controllers (in ASP.NET MVC and Web API) or directly via AsyncManager
and PageAsyncTask
in classic ASP.NET. You should use it. For more details, check this answer.
os.path.exists(path) Returns True if path refers to an existing path. An existing path can be regular files (http://en.wikipedia.org/wiki/Unix_file_types#Regular_file), but also special files (e.g. a directory). So in essence this function returns true if the path provided exists in the filesystem in whatever form (notwithstanding a few exceptions such as broken symlinks).
os.path.isdir(path) in turn will only return true when the path points to a directory
Where are you allocating memory for your buffer
? The line where you invoke bzero
invokes undefined behavior since buffer does not point to any valid region of memory.
char *buffer = new char[ BUFFER_SIZE ];
// do processing
// don't forget to release
delete[] buffer;
merge
is used to bring two (or more) branches together.
a little example:
# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"
# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"
# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"
so now there are three separate branches (namely A B and C) with different heads
to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:
# create an octopus merge
$ git merge B C
your history will then look something like this:
…-o-o-x-------A
|\ /|
| B---/ |
\ /
C---/
if you want to merge across repository/computer borders, have a look at git pull
command, e.g. from the pc with branch A (this example will create two new commits):
# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C
I solved it:
temp fix
$(document).on('click', "#buttonStarter", function(evt)
{
var context = new AudioContext();
document.getElementById('audioPlayer').play();
$("#buttonStarter").hide()
$("#Game").show()
});
Or use a custom player to trigger play http://zohararad.github.io/audio5js/
Note : Autoplay will be renabled in 31 December
$product->get_categories()
is deprecated since version 3.0! Use wc_get_product_category_list
instead.
https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt
project of ours. We needed a newer version of connect, since 2.7.3
. was causing trouble for us. So I created a file named npm-shrinkwrap.json
:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
npm
should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
Consider just downloading the file with permanent link and gdown
preinstalled like here
Using history.listen
For example like below:
In your component,
componentWillMount() {
this.props.history.listen(() => {
// Detecting, user has changed URL
console.info(this.props.history.location.pathname);
});
}
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions
variable
or
foreach($questions as &$question){
Adding the &
will keep the $questions
updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach
documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
babel-preset-es2015
is now deprecated and you'll get a warning if you try to use Laurence's solution.
To get this working with Babel 6.24.1+, use babel-preset-env
instead:
npm install babel-preset-env --save-dev
Then add env
to your presets in your .babelrc
:
{
"presets": ["env"]
}
See the Babel docs for more info.
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
You can use setenv.bat or .sh to pass the environment variables to the Tomcat.
Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.
On Windows:
set APP_MASTER_PASSWORD=foo
On Unix like systems:
export APP_MASTER_PASSWORD=foo
You are using
$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests
If 'requests' is a json file then you have to change this to
$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests.json
Now before this, if your json file is not indexed, you have to insert an index line before each line inside the json file. You can do this with JQ. Refer below link: http://kevinmarsh.com/2014/10/23/using-jq-to-import-json-into-elasticsearch.html
Go to elasticsearch tutorials (example the shakespeare tutorial) and download the json file sample used and have a look at it. In front of each json object (each individual line) there is an index line. This is what you are looking for after using the jq command. This format is mandatory to use the bulk API, plain json files wont work.
Here's a cool ASP.NET Web control called Multi-Select List Field at http://www.xnodesystems.com/. It's capable of:
(1) Multi-select; (2) Auto-complete; (3) Validation.
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
I guess the main question tries to figure out: "when should I use one or the other", or "which should I use", or "Am I using the right one"?
I guess the important point is atan only was intended to feed positive values in a right-upwards direction curve like for time-distance vectors. Cero is always at the bottom left, and thigs can only go up and right, just slower or faster. atan doesn't return negative numbers, so you can't trace things in the 4 directions on a screen just by adding/subtracting its result.
atan2 is intended for the origin to be in the middle, and things can go backwards or down. That's what you'd use in a screen representation, because it DOES matter what direction you want the curve to go. So atan2 can give you negative numbers, because its cero is in the center, and its result is something you can use to trace things in 4 directions.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
\d
means 'digit'. +
means, '1 or more times'. So \d+
means one or more digit. It will match 12
and 1
.
I'm developing with android studio 2+.
to create class diagrams I did the following: - install "ObjectAid UML Explorer" as plugin for eclipse(in my case luna with android sdk but works with younger versions as well) ... go to eclipse marketplace and search for "ObjectAid UML Explorer". it's further down in the search results. after installation and restart of eclipse ...
open an empty android or what-ever-java-project in eclipse. then right click on the empty eclipse project in the project explorer -> select 'build path' then I link my ANDROID STUDIO SRC PATH into my eclipse android project. doesn't matter if there are errors. again right click on the eclipse-android project and select: New in the filter type 'class' then you should see among others an option 'class diagram' ... select it and confgure it ... png stuff, visibility, etc. drag/drop your ANDROID STUDIO project classes into the open diagram -> voila :)
hth
I open eclipse(luna, but that doesn't matter).
I got the "ObjectAid UML Explorer"
that installed I open an empty android project oin eclipse, right
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
For me it was because I hadn't set an active
class on any of the slides.
DECLARE @String NVARCHAR(MAX);
USE Databse Name;
SELECT @String
=
(
SELECT 'ALTER INDEX [' + dbindexes.[name] + '] ON [' + db.name + '].[' + dbschemas.[name] + '].[' + dbtables.[name]
+ '] REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);' + CHAR(10) AS [text()]
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables
ON dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas
ON dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes
ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
INNER JOIN sys.databases AS db
ON db.database_id = indexstats.database_id
WHERE dbindexes.name IS NOT NULL
AND indexstats.database_id = DB_ID()
AND indexstats.avg_fragmentation_in_percent >= 10
ORDER BY indexstats.page_count DESC
FOR XML PATH('')
);
EXEC (@String);
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.
To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.
It depends on what the span is for. If it refers to the text of the link, and not the fact that it is a link, choose #1. If the span refers to the link as a whole, then choose #2. Unless you explain what the span represents, there's not much more of an answer than that. They're both inline elements, can be syntactically nested in any order.
See X-Frame-Options header on error response
You can simply add following line to .htaccess
Header always unset X-Frame-Options
Yet another possibility not yet mentioned here is to use NumPy tile:
a = numpy.tile(numpy.nan, (3, 3))
Also gives
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I don't know about speed comparison.
Another possibility would be to use pidof
it usually comes with most distributions. It will return you the PID of a given process by using it's name.
pidof process_name
This way you could store that information in a variable and execute kill -9
on it.
#!/bin/bash
pid=`pidof process_name`
kill -9 $pid
Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.
We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.
We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.
When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.
Came across this looking for something else.
While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}"
where # is the starting number of the array element we want to preserve forward:
#!/bin/bash
someVar="${1}"
someOtherVar="${2}"
set -- "${@:3}"
input=${@}
[[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"
echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"
Basically, the set -- "${@:3}"
just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.
Run this SQL:
select * from v$version;
And you'll get a result like:
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Try this CSS code for cross-browser compatibility.
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
This happens if you forgot to change your build settings to Simulator
. Unless you want to build to a device, in which case you should see the other answers.
Update: Check out the jQuery Pointer Events Polyfill project which allows you to bind to "pointer" events instead of choosing between mouse & touch.
Bind to both, but make a flag so the function only fires once per 100ms or so.
var flag = false;
$thing.bind('touchstart click', function(){
if (!flag) {
flag = true;
setTimeout(function(){ flag = false; }, 100);
// do something
}
return false
});