Try this code:
WebElement userName = pathfinderdriver.switchTo().activeElement();
userName.sendKeys(Keys.TAB);
To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
For the sake of completeness, here is an alternative emphasizing that REQUEST_URI
starts with a slash (at least in .htaccess
files):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it
Just don't use %{REQUEST_URI} (.*)/$
. Because in the root directory REQUEST_URI
equals /
, the leading slash, and it would be misinterpreted as a trailing slash.
If you are interested in more reading:
(update: this technique is now implemented in Laravel 5.5)
It doesn't work because you didn't attach the ScrollPane to the JFrame.
Also, you don't need 2 JScrollPanes:
JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");
JScrollPane scroll = new JScrollPane (textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scroll);
frame.setVisible (true);
You could use:
line.Replace(@"\", "");
or
line.Replace(@"\", string.Empty);
this is useful for me:
CREATE FUNCTION dbo.TRIM(@String VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END
GO
.
The most important difference is this:
In case of persist
method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)
But in case of merge
method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)
I had this as a faulty error message:
git pull
worked fine on the cmd line
git pull
failed in a Perl CGI process (a webhook to auto-deploy from github) with the above error.
Doing a git status
identified a clashing file. Sorting it fixed the problem.
Problem reoccurred later when I changed some config settings.
This time, setting $HOME and $USER env vars fixed it (are unset by default in a CGI process)
I had this same issue but with open jdk and none of the answers here helped. The trouble was that the mvn script was appending /bin/java at the end of JAVA home while trying to run java commands.
The solution for me was to manually edit the /usr/local/apache-maven/apache-maven-3.3.9/bin/mvn script (your own script might be installed differently; just run which mvn) and change
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
To
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME"
fi
else
JAVACMD="`which java`"
fi
fi
I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000
You might want to check out this page: http://pajhome.org.uk/crypt/md5/
However, if protecting the password is important, you should really be using something like SHA256 (MD5 is not cryptographically secure iirc). Even more, you might want to consider using TLS and getting a cert so you can use https.
You can use CountIf
. Put the following code in B1 and drag down the whole column
=COUNTIF(A:A,A1)
It will look like this:
If you're using PostgreSQL you can use DISTINCT ON
to find the first row in a group.
SELECT customer.*, purchase.*
FROM customer
JOIN (
SELECT DISTINCT ON (customer_id) *
FROM purchase
ORDER BY customer_id, date DESC
) purchase ON purchase.customer_id = customer.id
Note that the DISTINCT ON
field(s) -- here customer_id
-- must match the left most field(s) in the ORDER BY
clause.
Caveat: This is a nonstandard clause.
Your code has no problem. It does print the way you want. Alternatively, you can do this:
printf("%04x",a);
libcurl also provides CURLOPT_COOKIELIST which extracts all known cookies. All you need is to make sure the PHP/CURL binding can use it.
There's a much better way to add conditional validation rules in MVC3; have your model inherit IValidatableObject
and implement the Validate
method:
public class Person : IValidatableObject
{
public string Name { get; set; }
public bool IsSenior { get; set; }
public Senior Senior { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (IsSenior && string.IsNullOrEmpty(Senior.Description))
yield return new ValidationResult("Description must be supplied.");
}
}
Read more at Introducing ASP.NET MVC 3 (Preview 1).
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
}
}, 100);
Since at least version 0.16 of pandas, it does not take the parameter "rows"
As of 0.23, the solution would be:
df2.pivot_table(values='X', index='Y', columns='Z', aggfunc=pd.Series.nunique)
which returns:
Z Z1 Z2 Z3
Y
Y1 1.0 1.0 NaN
Y2 NaN NaN 1.0
With the Material Components Library you can use the MaterialShapeDrawable
.
With a TextView
:
<TextView
android:id="@+id/textview"
../>
You can programmatically apply a MaterialShapeDrawable
:
float radius = getResources().getDimension(R.dimen.corner_radius);
TextView textView = findViewById(R.id.textview);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.build();
MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
ViewCompat.setBackground(textView,shapeDrawable);
If you want to change the background color and the border just apply:
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.....));
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color....));
You had the identity
node as a child of authentication
node. That was the issue. As in the example above, authentication
and identity
nodes must be children of the system.web
node
The flags, or parameters that you can use with IFRAME and OBJECT embeds are documented here; the details about which parameter works with what player are also clearly mentioned:
YouTube Embedded Players and Player Parameters
You will notice that autoplay
is supported by all players (AS3, AS2 and HTML5).
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
function Double round2(Double val) {
return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}
Note the toString()!!!!
This is because BigDecimal converts the exact binary form of the double!!!
These are the various suggested methods and their fail cases.
// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d
Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val)
// By default use half even, works if you change mode to half_up
Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;
You can use signals to control nginx.
According to documentation, you need to send HUP signal to nginx master process.
HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes
Check the documentation here: http://nginx.org/en/docs/control.html
You can send the HUP signal to nginx master process PID like this:
kill -HUP $( cat /var/run/nginx.pid )
The command above reads the nginx PID from /var/run/nginx.pid
. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid
but that can be overridden in config. Check your nginx.config
to see where it saves the PID.
Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):
openssl pkcs12 -in filename.pfx -out cert.pem -nodes
Extracts the private key form a PFX to a PEM file:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
Exports the certificate (includes the public key only):
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
Removes the password (paraphrase) from the extracted private key (optional):
openssl rsa -in key.pem -out server.key
Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)
To send the data:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;
/* ... set the parameters, read files, etc. IE:
pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/
byte[] buffer = encoding.GetBytes(pData.GetPostData());
oRequest.ContentLength = buffer.Length;
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();
The PostData class should look like:
public class PostData
{
// Change this if you need to, not necessary
public static string boundary = "AaB03x";
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine("--" + boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: application/octet-stream");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine("--" + boundary + "--");
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public PostDataParam(string name, string filename, string value, PostDataParamType type)
{
Name = name;
Value = value;
FileName = filename;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
In command line it's better to use REG tool rather than REGEDIT:
REG IMPORT yourfile.reg
REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:
> REG IMPORT missing_file.reg
ERROR: Error opening the file. There may be a disk or file system error.
> %windir%\System32\reg.exe /?
REG Operation [Parameter List]
Operation [ QUERY | ADD | DELETE | COPY |
SAVE | LOAD | UNLOAD | RESTORE |
COMPARE | EXPORT | IMPORT | FLAGS ]
Return Code: (Except for REG COMPARE)
0 - Successful
1 - Failed
For help on a specific operation type:
REG Operation /?
Examples:
REG QUERY /?
REG ADD /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG COMPARE /?
REG EXPORT /?
REG IMPORT /?
REG FLAGS /?
int main()
{
char d = 'd';
std::string y("Hello worl");
y += d;
y.push_back(d);
y.append(1, d); //appending the character 1 time
y.insert(y.end(), 1, d); //appending the character 1 time
y.resize(y.size()+1, d); //appending the character 1 time
y += std::string(1, d); //appending the character 1 time
}
Note that in all of these examples you could have used a character literal directly: y += 'd';
.
Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'};
didn't work, but char d[2] = { 'd'};
(note the array is size two) would have been worked roughly the same as const char* d = "d";
, and a string literal can be appended: y.append(d);
.
You might want to see this page:
http://blog.niklasottosson.com/?p=1914
I guess you can go something like this:
DEMO:http://jsfiddle.net/g9eL6768/2/
HTML:
<table id="mytable"><thead>
<tr>
<th id="sl">S.L.</th>
<th id="nm">name</th>
</tr>
....
JS:
// sortTable(f,n)
// f : 1 ascending order, -1 descending order
// n : n-th child(<td>) of <tr>
function sortTable(f,n){
var rows = $('#mytable tbody tr').get();
rows.sort(function(a, b) {
var A = getVal(a);
var B = getVal(b);
if(A < B) {
return -1*f;
}
if(A > B) {
return 1*f;
}
return 0;
});
function getVal(elm){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseInt(v,10);
}
return v;
}
$.each(rows, function(index, row) {
$('#mytable').children('tbody').append(row);
});
}
var f_sl = 1; // flag to toggle the sorting order
var f_nm = 1; // flag to toggle the sorting order
$("#sl").click(function(){
f_sl *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_sl,n);
});
$("#nm").click(function(){
f_nm *= -1; // toggle the sorting order
var n = $(this).prevAll().length;
sortTable(f_nm,n);
});
Hope this helps.
Use the group collection of the Match object, indexing it with the capturing group name, e.g.
foreach (Match m in mc){
MessageBox.Show(m.Groups["link"].Value);
}
First, understand what async/await is. It is a way for a single-threaded GUI application or an efficient server to run multiple "fibers" or "co-routines" or "lightweight threads" on a single thread.
If you are ok with using ordinary threads, then the Java equivalent is ExecutorService.submit
and Future.get
. This will block until the task completes, and return the result. Meanwhile, other threads can do work.
If you want the benefit of something like fibers, you need support in the container (I mean in the GUI event loop or in the server HTTP request handler), or by writing your own.
For example, Servlet 3.0 offers asynchronous processing. JavaFX offers javafx.concurrent.Task
. These don't have the elegance of language features, though. They work through ordinary callbacks.
Edit: As has been noted in the other answers, the standard actually guarantees that "the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)". So even if your platform did not store signed ints as two's complement, the behavior would be the same.
Apparently your signed integer -62 is stored in two's complement (Wikipedia) on your platform:
62 as a 32-bit integer written in binary is
0000 0000 0000 0000 0000 0000 0011 1110
To compute the two's complement (for storing -62), first invert all the bits
1111 1111 1111 1111 1111 1111 1100 0001
then add one
1111 1111 1111 1111 1111 1111 1100 0010
And if you interpret this as an unsigned 32-bit integer (as your computer will do if you cast it), you'll end up with 4294967234 :-)
Justin answer translated to code (works perfect for me):
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
int scale = 1;
while ((options.outWidth * options.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + options.outWidth + ",
orig-height: " + options.outHeight);
Bitmap resultBitmap = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
options = new BitmapFactory.Options();
options.inSampleSize = scale;
resultBitmap = BitmapFactory.decodeStream(in, null, options);
// resize to desired dimensions
int height = resultBitmap.getHeight();
int width = resultBitmap.getWidth();
Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(resultBitmap, (int) x,
(int) y, true);
resultBitmap.recycle();
resultBitmap = scaledBitmap;
System.gc();
} else {
resultBitmap = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +resultBitmap.getWidth() + ", height: " +
resultBitmap.getHeight());
return resultBitmap;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}
I want to handle passing multiple lists, integer values and strings.
Helpful link => How to pass a Bash variable to Python?
def main(args):
my_args = []
for arg in args:
if arg.startswith("[") and arg.endswith("]"):
arg = arg.replace("[", "").replace("]", "")
my_args.append(arg.split(","))
else:
my_args.append(arg)
print(my_args)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
Order is not important. If you want to pass a list just do as in between "["
and "]
and seperate them using a comma.
Then,
python test.py my_string 3 "[1,2]" "[3,4,5]"
Output => ['my_string', '3', ['1', '2'], ['3', '4', '5']]
, my_args
variable contains the arguments in order.
As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.
--EDIT--
Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/
It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.
I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
If you want the quick and dirty way and don't worry about XSS attack, use params.merge
to keep previous parameters. e.g.
<%= link_to 'Link', params.merge({:per_page => 20}) %>
see: https://stackoverflow.com/a/4174493/445908
Otherwise , check this answer: params.merge and cross site scripting
If you like to set the --no-cache-dir
option by default, you can put this into pip.conf:
[global]
no-cache-dir = false
Note 1: It's confusing, but to enable the no-cache-dir
option you actually have to set it to false
. Pretty silly if you ask me... but that's how it is. There is a github issue to fix this.
Note 2: The location of pip.conf
depends on your OS. See the documentation for more info.
It is as simple as this query shown below.
UPDATE
Table1 T1 join Table2 T2 on T1.id = T2.id
SET
T1.LastName='DR. XXXXXX',
T2.WAprrs='start,stop'
WHERE
T1.id = '010008'
var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();
bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
time = new Date().getTime();
window.location.reload(true);
}else{
time = new Date().getTime();
}
}
Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.
Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
For jQuery users: naspinski's jQuery link seems broken, but try this one: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
You get a free jQuery plugin tutorial as a bonus. :)
Since dates are converted to UNIX epoch (numbers), you can use Math.max/min to find those:
var maxDate = Math.max.apply(null, dates)
// convert back to date object
maxDate = new Date(maxDate)
(tested in chrome only, but should work in most browsers)
num = 1
def function_to_add_one(num):
num += 1
return num
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
#Final Output: 2
num = 1
def procedure_to_add_one():
global num
num += 1
return num
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
#Final Output: 6
function_to_add_one
is a function
procedure_to_add_one
is a procedure
Even if you run the function five times, every time it will return 2
If you run the procedure five times, at the end of fifth run it will give you 6.
DISCLAIMER: Obviously this is a hyper-simplified view of reality. This answer just gives a taste of "functions" as opposed to "procedures". Nothing more. Once you have tasted this superficial yet deeply penetrative intuition, start exploring the two paradigms, and you will start to see the difference quite clearly.
Helps my students, hope it helps you too.
Normally you can use None
, but you can also use objc.NULL
, e.g.
import objc
val = objc.NULL
Especially useful when working with C code in Python.
Also see: Python objc.NULL Examples
You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.
To perform a request with a cookie attached just do the following:
var requestify = require('requestify');
requestify.post('http://google.com', {}, {
cookies: {
sessionCookie: 'session-cookie-data'
}
});
An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html
import WConio
WConio.getch()
Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).
double sqrt(double x)
{
...
return x;
}
void other(void)
{
double two = sqrt(2.0);
}
Under my thesis, x is the parameter to sqrt()
and 2.0 is the argument.
The terms are often used at least somewhat interchangeably.
If anyone is seeking a VB option, this was based on Pavel's answer:
Public Shared Function ToBase(base10 As Long, Optional baseChars As String = "0123456789ABCDEFGHIJKLMNOPQRTSUVWXYZ") As String
If baseChars.Length < 2 Then Throw New ArgumentException("baseChars must be at least 2 chars long")
If base10 = 0 Then Return baseChars(0)
Dim isNegative = base10 < 0
Dim radix = baseChars.Length
Dim index As Integer = 64 'because it's how long a string will be if the basechars are 2 long (binary)
Dim chars(index) As Char '65 chars, 64 from above plus one for sign if it's negative
base10 = Math.Abs(base10)
While base10 > 0
chars(index) = baseChars(base10 Mod radix)
base10 \= radix
index -= 1
End While
If isNegative Then
chars(index) = "-"c
index -= 1
End If
Return New String(chars, index + 1, UBound(chars) - index)
End Function
The Java Language Specification, section 15.10, states:
An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).
and
The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:
HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];
Your version is clearly better :-)
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
You can use as follows
public ActionResult NewWindow()
{
return Content("<script>window.open('{url}','_blank')</script>");
}
Edit This will create a link with Edit after clicking on editing a function name as edit will be called.
In JavaScript strings can be either string primitive type or string objects. The following code shows the distinction:
var a: string = 'test'; // string literal
var b: String = new String('another test'); // string wrapper object
console.log(typeof a); // string
console.log(typeof b); // object
Your error:
Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
Is thrown by the TS compiler because you tried to assign the type string
to a string object type (created via new
keyword). The compiler is telling you that you should use the type string
only for strings primitive types and you can't use this type to describe string object types.
For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library.
The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages
directory).
Make sure to read: http://docs.python.org/using/cmdline.html#environment-variables
On Mac OSX 10.15, Even after installing gpg, i was getting gpg2 command not found
$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`
$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found
Instead, this worked for me
$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
I'm using the same approach, I suggest to write the singleton a little better:
public static MyApp getInstance() {
if (instance == null) {
synchronized (MyApp.class) {
if (instance == null) {
instance = new MyApp ();
}
}
}
return instance;
}
but I'm not using everywhere, I use getContext()
and getApplicationContext()
where I can do it!
It's hard to say without seeing the rest of your CSS, but try adding !important
in front of the border color, to make it like so:
#refundReasonMenu #nav li:last-child
{
border-bottom: 1px solid #b5b5b5 !important;
}
How about something like this?
<div id="leftContainer">
<span>Company Name</span>
<br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
<span>Contact Name</span>
<br><input type="text" value="Timothy Patten">
</div>
Then, you can align the 2 divs by floating them left and right:-
#leftContainer {
float:left;
}
#rightContainer {
float:right;
}
video/mp4
should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4
. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4
.
Also, as a server, you should try to include the codecs
or profiles
parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.
I found in Linux kernel source code that PF_INET and AF_INET are the same. The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.
/* Protocol families, same as address families. */
...
#define PF_INET AF_INET
In my case I have two activities. In the second activity I forgot to put super on the onCreate method.
super.onCreate(savedInstanceState);
You are doing 157/32
which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...)
isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.
Convert a
and b
to a double, and you can use the division and Math.ceil
as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.
int n = (int) Math.ceil((double) a / b));
int n = a / b + ((a % b == 0) ? 0 : 1);
You do a / b
with always floor if a
and b
are both integers. Then you have an inline if-statement witch checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0
checks for the remainder.
This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0
.
int n = (a + b - 1) / b;
To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0
and b < 1
.
int n = (a - 1) / b + 1;
Since dividing two integer in Java (and most other programming languages) will always floor the result. So:
int a, b;
int result = a/b (is the same as floor(a/b) )
But we don't want floor(a/b)
, but ceil(a/b)
, and using the definitions and plots from Wikipedia:
With these plots of the floor and ceil function you can see the relationship.
You can see that floor(x) <= ceil(x)
. We need floor(x + s) = ceil(x)
. So we need to find s
. If we take 1/2 <= s < 1
it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1
, so
ceil(a/b) = floor(a/b + s)
= floor(a/b + (b-1)/b)
= floor( (a+b-1)/b) )
This is not a real proof, but I hope your are satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.
If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
needs name of string and its length will zero all characters other methods might stop at the first zero they encounter
void strClear(char p[],u8 len){u8 i=0;
if(len){while(i<len){p[i]=0;i++;}}
}
var ValuetoReturn = (from Rows in YourDataTable.AsEnumerable()
select Rows["ColumnName"]).Distinct().ToList();
Looks like TaskCache registry data is in ...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache
... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() {
var form_original_data = $("#myform").serialize();
$("#mybutton").click(function() {
if ($("#myform").serialize() != form_original_data) {
// Something changed
}
});
});
You can use mosquitto_sub
(which is part of the mosquitto-clients
package) and subscribe to the wildcard topic #
:
mosquitto_sub -v -h broker_ip -p 1883 -t '#'
I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:
/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before
invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
* @param format the format string
* @param arguments a list of 3 or more arguments
*/
public void debug(String format, Object... arguments);
src/sample/images/shopp.png
**
Parent root =new StackPane();
ImageView imageView=new ImageView(new Image(getClass().getResourceAsStream("images/shopp.png")));
((StackPane) root).getChildren().add(imageView);
**
Try this:
$("button").click(function () {
$(this).parents("div:first").html(...);
});
The best way to achieve this is to turn off default line separators, subclass UITableViewCell
and add a custom line separator as a subview of the contentView
- see below a custom cell that is used to present an object of type SNStock
that has two string properties, ticker
and name
:
import UIKit
private let kSNStockCellCellHeight: CGFloat = 65.0
private let kSNStockCellCellLineSeparatorHorizontalPaddingRatio: CGFloat = 0.03
private let kSNStockCellCellLineSeparatorBackgroundColorAlpha: CGFloat = 0.3
private let kSNStockCellCellLineSeparatorHeight: CGFloat = 1
class SNStockCell: UITableViewCell {
private let primaryTextColor: UIColor
private let secondaryTextColor: UIColor
private let customLineSeparatorView: UIView
var showsCustomLineSeparator: Bool {
get {
return !customLineSeparatorView.hidden
}
set(showsCustomLineSeparator) {
customLineSeparatorView.hidden = !showsCustomLineSeparator
}
}
var customLineSeparatorColor: UIColor? {
get {
return customLineSeparatorView.backgroundColor
}
set(customLineSeparatorColor) {
customLineSeparatorView.backgroundColor = customLineSeparatorColor?.colorWithAlphaComponent(kSNStockCellCellLineSeparatorBackgroundColorAlpha)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(reuseIdentifier: String, primaryTextColor: UIColor, secondaryTextColor: UIColor) {
self.primaryTextColor = primaryTextColor
self.secondaryTextColor = secondaryTextColor
self.customLineSeparatorView = UIView(frame:CGRectZero)
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier:reuseIdentifier)
selectionStyle = UITableViewCellSelectionStyle.None
backgroundColor = UIColor.clearColor()
contentView.addSubview(customLineSeparatorView)
customLineSeparatorView.hidden = true
}
override func prepareForReuse() {
super.prepareForReuse()
self.showsCustomLineSeparator = false
}
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
layoutCustomLineSeparator()
}
private func layoutCustomLineSeparator() {
let horizontalPadding: CGFloat = bounds.width * kSNStockCellCellLineSeparatorHorizontalPaddingRatio
let lineSeparatorWidth: CGFloat = bounds.width - horizontalPadding * 2;
customLineSeparatorView.frame = CGRectMake(horizontalPadding,
kSNStockCellCellHeight - kSNStockCellCellLineSeparatorHeight,
lineSeparatorWidth,
kSNStockCellCellLineSeparatorHeight)
}
// MARK: Public Class API
class func cellHeight() -> CGFloat {
return kSNStockCellCellHeight
}
// MARK: Public API
func configureWithStock(stock: SNStock) {
textLabel!.text = stock.ticker as String
textLabel!.textColor = primaryTextColor
detailTextLabel!.text = stock.name as String
detailTextLabel!.textColor = secondaryTextColor
setNeedsLayout()
}
}
To disable the default line separator use, tableView.separatorStyle = UITableViewCellSeparatorStyle.None;
. The consumer side is relatively simple, see example below:
private func stockCell(tableView: UITableView, indexPath:NSIndexPath) -> UITableViewCell {
var cell : SNStockCell? = tableView.dequeueReusableCellWithIdentifier(stockCellReuseIdentifier) as? SNStockCell
if (cell == nil) {
cell = SNStockCell(reuseIdentifier:stockCellReuseIdentifier, primaryTextColor:primaryTextColor, secondaryTextColor:secondaryTextColor)
}
cell!.configureWithStock(stockAtIndexPath(indexPath))
cell!.showsCustomLineSeparator = true
cell!.customLineSeparatorColor = tintColor
return cell!
}
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
Make sure you are not using "PATH" as a variable, which will override the existing PATH for environment variables.
user regular function to define the pattern to replace and then use replace function to work on input string,
var i = new RegExp('"{','g'),
j = new RegExp('}"','g'),
k = data.replace(i,'{').replace(j,'}');
For me , it was related to setting the "User Setting.xml" inside
Window > preferences > Maven > User Settings > and then browsing to the user Settings inside the { maven unarchived directory / }/apache-maven-2.2.1/conf/settings.xml .
Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:
public static bool IsValidJson<T>(this string strInput)
{
if(string.IsNullOrWhiteSpace(strInput)) return false;
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JsonConvert.DeserializeObject<T>(strInput);
return true;
}
catch // not valid
{
return false;
}
}
else
{
return false;
}
}
These are generally the scenarios where colon ':' is used in JavaScript
1- Declaring and Initializing an Object
var Car = {model:"2015", color:"blue"}; //car object with model and color properties
2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)
List:
while(counter < 50)
{
userInput += userInput;
counter++;
if(userInput > 10000)
{
break List;
}
}
3- In Switch Statement
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
4- In Ternary Operator
document.getElementById("demo").innerHTML = age>18? "True" : "False";
I think you can do this:
var client = new HttpClient();
HttpContent content = new Widget();
client.PostAsync<Widget>("http://localhost:44268/api/test", content, new FormUrlEncodedMediaTypeFormatter())
.ContinueWith((postTask) => { postTask.Result.EnsureSuccessStatusCode(); });
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
You could just do something like this:
SELECT *
FROM foo
WHERE (@param = 0 AND MyColumn IS NULL)
OR (@param = 1 AND MyColumn IS NOT NULL)
OR (@param = 2)
Something like that.
If you store an object in session state, that object must be serializable.
edit:
In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.
You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:
JTable table = new JTable(my_rows, my_header);
for (int c = 0; c < table.getColumnCount(); c++)
{
Class<?> col_class = table.getColumnClass(c);
table.setDefaultEditor(col_class, null); // remove editor
}
Without editors, data will be not editable.
In practice, there are two differences:
cout
in C++ or printf
in C): unsigned integer bit representation is interpreted as a nonnegative integer by print functions.this code can identify the integer using ordering criterion:
char a = 0;
a--;
if (0 < a)
printf("unsigned");
else
printf("signed");
char
is considered signed
in some compilers and unsigned
in other compilers. The code above determines which one is considered in a compiler, using the ordering criterion. If a
is unsigned, after a--
, it will be greater than 0
, but if it is signed
it will be less than zero. But in both cases, the bit representation of a
is the same. That is, in both cases a--
does the same change to the bit representation.
If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.
In store.js
:
export const state = () => ({
isClosed: false
})
export const mutations = {
closeWindow(state, payload) {
state.isClosed = payload
}
}
In this scenario, I am creating a boolean
state property that I am going to change in different places in the application like so:
this.$store.commit('closeWindow', true)
Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted
hook:
mounted() {
this.$store.watch(
state => state.isClosed,
(value) => {
if (value) { this.localProperty = 'edit' }
}
)
}
Firstly, I am setting a watcher on the state property and then in the callback function I use the value
of that property to change the localProperty
.
I hope it helps!
In more explanation for n. 'pronouns' m.
's answer,
Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.
There is the flow of Encryption:
+---------------------+ +--------------------+
| | | |
| generate random key | | the large file |
| (R) | | (F) |
| | | |
+--------+--------+---+ +----------+---------+
| | |
| +------------------+ |
| | |
v v v
+--------+------------+ +--------+--+------------+
| | | |
| encrypt (R) with | | encrypt (F) |
| your RSA public key | | with symmetric key (R) |
| | | |
| ASym(PublicKey, R) | | EF = Sym(F, R) |
| | | |
+----------+----------+ +------------+-----------+
| |
+------------+ +--------------+
| |
v v
+--------------+-+---------------+
| |
| send this files to the peer |
| |
| ASym(PublicKey, R) + EF |
| |
+--------------------------------+
And the flow of Decryption:
+----------------+ +--------------------+
| | | |
| EF = Sym(F, R) | | ASym(PublicKey, R) |
| | | |
+-----+----------+ +---------+----------+
| |
| |
| v
| +-------------------------+-----------------+
| | |
| | restore key (R) |
| | |
| | R <= ASym(PrivateKey, ASym(PublicKey, R)) |
| | |
| +---------------------+---------------------+
| |
v v
+---+-------------------------+---+
| |
| restore the file (F) |
| |
| F <= Sym(Sym(F, R), R) |
| |
+---------------------------------+
Besides, you can use this commands:
# generate random symmetric key
openssl rand -base64 32 > /config/key.bin
# encryption
openssl rsautl -encrypt -pubin -inkey /config/public_key.pem -in /config/key.bin -out /config/key.bin.enc
openssl aes-256-cbc -a -pbkdf2 -salt -in $file_name -out $file_name.enc -k $(cat /config/key.bin)
# now you can send this files: $file_name.enc + /config/key.bin.enc
# decryption
openssl rsautl -decrypt -inkey /config/private_key.pem -in /config/key.bin.enc -out /config/key.bin
openssl aes-256-cbc -d -a -in $file_name.enc -out $file_name -k $(cat /config/key.bin)
$date = new DateTime(date("Y-m-d"));
$date->modify('+7 day');
$tomorrowDATE = $date->format('Y-m-d');
You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>
There's an ongoing effort for a PDCurses port:
You need to put the text-align:center
on the containing div, not on the input itself.
VisualVM can show clear states of threads of a given JVM process
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
There is always the easy way.
import numpy as np
print(np.matrix(A))
This helps to find PID using port number.
lsof -i tcp:port_number
If the image cannot be loaded (for example, because it is not present at the supplied URL), image URL will be changed into default,
For more about .error()
$('img').on('error', function (e) {_x000D_
$(this).attr('src', 'broken.png');_x000D_
});
_x000D_
One more way to do it using the shell (bash or ksh, doesn't work with dash):
echo $((16#FF))
255
if (a % 2 == 0) {
} else {
}
I have that problem and my solution is going source folder and run command line: mvn clean install -DskipTests eclipse:eclipse then return eclipse workspace and refresh project. Hope that help!
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.
i m adding some line that copy in your project for complete working of Pratt answer.
<receiver
android:name=".DeviceAdminDemo"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
put this code in onReceive of DeviceAdminDemo
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
context.stopService(new Intent(context, TService.class));
Intent myIntent = new Intent(context, TService.class);
context.startService(myIntent);
}
You can use the /s
switch for del
to delete in subfolders as well.
Example
del D:\test\*.* /s
Would delete all files under test including all files in all subfolders.
To remove folders use rd
, same switch applies.
rd D:\test\folder /s /q
rd
doesn't support wildcards *
though so if you want to recursively delete all subfolders under the test
directory you can use a for
loop.
for /r /d D:\test %a in (*) do rd %a /s /q
If you are using the for
option in a batch file remember to use 2 %
's instead of 1.
d = {}
# import list of year,value pairs
for year,value in mylist:
try:
d[year].append(value)
except KeyError:
d[year] = [value]
The Python way - it is easier to receive forgiveness than ask permission!
Install Aptana plugin to your Eclipse installation.
It has built-in FTP support, and it works excellently.
You can:
As a matter of fact the FTP support is so good I'm using Aptana (or Eclipse + Aptana) now for all my FTP needs. Plus I get syntax highlighting/whatever coding support there is. Granted, Eclipse is not the speediest app to launch, but it doesn't bug me so much.
Alternately, if you are using a Macro Enabled workbook:
Add any control at all from the Developer -> Insert (Probably a button)
When it asks what Macro to assign, choose New. For the code for the generated module enter something like:
Thisworkbook.Sheets("Sheet Name").Activate
However, if you are not using Macros in your work book. Ooo's approach is definitely surperior as hyperlinks will work with no need to trust the document.
This answer uses MS SQL Server 2008 (I don't have access to MS SQL Server 2000), but the way I see it according to the OP are 3 situations to take into consideration. From what I've tried no answer here covers all 3 of them:
0
The function I came up with takes 2 parameters:
@String NVARCHAR(MAX)
: The string to be searched
@FindString NVARCHAR(MAX)
: Either a single character or a sub-string to get the last
index of in @String
It returns an INT
that is either the positive index of @FindString
in @String
or 0
meaning that @FindString
is not in @String
Here's an explanation of what the function does:
@ReturnVal
to 0
indicating that @FindString
is not in @String
@FindString
in @String
by using CHARINDEX()
@FindString
in @String
is 0
, @ReturnVal
is left as 0
@FindString
in @String
is > 0
, @FindString
is in @String
so
it calculates the last index of @FindString
in @String
by using REVERSE()
@ReturnVal
which is either a positive number that is the last index of
@FindString
in @String
or 0
indicating that @FindString
is not in @String
Here's the create function script (copy and paste ready):
CREATE FUNCTION [dbo].[fn_LastIndexOf]
(@String NVARCHAR(MAX)
, @FindString NVARCHAR(MAX))
RETURNS INT
AS
BEGIN
DECLARE @ReturnVal INT = 0
IF CHARINDEX(@FindString,@String) > 0
SET @ReturnVal = (SELECT LEN(@String) -
(CHARINDEX(REVERSE(@FindString),REVERSE(@String)) +
LEN(@FindString)) + 2)
RETURN @ReturnVal
END
Here's a little bit that conveniently tests the function:
DECLARE @TestString NVARCHAR(MAX) = 'My_sub2_Super_sub_Long_sub1_String_sub_With_sub_Long_sub_Words_sub2_'
, @TestFindString NVARCHAR(MAX) = 'sub'
SELECT dbo.fn_LastIndexOf(@TestString,@TestFindString)
I have only run this on MS SQL Server 2008 because I don't have access to any other version but from what I've looked into this should be good for 2008+ at least.
Enjoy.
DateTime is capable of storing only two distinct times, the local time and UTC. The Kind property indicates which.
DateTimeOffset expands on this by being able to store local times from anywhere in the world. It also stores the offset between that local time and UTC. Note how DateTime cannot do this unless you'd add an extra member to your class to store that UTC offset. Or only ever work with UTC. Which in itself is a fine idea btw.
I am assuming that test.html is a static file.To render static files use the static middleware like so.
app.use(express.static(path.join(__dirname, 'public')));
This tells express to look for static files in the public directory of the application.
Once you have specified this simply point your browser to the location of the file and it should display.
If however you want to render the views then you have to use the appropriate renderer for it.The list of renderes is defined in consolidate.Once you have decided which library to use just install it.I use mustache so here is a snippet of my config file
var engines = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
What this does is tell express to
look for files to render in views directory
Render the files using mustache
The extension of the file is .html(you can use .mustache too)
There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.
Currently repos and projects refer to a different kinds of entities that have separate APIs:
Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.
The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.
The term that is usually unambiguous is "project board".
The first endpoint in the documentation of the Projects API:
is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:
{
"message": "Projects are disabled for this repo",
"documentation_url": "https://developer.github.com/v3"
}
which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.
There are some other interesting endpoints:
POST /repos/:owner/:repo/projects
POST /orgs/:org/projects
but there is no:
POST /users/:user/projects
Which leads us to another difference:
1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations
or, more importantly:
1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users
See also:
I know it's confusing. I tried to explain it as precisely as I could.
Using while and a counter:
count = 1
while count <= 3: # try 3 times
try:
# do_the_logic()
break
except SomeSpecificException as e:
# If trying 3rd time and still error??
# Just throw the error- we don't have anything to hide :)
if count == 3:
raise
count += 1
If you are using System.Web.Script.Serialization
in the .NET framework you can put a ScriptIgnore
attribute on the members that shouldn't be serialized. See the example taken from here:
Consider the following (simplified) case:
public class User { public int Id { get; set; } public string Name { get; set; } [ScriptIgnore] public bool IsComplete { get { return Id > 0 && !string.IsNullOrEmpty(Name); } } }
In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:
{ Id: 3, Name: 'Test User' }
PS. Don't forget to add a reference to "System.Web.Extensions
" for this to work
Catch the base exception 'Exception'
try {
//some code
} catch (Exception e) {
//catches exception and all subclasses
}
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.
Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)
This worked for me:
NSTimer *switchTo = [NSTimer scheduledTimerWithTimeInterval:0.1
target:selfselector:@selector(switchToTimer)userInfo:nil repeats:NO];
- (void) switchToTimer {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"MyViewControllerID"]; // Storyboard ID
[self presentViewController:vc animated:FALSE completion:nil];
}
I see this question so much! everywhere I look lacks the real answer.
The php.ini should be in the wp-admin directory, if it isn't just create it and then define whats needed, by default it should contain.
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
try this
<div ng-app="myApp" ng-controller="customersCtrl">
<div ng-include="'myTable.htm'"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.names = response.data.records;
});
});
</script>
Similarly, I experienced this: Port 443 in use by "Unable to open process" with PID 6012! When starting XAMPP Control Panel v3.2.1 for the first time.
In Task Manager I found that PID 6012 was Apache web server. A copy of it was running in the background without the GUI, and when I invoked the GUI it was trying to start another copy. Killed the phantom copy and then XAMPP started up fine.
I didn't have to change any port settings.
Just simply 'export' variable and 'import' in your class
export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';
// default err string message
export var errStringMsg = 'Something went wrong';
Now use it as,
import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);
For elementwise multiplication of matrix
objects, you can use numpy.multiply
:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)
Result
array([[ 5, 12],
[21, 32]])
However, you should really use array
instead of matrix
. matrix
objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use *
for elementwise multiplication:
a * b
If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @
does matrix multiplication now:
a @ b # matrix multiplication
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({
stop: function(event, ui) {
alert("New position: " + ui.item.index());
}
});
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
So, I tested above themes and found out none of them are showing proper color combination when using Productivity Power Tools in Visual Studio.
Ultimately, being a fan of dark themes, I created one myself which is fully supported from VS2005 to VS2013.
Here's the screenshot
Download this dark theme from here: Obsidian Meets Visual Studio
To use this theme go to Tools -> Import and Export Setting... -> import selected environment settings -> (optional to save current settings) -> Browse select and then Finish.
Now only I came across this situation and found some more interesting features around GROUP_CONCAT
. I hope these details will make you feel interesting.
simple GROUP_CONCAT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT and ORDER BY
SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC)
FROM Tasks;
Result:
+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+
GROUP_CONCAT with DISTINCT and SEPARATOR
SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')
FROM Tasks;
Result:
+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+
GROUP_CONCAT and Combining Columns
SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')
FROM Tasks;
Result:
+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+
GROUP_CONCAT and Grouped Results
Assume that the following are the results before using GROUP_CONCAT
+------------------------+--------------------------+
| ArtistName | AlbumName |
+------------------------+--------------------------+
| Iron Maiden | Powerslave |
| AC/DC | Powerage |
| Jim Reeves | Singing Down the Lane |
| Devin Townsend | Ziltoid the Omniscient |
| Devin Townsend | Casualties of Cool |
| Devin Townsend | Epicloud |
| Iron Maiden | Somewhere in Time |
| Iron Maiden | Piece of Mind |
| Iron Maiden | Killers |
| Iron Maiden | No Prayer for the Dying |
| The Script | No Sound Without Silence |
| Buddy Rich | Big Swing Face |
| Michael Learns to Rock | Blue Night |
| Michael Learns to Rock | Eternity |
| Michael Learns to Rock | Scandinavia |
| Tom Jones | Long Lost Suitcase |
| Tom Jones | Praise and Blame |
| Tom Jones | Along Came Jones |
| Allan Holdsworth | All Night Wrong |
| Allan Holdsworth | The Sixteen Men of Tain |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;
Result:
+------------------------+----------------------------------------------------------------------------+
| ArtistName | GROUP_CONCAT(al.AlbumName) |
+------------------------+----------------------------------------------------------------------------+
| AC/DC | Powerage |
| Allan Holdsworth | All Night Wrong,The Sixteen Men of Tain |
| Buddy Rich | Big Swing Face |
| Devin Townsend | Epicloud,Ziltoid the Omniscient,Casualties of Cool |
| Iron Maiden | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves | Singing Down the Lane |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night |
| The Script | No Sound Without Silence |
| Tom Jones | Long Lost Suitcase,Praise and Blame,Along Came Jones |
+------------------------+----------------------------------------------------------------------------+
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
Handy one liner to parse a CSV file into an array
$csv = array_map('str_getcsv', file('data.csv'));
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
The database must have a name (example DB1), try this one:
OracleConnection con = new OracleConnection("data source=DB1;user id=fastecit;password=fastecit");
In case the TNS is not defined you can also try this one:
OracleConnection con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=DB1)));
User Id=fastecit;Password=fastecit");
For everyone with Ionic: Updating to the latest @ionic/app-scripts version gave a better error message.
npm install @ionic/app-scripts@latest --save-dev
It was a wrong path for styleUrls in a component to a non-existing file. Strangely it gave no error in development.
If you use this, check man sudo
too:
#!/bin/bash
sudo echo "Hi, I'm root"
sudo -u nobody echo "I'm nobody"
sudo -u 1000 touch /test_user
There are a lot of ways to do so, for example:
in case you have not pushed the commit publicly yet:
git reset HEAD~1 --soft
That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man
In case you did push publicly (on a branch called 'master'):
git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )
revert commit normally and push
git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master
now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit
option:
git revert --no-commit 86b48ba (hash of the revert commit).
I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master
If you have learned C++
, you must be familiar with function object
or functor
, means any object that can be called as if it is a function
.
In C++, an ordinary function
is a function object, and so is a function pointer; more generally, so is an object of a class that defines operator()
. In C++11 and greater, the lambda expression
is the functor
too.
Similarity, in Python, those functors
are all callable
. An ordinary function
can be callable, a lambda expression
can be callable, a functional.partial
can be callable, the instances of class with a __call__() method
can be callable.
Ok, go back to question : I have a variable, x, and I want to know whether it is pointing to a function or not.
If you want to judge weather the object acts like a function, then the
callable
method suggested by@John Feminella
is ok.If you want to
judge whether a object is just an ordinary function or not
( not a callable class instance, or a lambda expression), then thextypes.XXX
suggested by@Ryan
is a better choice.
#!/usr/bin/python3
# 2017.12.10 14:25:01 CST
# 2017.12.10 15:54:19 CST
import functools
import types
import pprint
Define a class and an ordinary function.
class A():
def __call__(self, a,b):
print(a,b)
def func1(self, a, b):
print("[classfunction]:", a, b)
@classmethod
def func2(cls, a,b):
print("[classmethod]:", a, b)
@staticmethod
def func3(a,b):
print("[staticmethod]:", a, b)
def func(a,b):
print("[function]", a,b)
Define the functors:
#(1.1) built-in function
builtins_func = open
#(1.2) ordinary function
ordinary_func = func
#(1.3) lambda expression
lambda_func = lambda a : func(a,4)
#(1.4) functools.partial
partial_func = functools.partial(func, b=4)
#(2.1) callable class instance
class_callable_instance = A()
#(2.2) ordinary class function
class_ordinary_func = A.func1
#(2.3) bound class method
class_bound_method = A.func2
#(2.4) static class method
class_static_func = A.func3
Define the functors' list and the types' list:
## list of functors
xfuncs = [builtins_func, ordinary_func, lambda_func, partial_func, class_callable_instance, class_ordinary_func, class_bound_method, class_static_func]
## list of type
xtypes = [types.BuiltinFunctionType, types.FunctionType, types.MethodType, types.LambdaType, functools.partial]
Judge wether the functor is callable. As you can see, they all are callable.
res = [callable(xfunc) for xfunc in xfuncs]
print("functors callable:")
print(res)
"""
functors callable:
[True, True, True, True, True, True, True, True]
"""
Judge the functor's type( types.XXX). Then the types of functors are not all the same.
res = [[isinstance(xfunc, xtype) for xtype in xtypes] for xfunc in xfuncs]
## output the result
print("functors' types")
for (row, xfunc) in zip(res, xfuncs):
print(row, xfunc)
"""
functors' types
[True, False, False, False, False] <built-in function open>
[False, True, False, True, False] <function func at 0x7f1b5203e048>
[False, True, False, True, False] <function <lambda> at 0x7f1b5081fd08>
[False, False, False, False, True] functools.partial(<function func at 0x7f1b5203e048>, b=4)
[False, False, False, False, False] <__main__.A object at 0x7f1b50870cc0>
[False, True, False, True, False] <function A.func1 at 0x7f1b5081fb70>
[False, False, True, False, False] <bound method A.func2 of <class '__main__.A'>>
[False, True, False, True, False] <function A.func3 at 0x7f1b5081fc80>
"""
Then you can choose the functors' types that suitable.
such as:
def func(a,b):
print("[function]", a,b)
>>> callable(func)
True
>>> isinstance(func, types.FunctionType)
True
>>> isinstance(func, (types.BuiltinFunctionType, types.FunctionType, functools.partial))
True
>>>
>>> isinstance(func, (types.MethodType, functools.partial))
False
My best answer for this is to simply use format painter. This might be a bit of a pain, but it works rather well as the problem you are facing is that Gridlines are covered by fill and other effects that are layered on top. Imagine putting a piece of white paper on top of your grid, the grid lines are present underneath, but they just don't show.
So try:
From my experience this is the easiest way to do this quickly. Especially when pasting things in and out of excel.
Again this is not the programmatic way of solving this problem.
Select the text.
Right Click.
Plugin Commands -> Copy Text with Syntax Highlighting
Paste it into Word or whatever.
For macOS I use two commands together to show information about the processes listening on the machine and process connecting to remote servers. In other words, to check the listening ports and the current (TCP) connections on a host you could use the two following commands together
1. netstat -p tcp -p udp
2. lsof -n -i4TCP -i4UDP
Thought I would add my input, hopefully it can end up helping someone.
If you can live with limited parallel capablilities, the following solution will work:
private static <T> Stream<T> nonEmptyStream(
Stream<T> stream, Supplier<RuntimeException> e) {
Spliterator<T> it=stream.spliterator();
return StreamSupport.stream(new Spliterator<T>() {
boolean seen;
public boolean tryAdvance(Consumer<? super T> action) {
boolean r=it.tryAdvance(action);
if(!seen && !r) throw e.get();
seen=true;
return r;
}
public Spliterator<T> trySplit() { return null; }
public long estimateSize() { return it.estimateSize(); }
public int characteristics() { return it.characteristics(); }
}, false);
}
Here is some example code using it:
List<String> l=Arrays.asList("hello", "world");
nonEmptyStream(l.stream(), ()->new RuntimeException("No strings available"))
.forEach(System.out::println);
nonEmptyStream(l.stream().filter(s->s.startsWith("x")),
()->new RuntimeException("No strings available"))
.forEach(System.out::println);
The problem with (efficient) parallel execution is that supporting splitting of the Spliterator
requires a thread-safe way to notice whether either of the fragments has seen any value in a thread-safe manner. Then the last of the fragments executing tryAdvance
has to realize that it is the last one (and it also couldn’t advance) to throw the appropriate exception. So I didn’t add support for splitting here.
Why does redirect_to(:back)
not work for you, why is it a no go?
redirect_to(:back)
works like a charm for me. It's just a short cut for
redirect_to(request.env['HTTP_REFERER'])
http://apidock.com/rails/ActionController/Base/redirect_to (pre Rails 3) or http://apidock.com/rails/ActionController/Redirecting/redirect_to (Rails 3)
Please note that redirect_to(:back)
is being deprecated in Rails 5. You can use
redirect_back(fallback_location: 'something')
instead (see http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)
Read strfrtime from the official docs.
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example
public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
}}
above example == is a reference comparison i.e. both objects point to the same memory location
String equals() is evaluates to the comparison of values in the objects.
public class EqualsExample1{
public static void main(String args[]){
String s = "Hell";
String s1 =new string( "Hello");
String s2 =new string( "Hello");
s1.equals(s2); //true
s.equals(s1) ; //false
}}
above example It compares the content of the strings. It will return true if string matches, else returns false.
First, use git log
to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash
. After you are done, git checkout original_branch
. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.
.blackBox {_x000D_
width: 100%;_x000D_
height: 200px;_x000D_
background-color: #000;_x000D_
position: relative;_x000D_
color: cyan;_x000D_
padding: 20px;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.blackBox::before {_x000D_
position: absolute;_x000D_
border: 1px dotted #fff;_x000D_
left: 10px;_x000D_
right: 10px;_x000D_
top: 10px;_x000D_
bottom: 10px;_x000D_
content: "";_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="blackBox">Created an inner border box. <br> Working fine all major browsers.</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
I think your best shot is a border-left
property that is assigned to each one of the li
s except the first one (You would have to give the first one a class named first
and explicitly remove the border for that).
Even if you are generating the <li>
programmatically, assigning a first
class should be easy.
The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?
Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)
TimeZone timeZone = TimeZone.getDefault();
timeZone.getID();
It will print like
Asia/Kolkata
The safest way to pass commands to psql
in a script is by piping a string or passing a here-doc.
The man docs for the -c/--command
option goes into more detail when it should be avoided.
-c command
--command=command
Specifies that psql is to execute one command string, command, and then exit. This is useful in shell scripts. Start-up files (psqlrc and ~/.psqlrc)
are ignored with this option.
command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single
backslash command. Thus you cannot mix SQL and psql meta-commands with this option. To achieve that, you could pipe the string into psql, for
example: echo '\x \\ SELECT * FROM foo;' | psql. (\\ is the separator meta-command.)
If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands
included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psql's standard
input. Also, only the result of the last SQL command is returned.
Because of these legacy behaviors, putting more than one command in the -c string often has unexpected results. It's better to feed multiple
commands to psql's standard input, either using echo as illustrated above, or via a shell here-document, for example:
psql <<EOF
\x
SELECT * FROM foo;
EOF
Here's a less flexible alternative using unset():
$array = array(
1 => 'one',
2 => 'two',
3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
unset($array[$key]);
}
The result of print_r($array)
being:
Array
(
[2] => two
)
This is not applicable if you want to keep the filtered values for later use but tidier, if you're certain that you don't.
Although this question is old, it is still asked by many who use MSYS2.
I started to use it this year to replace CygWin, and I'm getting pretty satisfied.
To install make
, open the MSYS2 shell and type the following commands:
# Update the package database and core system packages
pacman -Syu
# Close shell and open again if needed
# Update again
pacman -Su
# Install make
pacman -S make
# Test it (show version)
make -v
In your current code, what Dictionary.update()
does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.
If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list
as a list and then append case
to it (instead of update) .
Example -
case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)
Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1
or entry2
, etc and the value being the corresponding dictionary for that entry.
case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.
you can use webview in android that will use chrome browser Or you can try Phonegap or sencha Touch
class Item{
bool IsNullOrZero{ get{return ((this.Rate ?? 0) == 0);}}
}
Or you can cast your string to Date format with date function. Even the date is stored as TEXT in the DB. Like this (the most workable variant):
SELECT * FROM test WHERE date(date)
BETWEEN date('2011-01-11') AND date('2011-8-11')
If it is the first element, i.e. $array[0]
, you can try:
echo key($array);
If it is the second element, i.e. $array[1]
, you can try:
next($array);
echo key($array);
I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.
You might consider Joda Time or Java 8, which has a type called LocalTime
specifically for a time of day without a date component.
Example code in Joda-Time 2.7/Java 8.
LocalTime t = LocalTime.parse( "17:40" ) ;
Either way, when the using block is exited (either by successful completion or by error) it is closed.
Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
try
{
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
catch (Exception)
{
/*Handle error*/
}
}
I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.
Install express
npm install express
Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server
Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');
// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
app.listen(8000);
console.log('Listening on port 8000');
After you've saved server.js, you can run the server using:
node server.js
http://localhost:8000/FILENAME
and you should see the HTML file you were trying to load#decorator.py
def makeHtmlTag(tag, *args, **kwds):
def real_decorator(fn):
css_class = " class='{0}'".format(kwds["css_class"]) \
if "css_class" in kwds else ""
def wrapped(*args, **kwds):
return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
return wrapped
# return decorator dont call it
return real_decorator
@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
return "hello world"
print hello()
You can also write decorator in Class
#class.py
class makeHtmlTagClass(object):
def __init__(self, tag, css_class=""):
self._tag = tag
self._css_class = " class='{0}'".format(css_class) \
if css_class != "" else ""
def __call__(self, fn):
def wrapped(*args, **kwargs):
return "<" + self._tag + self._css_class+">" \
+ fn(*args, **kwargs) + "</" + self._tag + ">"
return wrapped
@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
return "Hello, {}".format(name)
print hello("Your name")
One method is to query syscolumns:
select
syscolumns.name as [Column],
syscolumns.xusertype as [Type],
sysobjects.xtype as [Objtype]
from
sysobjects
inner join
syscolumns on sysobjects.id = syscolumns.id
where sysobjects.xtype = 'u'
and sysobjects.name = 'MyTableName'
order by syscolumns.name
def reverse_lines(filename):
y=open(filename).readlines()
return y[::-1]
Note:
This answer just covers the timing differences between
await
in series andPromise.all
. Be sure to read @mikep's comprehensive answer that also covers the more important differences in error handling.
For the purposes of this answer I will be using some example methods:
res(ms)
is a function that takes an integer of milliseconds and returns a promise that resolves after that many milliseconds.rej(ms)
is a function that takes an integer of milliseconds and returns a promise that rejects after that many milliseconds.Calling res
starts the timer. Using Promise.all
to wait for a handful of delays will resolve after all the delays have finished, but remember they execute at the same time:
const data = await Promise.all([res(3000), res(2000), res(1000)])
// ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
// delay 1 delay 2 delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O delay 2
// =========O delay 3
//
// =============================O Promise.all
async function example() {
const start = Date.now()
let i = 0
function res(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
const data = await Promise.all([res(3000), res(2000), res(1000)])
console.log(`Promise.all finished`, Date.now() - start)
}
example()
_x000D_
This means that Promise.all
will resolve with the data from the inner promises after 3 seconds.
But, Promise.all
has a "fail fast" behavior:
const data = await Promise.all([res(3000), res(2000), rej(1000)])
// ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^
// delay 1 delay 2 delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O delay 2
// =========X delay 3
//
// =========X Promise.all
async function example() {
const start = Date.now()
let i = 0
function res(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
function rej(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
reject()
console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
try {
const data = await Promise.all([res(3000), res(2000), rej(1000)])
} catch (error) {
console.log(`Promise.all finished`, Date.now() - start)
}
}
example()
_x000D_
If you use async-await
instead, you will have to wait for each promise to resolve sequentially, which may not be as efficient:
const delay1 = res(3000)
const delay2 = res(2000)
const delay3 = rej(1000)
const data1 = await delay1
const data2 = await delay2
const data3 = await delay3
// ms ------1---------2---------3
// =============================O delay 1
// ===================O delay 2
// =========X delay 3
//
// =============================X await
async function example() {
const start = Date.now()
let i = 0
function res(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
function rej(n) {
const id = ++i
return new Promise((resolve, reject) => {
setTimeout(() => {
reject()
console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
}, n)
})
}
try {
const delay1 = res(3000)
const delay2 = res(2000)
const delay3 = rej(1000)
const data1 = await delay1
const data2 = await delay2
const data3 = await delay3
} catch (error) {
console.log(`await finished`, Date.now() - start)
}
}
example()
_x000D_
The Web Security team at Mozilla put together a great guide, which we abide by in the development of our sites and services.
when you define the class A, in A.h, you explicitely say that the class has a member B.
You MUST include "B.h" in "A.h"
Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
Configure webpack
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
}
WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.
Let's trace a series of messages flowing back and forth:
Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.
Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.
Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.
Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.
WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.
For large datasets, it is memory efficient to read only selected rows via the skiprows
parameter.
Example
pred = lambda x: x not in [1, 3]
pd.read_csv("data.csv", skiprows=pred, index_col=0, names=...)
This will now return a DataFrame from a file that skips all rows except 1 and 3.
Details
From the docs:
skiprows
: list-like or integer or callable, defaultNone
...
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be
lambda x: x in [0, 2]
This feature works in version pandas 0.20.0+. See also the corresponding issue and a related post.
Use a Macro.
Macro>Start Recording
Use the keyboard to make your changes in a repeatable manner e.g.
home>type "able">end>down arrow>home
Then go back to the menu and click stop recording then run a macro multiple times.
That should do it and no regex based complications!
UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.
It doesn't feel nice, but you can just put the new lines in the html. Like this:
<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
1 Long St
London
Postcode
UK"></textarea>
_x000D_
Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:
http://jsfiddle.net/01taylop/HDfju/
resize: none;
in the css so that the size of the textarea is fixed (See jsfiddle).Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!
Check out the JSFiddle.
box-sizing
and display: block
properties on the textarea are important or the div behind it will not be the same size.resize: vertical
and a min-height
on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize
property will cause issues when expanding the textarea horizontally.HTML:
<form>
<input type='text' placeholder='First Name' />
<input type='text' placeholder='Last Name' />
<div class='textarea-placeholder'>
<textarea></textarea>
<div>
First Line
<br /> Second Line
<br /> Third Line
</div>
</div>
</form>
SCSS:
$input-padding: 4px;
@mixin input-font() {
font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
font-size: 12px;
font-weight: 300;
line-height: 16px;
}
@mixin placeholder-style() {
color: #999;
@include input-font();
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
form {
width: 250px;
}
input,textarea {
display: block;
width: 100%;
padding: $input-padding;
border: 1px solid #ccc;
}
input {
margin-bottom: 10px;
background-color: #fff;
@include input-font();
}
textarea {
min-height: 80px;
resize: vertical;
background-color: transparent;
&.data-edits {
background-color: #fff;
}
}
.textarea-placeholder {
position: relative;
> div {
position: absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: $input-padding;
background-color: #fff;
@include placeholder-style();
}
}
::-webkit-input-placeholder {
@include placeholder-style();
}
:-moz-placeholder {
@include placeholder-style();
}
::-moz-placeholder {
@include placeholder-style();
}
:-ms-input-placeholder {
@include placeholder-style();
}
Javascript:
$("textarea").on('change keyup paste', function() {
var length = $(this).val().length;
if (length > 0) {
$(this).addClass('data-edits');
} else {
$(this).removeClass('data-edits');
}
});
Check out this blog post here that talks about the same thing. From what I gather, the extra time might have to do with walking up the scope chain.
You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy
This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.
A nice kotlin solution, using the latest cross-platform answer mentioned by lakshman sai...
No unnecessary Uri.toString and the Uri.parse though, this answer clean and minimal:
val intentUri = Uri.Builder().apply {
scheme("https")
authority("www.google.com")
appendPath("maps")
appendPath("dir")
appendPath("")
appendQueryParameter("api", "1")
appendQueryParameter("destination", "${yourLocation.latitude},${yourLocation.longitude}")
}.build()
startActivity(Intent(Intent.ACTION_VIEW).apply {
data = intentUri
})
Update 2016: seems to be working again.
Update August 2014: No longer works as of recent Chrome versions.
Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.
chrome://extensions
.user.js
file into that page.Voila. You can also drag files from the downloads footer bar to the extensions tab.
Chrome will automatically create a manifest.json
file in the extensions directory that Brock documented.
<3 Freedom.
In case your app needs to work on files (what you would normally expect to pass as: ./myApp *.jpg
), you would do it like this:
open *.jpg -a myApp
Can you try the following?
psexec \\server cmd /c "echo . | powershell script.ps1"
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
No, there is no build in function in python to do this, because simply:
set(A)- set(subset_of_A)
will provide you the answer.
I searched for this very question and when I saw the answers I ended up creating something different (because I favor less code over most other things most of the time) that should work in the vast majority of cases. Basically turn the array into a string with array elements separated by some delimiter character, and then wrap the search value in the delimiter character and pass through instr.
Function is_in_array(value As String, test_array) As Boolean
If Not (IsArray(test_array)) Then Exit Function
If InStr(1, "'" & Join(test_array, "'") & "'", "'" & value & "'") > 0 _
Then is_in_array = True
End Function
And you'd execute the function like this:
test = is_in_array(1, array(1, 2, 3))
You will get it by tag type="date"...then it will render beautiful calendar and all...
@Html.TextBoxFor(model => model.EndTime, new { type = "date" })
I'm assuming you're using express
, given the logs you have in your question. The key is to set the timeout
property on server (the following sets the timeout to one second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;
If you're not using express and are only working with vanilla node, the principle is the same. The following will not return data:
var http = require('http');
var server = http.createServer(function (req, res) {
setTimeout(function() {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}, 200);
}).listen(1337, '127.0.0.1');
server.timeout = 20;
console.log('Server running at http://127.0.0.1:1337/');
A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:
#globals.py
class dbinfo : # for database globals
username = 'abcd'
password = 'xyz'
class runtime :
debug = False
output = 'stdio'
Then, if you have two code files c1.py and c2.py, both can have at the top
import globals as gl
Now all code can access and set values, as such:
gl.runtime.debug = False
print(gl.dbinfo.username)
People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.
By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.
This lacks some of the clever error checking of other approaches, but is simple and easy to follow.
In my situation Adobe was using the same port. After stopping the Adobe Creative Cloud Desktop process, VS functioned as expected.
I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.
-- *****************************************************************************
-- test_PVreplace
DROP FUNCTION IF EXISTS test_PVreplace;
delimiter //
CREATE FUNCTION test_PVreplace (
str TEXT, -- String to do search'n'replace on
pv TEXT -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
)
RETURNS TEXT
-- Replace specific tags with specific values.
sproc:BEGIN
DECLARE idx INT;
DECLARE idx0 INT DEFAULT 1; -- 1-origined, not 0-origined
DECLARE len INT;
DECLARE sPV TEXT;
DECLARE iPV INT;
DECLARE sP TEXT;
DECLARE sV TEXT;
-- P/V string *must* end with a delimiter.
IF (RIGHT (pv, 1) <> '|') THEN
SET pv = CONCAT (pv, '|');
END IF;
-- Find all the P/V pairs.
SELECT LOCATE ('|', pv, idx0) INTO idx;
WHILE (idx > 0) DO
SET len = idx - idx0;
SELECT SUBSTRING(pv, idx0, len) INTO sPV;
-- Found a P/V pair. Break it up.
SELECT LOCATE ('=', sPV) INTO iPV;
IF (iPV = 0) THEN
SET sP = sPV;
SET sV = '';
ELSE
SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
SELECT SUBSTRING(sPV, iPV+1) INTO sV;
END IF;
-- Do the substitution(s).
SELECT REPLACE (str, sP, sV) INTO str;
-- Do next P/V pair.
SET idx0 = idx + 1;
SELECT LOCATE ('|', pv, idx0) INTO idx;
END WHILE;
RETURN (str);
END//
delimiter ;
SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');
If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.
Set both DATE_FORMAT
and USE_L10N
To make changes for the entire site in Django 1.4.1 add:
DATE_FORMAT = "Y-m-d"
to your settings.py
file and edit:
USE_L10N = False
since l10n overrides DATE_FORMAT
This is documented at: https://docs.djangoproject.com/en/dev/ref/settings/#date-format
I've made a category from @Abizern answer
@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
NSError *error;
NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
return (!json ? nil : json);
}
@end
Use it like this,
NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);
Use six module to make you code compatible between python2 and python3
urllib.request.urlopen("<your-url>")```
You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.
There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").
POSTing to the login form
Form posts are easy to simulate, it's just a case of formatting your post data as follows:
field1=value1&field2=value2
Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
Here's an example of what you should see in the Set-cookie header for your login form:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
GETting the page behind the login form
Now you can perform your GET request to a page that you need to be logged in for.
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
EDIT:
If you need to view the results of the first POST, you can recover the HTML it returned with:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Place this directly below cookieHeader = resp.Headers["Set-cookie"];
and then inspect the string held in pageSource.
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
I would like to stress that, even if there are situations where if expr :
isn't sufficient because one wants to make sure expr
is True
and not just different from 0
/None
/whatever, is
is to be prefered from ==
for the same reason S.Lott mentionned for avoiding == None
.
It is indeed slightly more efficient and, cherry on the cake, more human readable.
In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
When you just want to execute one or several HTTP requests without having to wait for the response, there is a simple PHP solution, as well.
In the calling script:
$socketcon = fsockopen($host, 80, $errno, $errstr, 10);
if($socketcon) {
$socketdata = "GET $remote_house/script.php?parameters=... HTTP 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socketcon, $socketdata);
fclose($socketcon);
}
// repeat this with different parameters as often as you like
On the called script.php, you can invoke these PHP functions in the first lines:
ignore_user_abort(true);
set_time_limit(0);
This causes the script to continue running without time limit when the HTTP connection is closed.
a simple hack with the first answer
var getLocation = function(href=window.location.href) {
var l = document.createElement("a");
l.href = href;
return l;
};
this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname
I found out that the image that you are specify with the og:image, has to actually be present in the HTML page inside an image tag.
the thumbnail appeared for me only after i added an image tag for the image. it was commented out. but worked.