I'd say it depends upon the size of your project... Personnally, I would use Maven for simple projects that need straightforward compiling, packaging and deployment. As soon as you need to do some more complicated things (many dependencies, creating mapping files...), I would switch to Ant...
Easy! Just use jQuery's click function:
$("#theElement").click();
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
For a lambda-avoiding method, first define your own function:
def MyFn(a):
return a[1]
then:
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=MyFn)
We can use IF condition in SELECT query as below:
Suppose that for anything with "ABC","ABC1","ABC2","ABC3",..., we want to replace with "ABC" then using REGEXP and IF() condition in the SELECT query, we can achieve this.
Syntax:
SELECT IF(column_name REGEXP 'ABC[0-9]$','ABC',column_name)
FROM table1
WHERE column_name LIKE 'ABC%';
Example:
SELECT IF('ABC1' REGEXP 'ABC[0-9]$','ABC','ABC1');
Right click on the project
->Run As
--> Run configurations
.
Then select Maven Build
Then click new button to create a configuration of the selected type. Click on Browse workspace
(now is Workspace...
) then select your project and in goals specify eclipse:eclipse
You want:
git rm --cached [file]
If you omit the --cached
option, it will also delete it from the working tree. git rm
is slightly safer than git reset
, because you'll be warned if the staged content doesn't match either the tip of the branch or the file on disk. (If it doesn't, you have to add --force
.)
How about programmatically modifying the size attribute on the input?
Semantically (imo), this solution is better than the accepted solution because it still uses input fields for user input but it does introduce a little bit of jQuery. Soundcloud does something similar to this for their tagging.
<input size="1" />
$('input').on('keydown', function(evt) {
var $this = $(this),
size = parseInt($this.attr('size'), 10),
isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
(evt.which >= 48 && evt.which <= 57) || // 0-9
evt.which === 32;
if ( evt.which === 8 && size > 0 ) {
// backspace
$this.attr('size', size - 1);
} else if ( isValidKey ) {
// all other keystrokes
$this.attr('size', size + 1);
}
});
Setting the tz
attribute of the index explicitly seems to work:
ts_utc = ts.tz_convert("UTC")
ts_utc.index.tz = None
Cookies:
Local Storage:
For completely transparent color, use:
rbga(255,255,255,0)
A little more visible:
rbga(255,255,255,.3)
Shift + Control + I opens the Developer tool window. From bottom-left second image (that looks like the following) will open/hide the console for you:
There's nothing wrong with include file in head. It seems you forgot to add;
. Please try this one:
<body onload="imageRefreshBig();">
But as per my knowledge semicolons are optional. You can try with ;
but better debug code and see if chrome console gives any error.
I hope this helps.
To delimit by a tab you can use the sep
argument of to_csv
:
df.to_csv(file_name, sep='\t')
To use a specific encoding (e.g. 'utf-8') use the encoding
argument:
df.to_csv(file_name, sep='\t', encoding='utf-8')
USE master
GO
xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc'
GO
[Identify Port used by Named Instance of SQL Server Database Engine by Reading SQL Server Error Logs]
I have found out when running a PS1 file for a Mapped drive to Dropbox that I'm always getting this error. When opening up properties for the PS1 there is no "Unblock".
The only thing that work for me is
powershell.exe -executionpolicy bypass -file .\Script.ps1
I upgraded my docker this afternoon and ran into the same problem. I tried restarting docker but no luck.
Finally, I had to restart my computer and it worked. Definitely a bug.
Pandas uses numpy
's NaN value. Use numpy.isnan
to obtain a Boolean vector from a pandas series.
A thing you have to understand first: you have no files.
A file is a subject of a filesystem, but you are making your request using HTTP protocol which supports no files but URLs.
So, you have to request an unexisting file using your browser and see the response code. if it's not 404, you are unable to use any wrappers to see if a file exists and you have to request your cdn using some other protocol, FTP for example
Donal had the right solution for me. However, the updated plist
name for 2017 is
com.oracle.oss.mysql.mysqld.plist.
Do something like this:
<script>
function changeColor(id)
{
document.getElementById(id).style.color = "#ff0000"; // forecolor
document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>
<div id="myid">Hello There !!</div>
<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
For string to int conversion.
db.my_collection.find().forEach( function(obj) {
obj.my_value= new NumberInt(obj.my_value);
db.my_collection.save(obj);
});
For string to double conversion.
obj.my_value= parseInt(obj.my_value, 10);
For float:
obj.my_value= parseFloat(obj.my_value);
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
The error message could result due to the following reason:
Please follow the steps mentioned below to resolve the issue:
Method 1:
Method 2: 1. Run System File Checker. Refer to the link mentioned below for additional information: http://support.microsoft.com/kb/929833
Your TextView Attributes need to be something like,
<TextView ...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right" ../>
Now, Description why these need to be done,
android:layout_width="match_parent"
android:layout_height="match_parent"
Makes your TextView to match_parent
or fill_parent
if You don't want to be it like, match_parent
you have to give some specified values to layout_height
so it get space for vertical center gravity. android:layout_width="match_parent"
necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.
Now, its about android:gravity
which makes the content of Your TextView alignment. android:layout_gravity
makes alignment of TextView respected to its Parent Layout.
Update:
As below comment says use fill_parent
instead of match_parent
. (Problem in some device.)
This is how Flatten works converting Matrix to single array.
CSS relates to visual styling and not behaviour, so the answer is no really.
You could however either use javascript to modify the behaviour or change the styling of the span in question so that it doesn't have the pointy finger, underline, etc. Styling it like that will still leave it clickable.
Even better, change your markup so that it reflects what you want it to do.
My code is as follows:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here, and if you have to refresh UI put this code:
runOnUiThread(new Runnable() {
public void run() {
//your code
}
});
}
},
5000
);
The dot syntax works in JavaScript, but not in Python.
del df['column_name']
del df['column_name']
or del df.column_name
I had tried many ways from replies in this topic, mostly works but got some side-effect like if I use overflow-x on body,html
it might slow/freeze the page when users scroll down on mobile.
use position: fixed
on wrapper/div inside the body is good too, but when I have a menu and use Javascript click animated scroll to some section, It's not working.
So, I decided to use touch-action: pan-y pinch-zoom
on wrapper/div inside the body. Problem solved.
if you're using SQL Server,
dateadd(DAY,0, datediff(day,0, created))
will return the day created
for example, if the sale created on '2009-11-02 06:12:55.000',
dateadd(DAY,0, datediff(day,0, created))
return '2009-11-02 00:00:00.000'
select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))
Is there a problem with this formulation?
I don't see any.
Is there a better way?
I'd collapse the two statements into one:
const Colors = Object.freeze({
RED: Symbol("red"),
BLUE: Symbol("blue"),
GREEN: Symbol("green")
});
If you don't like the boilerplate, like the repeated Symbol
calls, you can of course also write a helper function makeEnum
that creates the same thing from a list of names.
How can we read data from a text file and store in a String Variable?
Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.
Is it possible to pass the filename in a method and it would return the String which is the text from the file.
Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.
I wrote a small lib for this. https://www.npmjs.com/package/@inf3rno/promise.exposed
I used the factory method approach others wrote, but I overrode the then
, catch
, finally
methods too, so you can resolve the original promise by those as well.
Resolving Promise without executor from outside:
const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");
Racing with the executor's setTimeout from outside:
const promise = Promise.exposed(function (resolve, reject){
setTimeout(function (){
resolve("I almost fell asleep.")
}, 100000);
}).then(console.log);
setTimeout(function (){
promise.resolve("I don't want to wait that much.");
}, 100);
There is a no-conflict mode if you don't want to pollute the global namespace:
const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const promise = createExposedPromise().then(console.log);
promise.resolve("This should show up in the console.");
I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public void run()
{
try
{
String text = "Hello World";
String key = "Bar12345Bar12345"; // 128 bit key
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b: encrypted) {
sb.append((char)b);
}
// the encrypted String
String enc = sb.toString();
System.out.println("encrypted:" + enc);
// now convert the string to byte array
// for decryption
byte[] bb = new byte[enc.length()];
for (int i=0; i<enc.length(); i++) {
bb[i] = (byte) enc.charAt(i);
}
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(bb));
System.err.println("decrypted:" + decrypted);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
StrongAES app = new StrongAES();
app.run();
}
}
using System.IO;
this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))
both should be quite easy to understand and use.
string pathToFile = "";//to save the location of the selected object
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(theDialog.FileName.ToString());
pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object
}
if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
{
//method1
string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();
//method2
string text = "";
using(StreamReader sr =new StreamReader(pathToFile))
{
text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
}
}
}
To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.
to add the data to your class you can use the constructor to add the data like:
public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
{
EmployeeNum = EMPLOYEENUM;
Name = NAME;
Address = ADRESS;
Wage = WAGE;
Hours = HOURS;
}
or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).
Currently VARCHAR behaves exactly the same as VARCHAR2. However, the type VARCHAR
should not be used as it is reserved for future usage.
Taken from: Difference Between CHAR, VARCHAR, VARCHAR2
=begin
My
multiline
comment
here
=end
@Entity @Table(name = "stock", catalog = "mkyongdb",
uniqueConstraints = @UniqueConstraint(columnNames =
"STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
class Stock implements java.io.Serializable {
}
Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique.
Magic: Unknown semantic
Symbolic Constant -> Provides both correct semantic and correct context for use
Semantic: The meaning or purpose of a thing.
"Create a constant, name it after the meaning, and replace the number with it." -- Martin Fowler
First, magic numbers are not just numbers. Any basic value can be "magic". Basic values are manifest entities such as integers, reals, doubles, floats, dates, strings, booleans, characters, and so on. The issue is not the data type, but the "magic" aspect of the value as it appears in our code text.
What do we mean by "magic"? To be precise: By "magic", we intend to point to the semantics (meaning or purpose) of the value in the context of our code; that it is unknown, unknowable, unclear, or confusing. This is the notion of "magic". A basic value is not magic when its semantic meaning or purpose-of-being-there is quickly and easily known, clear, and understood (not confusing) from the surround context without special helper words (e.g. symbolic constant).
Therefore, we identify magic numbers by measuring the ability of a code reader to know, be clear, and understand the meaning and purpose of a basic value from its surrounding context. The less known, less clear, and more confused the reader is, the more "magic" the basic value is.
We have two scenarios for our magic basic values. Only the second is of primary importance for programmers and code:
An overarching dependency of "magic" is how the lone basic value (e.g. number) has no commonly known semantic (like Pi), but has a locally known semantic (e.g. your program), which is not entirely clear from context or could be abused in good or bad context(s).
The semantics of most programming languages will not allow us to use lone basic values, except (perhaps) as data (i.e. tables of data). When we encounter "magic numbers", we generally do so in a context. Therefore, the answer to
"Do I replace this magic number with a symbolic constant?"
is:
"How quickly can you assess and understand the semantic meaning of the number (its purpose for being there) in its context?"
With this thought in mind, we can quickly see how a number like Pi (3.14159) is not a "magic number" when placed in proper context (e.g. 2 x 3.14159 x radius or 2*Pi*r). Here, the number 3.14159 is mentally recognized Pi without the symbolic constant identifier.
Still, we generally replace 3.14159 with a symbolic constant identifier like Pi because of the length and complexity of the number. The aspects of length and complexity of Pi (coupled with a need for accuracy) usually means the symbolic identifier or constant is less prone to error. Recognition of "Pi" as a name is a simply a convenient bonus, but is not the primary reason for having the constant.
Laying aside common constants like Pi, let's focus primarily on numbers with special meanings, but which those meanings are constrained to the universe of our software system. Such a number might be "2" (as a basic integer value).
If I use the number 2 by itself, my first question might be: What does "2" mean? The meaning of "2" by itself is unknown and unknowable without context, leaving its use unclear and confusing. Even though having just "2" in our software will not happen because of language semantics, we do want to see that "2" by itself carries no special semantics or obvious purpose being alone.
Let's put our lone "2" in a context of: padding := 2
, where the context is a "GUI Container". In this context the meaning of 2 (as pixels or other graphical unit) offers us a quick guess of its semantics (meaning and purpose). We might stop here and say that 2 is okay in this context and there is nothing else we need to know. However, perhaps in our software universe this is not the whole story. There is more to it, but "padding = 2" as a context cannot reveal it.
Let's further pretend that 2 as pixel padding in our program is of the "default_padding" variety throughout our system. Therefore, writing the instruction padding = 2
is not good enough. The notion of "default" is not revealed. Only when I write: padding = default_padding
as a context and then elsewhere: default_padding = 2
do I fully realize a better and fuller meaning (semantic and purpose) of 2 in our system.
The example above is pretty good because "2" by itself could be anything. Only when we limit the range and domain of understanding to "my program" where 2 is the default_padding
in the GUI UX parts of "my program", do we finally make sense of "2" in its proper context. Here "2" is a "magic" number, which is factored out to a symbolic constant default_padding
within the context of the GUI UX of "my program" in order to make it use as default_padding
quickly understood in the greater context of the enclosing code.
Thus, any basic value, whose meaning (semantic and purpose) cannot be sufficiently and quickly understood is a good candidate for a symbolic constant in the place of the basic value (e.g. magic number).
Numbers on a scale might have semantics as well. For example, pretend we are making a D&D game, where we have the notion of a monster. Our monster object has a feature called life_force
, which is an integer. The numbers have meanings that are not knowable or clear without words to supply meaning. Thus, we begin by arbitrarily saying:
From the symbolic constants above, we start to get a mental picture of the aliveness, deadness, and "undeadness" (and possible ramifications or consequences) for our monsters in our D&D game. Without these words (symbolic constants), we are left with just the numbers ranging from -10 .. 10
. Just the range without the words leaves us in a place of possibly great confusion and potentially with errors in our game if different parts of the game have dependencies on what that range of numbers means to various operations like attack_elves
or seek_magic_healing_potion
.
Therefore, when searching for and considering replacement of "magic numbers" we want to ask very purpose-filled questions about the numbers within the context of our software and even how the numbers interact semantically with each other.
Let's review what questions we ought to ask:
You might have a magic number if ...
Examine stand-alone manifest constant basic values in your code text. Ask each question slowly and thoughtfully about each instance of such a value. Consider the strength of your answer. Many times, the answer is not black and white, but has shades of misunderstood meaning and purpose, speed of learning, and speed of comprehension. There is also a need to see how it connects to the software machine around it.
In the end, the answer to replacement is answer the measure (in your mind) of the strength or weakness of the reader to make the connection (e.g. "get it"). The more quickly they understand meaning and purpose, the less "magic" you have.
CONCLUSION: Replace basic values with symbolic constants only when the magic is large enough to cause difficult to detect bugs arising from confusions.
SQLMenace's solution worked for me with a slight tweak to how data is deleted - DELETE FROM
instead of TRUNCATE
.
-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
-- enable referential integrity again
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'
GO
You can also use day names like Mon
for Monday, Tue
for Tuesday, etc. It's more human friendly.
The problem is you are not linking to the jQuery UI library (which is where datepicker resides):
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div><!-- End demo -->
</body>
</HTML>
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
print("Hello, World!")
You are probably using Python 3.0, where print
is now a function (hence the parenthesis) instead of a statement.
You can simply use Python standard library. Make a shallow copy of the original image as follows:
import copy
original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)
In case you are using RabbitMQ with Docker your steps should be:
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);
) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function
is a list of tf.Variable
objects, then the line session.run(init)
will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters
to use initial_parameters_of_hypothesis_function[i].initialized_value()
, which adds the necessary dependency:
parameters = []
for i in range(0, number_of_attributes, 1):
parameters.append(tf.Variable(
initial_parameters_of_hypothesis_function[i].initialized_value()))
You should be using things like: KeyEvent.VK_UP instead of the actual code.
How are you wanting to refactor it? What is the goal of the refactoring?
It can be as simple as:
default_data['item3'] = 3
As Chris' answer says, you can use update to add more than one item. An example:
default_data.update({'item4': 4, 'item5': 5})
Please see the documentation about dictionaries as data structures and dictionaries as built-in types.
Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:
we <- gsub(",", "", we) # remove comma
we <- as.numeric(we) # turn into numbers
and now you can do
hist(we)
and other numeric operations.
I implemented this extension method to get the description from enum values. It works for all kind of enums.
public static class EnumExtension
{
public static string ToDescription(this System.Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
}
To enhance Fabian's one-liner; let us say that we want to ignore only exit status 1 but to preserve the exit status if it is anything else:
tar -czf sample.tar.gz dir1 dir2 || ( export ret=$?; [[ $ret -eq 1 ]] || exit "$ret" )
This does everything sandeep's script does, on one line.
Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.
As an example on an SSL certificate for a web site the subject would be the domain name of the web site.
this is my approach from a simple blog:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
- See more at: http://www.programmingtunes.com/generation-of-prime-numbers-c/#sthash.YoWHqYcm.dpuf
In
int *ptr= l_matrix[0];
you can access like
*p
*(p+1)
*(p+2)
after all 2 dimensional arrays are also stored as 1-d.
I had the same issue after trying many combination I had this working note I have compatibility checked for intranet
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<head runat="server">
You can use echo and prefix "\033", simple:
Artisan::command('mycommand', function () {
echo "\033======== Start ========\n";
});
And change color text:
if (App::environment() === 'production') {
echo "\033[0;33m======== WARNING ========\033[0m\n";
}
I usually do it this way...
#include <string>
#include <vector>
int main( int argc, char* argv[] )
{
std::vector<char> vec;
//... do something with vec
std::string str(vec.begin(), vec.end());
//... do something with str
return 0;
}
Yet another possibility to check, it was my problem this time.
I had added the function to the library, and included the library's output folder in the search path.
But I also had a folder with an older version of the library listed before, so VS was using the old library, and of course not finding the new function.
Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-
When we mark a parameter as optional in the action uri using ?
character then we must provide default values to the parameters in the method signature as shown below:
MyMethod(string name = "someDefaultValue", int? Id = null)
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
TypeScript 2.0 has the readonly
modifier:
class MyClass {
readonly myReadOnlyProperty = 1;
myMethod() {
console.log(this.myReadOnlyProperty);
this.myReadOnlyProperty = 5; // error, readonly
}
}
new MyClass().myReadOnlyProperty = 5; // error, readonly
It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.
Alternative Solution
An alternative is to use the static
keyword with readonly
:
class MyClass {
static readonly myReadOnlyProperty = 1;
constructor() {
MyClass.myReadOnlyProperty = 5; // error, readonly
}
myMethod() {
console.log(MyClass.myReadOnlyProperty);
MyClass.myReadOnlyProperty = 5; // error, readonly
}
}
MyClass.myReadOnlyProperty = 5; // error, readonly
This has the benefit of not being assignable in the constructor and only existing in one place.
I had to add this line in the ConfigureServices in order to work.
services.AddSingleton<IOrderService, OrderService>();
Check something with echo
, print()
or printr()
in the include file, header.php
.
It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>
. This could also make a problem.
It will work.
long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
//?Creating a new row with the structure of the table:
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
//Giving values to the columns of the row(this row is supposed to have 28 columns):
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
Apache Commons IO Charsets class can come in handy:
String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())
Well I tried using
String converted = URLDecoder.decode("toconvert","UTF-8");
I hope this is what you were actually looking for?
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
These work for general strings (in case you do not want to output to file/console, but store for later use or something).
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
String streams
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
When writing HTML tests, the ENTER key is available as ${KEY_ENTER}
.
You can use it with sendKeys
, here is an example:
sendKeys | id=search | ${KEY_ENTER}
Mac Solution:
Added local ssh id_rsa key to vagrant private key
vi /Users//.vagrant/machines/default/virtualbox/private_key
/Users//.ssh/id_rsa
copied public key /Users//.ssh/id_rsa.pub on vagrant box authorized_keys
ssh vagrant@localhost -p 2222
(password: vagrant)
ls -la
cd .ssh
chmod 0600 ~/.ssh/authorized_keys
vagrant reload
Problem resolved.
Thanks to
I was experiencing this same problem. In my instance the send mail was timing out because my Exchange server was relaying email to a server on the internet. That server had exceeded it's bandwidth quota. Apparently php mailer has some built in timeout and it wasn't long enough to see the actual message.
Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings
or use:
tr '\r\n' ' '
both answers are is incorrect. it should read:
x-=r;
y-=r;
drawOval(x,y,r*2,r*2);
Try this
First_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddMonths(-1)
Last_Day_Of_Previous_Month = New Date(Today.Year, Today.Month, 1).AddDays(-1)
<form name="input" action="some.php" method="post">
<input type="text" name="user" id="mytext">
<input type="submit" value="Submit">
</form>
<script>
var w = someValue;
document.getElementById("mytext").value = w;
</script>
//php on some.php page
echo $_POST['user'];
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode
-Version 2
or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection
from wget
if you're behind a proxy and don't have HTTP_PROXY
and HTTPS_PROXY
environment variables set correctly. Make sure to set HTTP_PROXY
and HTTPS_PROXY
to point to your proxy.
This is a common situation if you work for a large corporation.
MediaWiki's API is running on Wikipedia (docs). You can also use the Special:Export feature to dump data and parse it yourself.
Like Scaffman said - You are missing quotes. Always when you are passing a value to varchar2 use quotes
INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
So one (') starts the string and the second (') closes it.
But if you want to add a quote symbol into a string for example:
My father told me: 'you have to be brave, son'.
You have to use a triple quote symbol like:
'My father told me: ''you have to be brave, son''.'
*adding quote method can vary on different db engines
working now :) Code attached below
<TextView
android:text="START | lunch 20.00 | Dinner 60.00 | Travel 60.00 | Doctor 5000.00 | lunch 20.00 | Dinner 60.00 | Travel 60.00 | Doctor 5000.00 | END"
android:id="@+id/MarqueeText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:paddingLeft="15dip"
android:paddingRight="15dip"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true">
Edit (on behalf of Adil Hussain):
textView.setSelected(true)
needs to be set in code behind for this to work.
try this code to create a button and repeat it for 2 more times with different coordinates and the method(myButtonClick) is called when the button is pressed
UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom];
editButton.frame = CGRectMake(0, 0, width, height);
[editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal];
[myButton addTarget:self action:@selector(myButtonClick:) forControlEvents:UIControlEventTouchUpInside];
editButton.adjustsImageWhenHighlighted = YES;
editButton.titleLabel.text = @"Edit";
editButton.titleLabel.textColor = [UIColor whiteColor];
editButton.titleLabel.textAlignment = UITextAlignmentCenter;
editButton.titleLabel.font = [UIFont fontWithName: @"Helvetica" size: 14];
[self.view addSubview: editButton];
-(void) myButtonClick:(NSString *)myString{
NSLog(@"you clicked on button %@", myString);
}
You could also try wrapping the two div's in two div's with unique ids. Then select the div by $("#div1","#wraper1")
and $("#div1","#wraper2")
Here you go:
<div id="wraper1">
<div id="div1">
</div>
<div id="wraper2">
<div id="div1">
</div>
You can do it like this:
class UsersController < ApplicationController
## Exception Handling
class NotActivated < StandardError
end
rescue_from NotActivated, :with => :not_activated
def not_activated(exception)
flash[:notice] = "This user is not activated."
Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
redirect_to "/"
end
def show
// Do something that fails..
raise NotActivated unless @user.is_activated?
end
end
What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.
Best wishes,
Fabian
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
If you are using Kotlin getting error because of some mistakes in xml files. In kotlin its very hard to find xml errors, build getting fail simply . To know the exact error log run below command in Android Studio Terminal and it is easy to fix the errors.
./gradlew clean
./gradlew assemble
This worked for me:
-> uninstalled Jupyter
-> install jupyter in Python36 folder
-> open Jupyter from command prompt instead of git bash.
Here is what worked for me. Tested in PHP 5.6 as well as as PHP 7.0:
$skuList = str_replace("\\r\\n", "\n", $_POST['skuList']);
$skuList = str_replace("\\n\\r", "\n", $skuList);
$skuList = preg_split("/\n/", $skuList);
print_r($skuList);
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
You need to provide the entire certificate chain to curl, since curl no longer ships with any CA certs. Since the cacert option can only use one file, you need to concat the full chain info into 1 file
Copy the certificate chain (from your browser, for example) into DER encoded binary x.509(.cer). Do this for each cert.
Convert the certs into PEM, and concat them into 1 file.
openssl x509 -inform DES -in file1.cer -out file1.pem -text
openssl x509 -inform DES -in file2.cer -out file2.pem -text
openssl x509 -inform DES -in file3.cer -out file3.pem -text
cat *.pem > certRepo
curl --cacert certRepo -u user:passwd -X GET -H 'Content-Type: application/json' "https//somesecureserver.com/rest/field"
I wrote a blog on how to do this here: http://javamemento.blogspot.no/2015/10/using-curl-with-ssl-cert-chain.html
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
I've tryied all answers of this topic, but just this below worked fine on my project.
Angular 7 and AGM Core 1.0.0-beta.7
<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
<agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
*ngFor="let localizacao of localizacoesTec">
</agm-marker>
</agm-map>
The properties [agmFitBounds]="true"
at agm-marker
and [fitBounds]="true"
at agm-map
does the job
Use from
to directly convert a previously created Promise to an Observable.
import { from } from 'rxjs';
// getPromise() is called once, the promise is passed to the Observable
const observable$ = from(getPromise());
observable$
will be a hot Observable that effectively replays the Promises value to Subscribers.
It's a hot Observable because the producer (in this case the Promise) is created outside of the Observable. Multiple subscribers will share the same Promise. If the inner Promise has been resolved a new subscriber to the Observable will get its value immediately.
Use defer
with a Promise factory function as input to defer the creation and conversion of a Promise to an Observable.
import { defer } from 'rxjs';
// getPromise() is called every time someone subscribes to the observable$
const observable$ = defer(() => getPromise());
observable$
will be a cold Observable.
It's a cold Observable because the producer (the Promise) is created inside of the Observable. Each subscriber will create a new Promise by calling the given Promise factory function.
This allows you to create an observable$
without creating and thus executing a Promise right away and without sharing this Promise with multiple subscribers.
Each subscriber to observable$
effectively calls from(promiseFactory()).subscribe(subscriber)
. So each subscriber creates and converts its own new Promise to a new Observable and attaches itself to this new Observable.
Most RxJS operators that combine (e.g. merge
, concat
, forkJoin
, combineLatest
...) or transform observables (e.g. switchMap
, mergeMap
, concatMap
, catchError
...) accept promises directly. If you're using one of them anyway you don't have to use from
to wrap a promise first (but to create a cold observable you still might have to use defer
).
// Execute two promises simultaneously
forkJoin(getPromise(1), getPromise(2)).pipe(
switchMap(([v1, v2]) => v1.getPromise(v2)) // map to nested Promise
)
Check the documentation or implementation to see if the operator you're using accepts ObservableInput
or SubscribableOrPromise
.
type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
// Note the PromiseLike ----------------------------------------------------v
type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>;
The difference between from
and defer
in an example: https://stackblitz.com/edit/rxjs-6rb7vf
const getPromise = val => new Promise(resolve => {
console.log('Promise created for', val);
setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000);
});
// the execution of getPromise('FROM') starts here, when you create the promise inside from
const fromPromise$ = from(getPromise('FROM'));
const deferPromise$ = defer(() => getPromise('DEFER'));
fromPromise$.subscribe(console.log);
// the execution of getPromise('DEFER') starts here, when you subscribe to deferPromise$
deferPromise$.subscribe(console.log);
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
just after TouchableWithoutFeedback
or <TouchableHighlight>
insert a <View>
this way you won't get this error. why is that then @Pedram answer or other answers explains enough.
Best to use JSON.stringify()
to cover all your bases, like backslashes and other special characters. Here's your original function with that in place instead of modifying strInputString
:
function testEscape() {
var strResult = "";
var strInputString = "fsdsd'4565sd";
var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);
}
(This way your strInputString
could be something like \\\'\"'"''\\abc'\
and it will still work fine.)
Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.
Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it.
HashMap<String,int> frequencymap = new HashMap<String,int>();
foreach(String a in animals) {
if(frequencymap.containsKey(a)) {
frequencymap.put(a, frequencymap.get(a)+1);
}
else{ frequencymap.put(a, 1); }
}
public function index() {
$user = $this->session->userdata("username");
$file_path = "./images/" . $user . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('images/' . $user)) {
mkdir('./images/' . $user, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
for ($i = 0; $i < $cpt; $i ++) {
$name = time().$files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->load->model('uploadModel','um');
$this->um->insertRecord($user,$name);
}
}
} else {
$this->load->view('uploadForm');
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}
In Typescript, one doesn't necessarily have to follow the new instance()
Singleton methodology. An imported, constructor-less static class can work equally as well.
Consider:
export class YourSingleton {
public static foo:bar;
public static initialise(_initVars:any):void {
YourSingleton.foo = _initvars.foo;
}
public static doThing():bar {
return YourSingleton.foo
}
}
You can import the class and refer to YourSingleton.doThing()
in any other class. But remember, because this is a static class, it has no constructor so I usually use an intialise()
method that is called from a class that imports the Singleton:
import {YourSingleton} from 'singleton.ts';
YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();
Don't forget that in a static class, every method and variable needs to also be static so instead of this
you would use the full class name YourSingleton
.
This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange
function from the dplyr
package in the same way as the plyr
package.
library(dplyr)
arrange(DF, ID, desc(num))
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
Recommendation:
when you have more than one condition with and
and or
is better separate with ()
to avoid verification problems
<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">
There are many ways...one is to use the std::find()
algorithm, e.g.
#include <algorithm>
int myArray[] = { 3, 2, 1, 0, 1, 2, 3 };
size_t myArraySize = sizeof(myArray) / sizeof(int);
int *end = myArray + myArraySize;
// find the value 0:
int *result = std::find(myArray, end, 0);
if (result != end) {
// found value at "result" pointer location...
}
Using Promise
and checking if the body
object is a valid JSON. If not a Promise reject
will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
If you're feeling brave, you can experiment with browser sniffing and get a version:
var ua = navigator.userAgent;
if(/chrome/i.test(ua)) {
var uaArray = ua.split(' ')
, version = uaArray[uaArray.length - 2].substr(7);
}
This detected version might be a Chrome version, or a Edge version, or something else. Browser plugins can easily change userAgent and platform and other things though, so this is not recommended.
Apologies to The Big Lebowski for using his answer within mine.
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
Selenium doesn't currently offer API for this, but there are several ways to initiate an HTTP request in your test. It just depends what language you are writing in.
In Java for example, it might look like this:
// setup the request
String request = "startpoint?stuff1=foo&stuff2=bar";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// get a response - maybe "success" or "true", XML or JSON etc.
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
response.append('\r');
}
bufferedReader.close();
// continue with test
if (response.toString().equals("expected response"){
// do selenium
}
I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.
Under Oracle 12c, I found that that my registry$history is empty. This works instead:
select * from registry$sqlpatch;
You can use istringstream
.
string s = "10";
// create an input stream with your string.
istringstream is(str);
int i;
// use is like an input stream
is >> i;
You could use Enumerable#select:
clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]
Note that the result will be an array of all the matching values, where each is an array of the key and value.
From the shell command line:
python file.py
From the Python command line
import file
or
from file import *
Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.
In Swift, I'm using:
In my Macros.swift I just added
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__){
println("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
you can now just call anywhere
TICK()
// your code to be tracked
TOCK()
Swift 5.0
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = #function, file: String = #file, line: Int = #line){
print("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.
Server:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
and the Client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
}
}
IFormattable also includes a format provider that can be used, it allows both format of IFormatProvider to be null in dotnet 4.0 this would be
/// <summary>
/// Extentionclass for a nullable structs
/// </summary>
public static class NullableStructExtensions {
/// <summary>
/// Formats a nullable struct
/// </summary>
/// <param name="source"></param>
/// <param name="format">The format string
/// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
/// <param name="provider">The format provider
/// If <c>null</c> the default provider is used</param>
/// <param name="defaultValue">The string to show when the source is <c>null</c>.
/// If <c>null</c> an empty string is returned</param>
/// <returns>The formatted string or the default value if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, string format = null,
IFormatProvider provider = null,
string defaultValue = null)
where T : struct, IFormattable {
return source.HasValue
? source.Value.ToString(format, provider)
: (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
}
}
using together with named parameters you can do:
dt2.ToString(defaultValue: "n/a");
In older versions of dotnet you get a lot of overloads
/// <summary>
/// Extentionclass for a nullable structs
/// </summary>
public static class NullableStructExtensions {
/// <summary>
/// Formats a nullable struct
/// </summary>
/// <param name="source"></param>
/// <param name="format">The format string
/// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
/// <param name="provider">The format provider
/// If <c>null</c> the default provider is used</param>
/// <param name="defaultValue">The string to show when the source is <c>null</c>.
/// If <c>null</c> an empty string is returned</param>
/// <returns>The formatted string or the default value if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, string format,
IFormatProvider provider, string defaultValue)
where T : struct, IFormattable {
return source.HasValue
? source.Value.ToString(format, provider)
: (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
}
/// <summary>
/// Formats a nullable struct
/// </summary>
/// <param name="source"></param>
/// <param name="format">The format string
/// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
/// <param name="defaultValue">The string to show when the source is null. If <c>null</c> an empty string is returned</param>
/// <returns>The formatted string or the default value if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, string format, string defaultValue)
where T : struct, IFormattable {
return ToString(source, format, null, defaultValue);
}
/// <summary>
/// Formats a nullable struct
/// </summary>
/// <param name="source"></param>
/// <param name="format">The format string
/// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
/// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
/// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, string format, IFormatProvider provider)
where T : struct, IFormattable {
return ToString(source, format, provider, null);
}
/// <summary>
/// Formats a nullable struct or returns an empty string
/// </summary>
/// <param name="source"></param>
/// <param name="format">The format string
/// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
/// <returns>The formatted string or an empty string if the source is null</returns>
public static string ToString<T>(this T? source, string format)
where T : struct, IFormattable {
return ToString(source, format, null, null);
}
/// <summary>
/// Formats a nullable struct
/// </summary>
/// <param name="source"></param>
/// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
/// <param name="defaultValue">The string to show when the source is <c>null</c>. If <c>null</c> an empty string is returned</param>
/// <returns>The formatted string or the default value if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, IFormatProvider provider, string defaultValue)
where T : struct, IFormattable {
return ToString(source, null, provider, defaultValue);
}
/// <summary>
/// Formats a nullable struct or returns an empty string
/// </summary>
/// <param name="source"></param>
/// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
/// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
public static string ToString<T>(this T? source, IFormatProvider provider)
where T : struct, IFormattable {
return ToString(source, null, provider, null);
}
/// <summary>
/// Formats a nullable struct or returns an empty string
/// </summary>
/// <param name="source"></param>
/// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
public static string ToString<T>(this T? source)
where T : struct, IFormattable {
return ToString(source, null, null, null);
}
}
I always do the following whenever I get such error:
// remove node_modules/
rm -rf node_modules/
// install node_modules/ again
npm install // or, yarn
and then start the project
npm start //or, yarn start
It works fine after re-installing node_modules. But I don't know if it's good practice.
If you want the correlations between all pairs of columns, you could do something like this:
import pandas as pd
import numpy as np
def get_corrs(df):
col_correlations = df.corr()
col_correlations.loc[:, :] = np.tril(col_correlations, k=-1)
cor_pairs = col_correlations.stack()
return cor_pairs.to_dict()
my_corrs = get_corrs(df)
# and the following line to retrieve the single correlation
print(my_corrs[('Citable docs per Capita','Energy Supply per Capita')])
aggfunc=pd.Series.nunique
provides distinct count.
Full Code:
df2.pivot_table(values='X', rows='Y', cols='Z',
aggfunc=pd.Series.nunique)
Credit to @hume for this solution (see comment under the accepted answer). Adding as an answer here for better discoverability.
In android-studio version 4.0., OS-Ubuntu-18.04., Please follow my Steps
Step-1: Right Click on Project-->Open Module Option
Step-2: Click Your Module --> click (-)sign done on Top Left in PopUp, then press ok button.
Step-3: After removed module from the project
Step-4: Again do right-click in Project, Select Delete menu to Remove whole content from Disk space(i.e.folder).
Step-5: Delete the content of the module from disk by clicking done.
Hope it helps. Thank you
The Google Maps API location now works, even has listeners, you can do it using that, for example:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
OnMyLocationChangeListener
interface is deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
It's a builtin function that returns an object that can be iterated over. See the documentation.
In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:
for item in enumerate(["a", "b", "c"]):
print item
prints
(0, "a")
(1, "b")
(2, "c")
It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate
.
In one of the comments, you say:
Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object
If it's your code, figure out how you're getting None
when you expect a number and stop that from happening.
If it's someone else's code, find out the conditions under which it gives None
and determine a sensible value to use for that, with the usual conditional code:
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
...or even...
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
There's no reason to automatically use 0
here — solutions that depend on the "false"-ness of None
assume you will want this. The DEFAULT_VALUE
(if it even exists) completely depends on your code's purpose.
var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;
I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:
public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp)
{
var parameter = Expression.Parameter(sourceType);
var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
var left = leftVisitor.Visit(exp.Body);
var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
var right = rightVisitor.Visit(newExp.Body);
var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
}
You can return multiple value inside a xml data type in "case" expression, then extract them, also "else" block is available
SELECT
xmlcol.value('(value1)[1]', 'NVARCHAR(MAX)') AS value1,
xmlcol.value('(value2)[1]', 'NVARCHAR(MAX)') AS value2
FROM
(SELECT CASE
WHEN <condition 1> THEN
CAST((SELECT a1 AS value1, b1 AS value2 FOR XML PATH('')) AS XML)
WHEN <condition 2> THEN
CAST((SELECT a2 AS value1, b2 AS value2 FOR XML PATH('')) AS XML)
ELSE
CAST((SELECT a3 AS value1, b3 AS value2 FOR XML PATH('')) AS XML)
END AS xmlcol
FROM <table>) AS tmp
You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';
In the current version of Google Play store Console as of(August 2017) here is the procedure of unpublishing your app.
After clicking unpublish a dialog will popup confirm and save the changes.
However, it is important to note that the mysql connector driver version must be older than 5.1.47 and later.
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.
$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0
git-status
on the parent repository will now report a dirty tree:
# On branch dev [...]
#
# modified: submodule (new commits)
Add the submodule directory and commit to store the new pointer.
Are you running C++ 11? stoi was added in C++ 11, if you're running on an older version use atoi()
Delete the Intermediate folder after then run the project is working fine actually that APK builds to another system. Go to app/build/intermediates.
It's easy to achieve this is to just use an Intent like this: (I put the method in a custom class that takes in an Activity as a parameter so it can be called from any Fragment or Activity)
public class UIutils {
private Activity mActivity;
public UIutils(Activity activity){
mActivity = activity;
}
public void showPhoto(Uri photoUri){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(photoUri, "image/*");
mActivity.startActivity(intent);
}
}
Then to use it just do this:
imageView.setOnClickListener(v1 -> new UIutils(getActivity()).showPhoto(Uri.parse(imageURI)));
I use this with an Image URL but it can be used with stored files as well. If you are accessing images form the phones memory you should use a content provider.
Responding to pzulw's feedback to sandroid about specifying the intent.
The format of the component name is described in the api docs for ComponentName.unflattenFromString
It splits the string at the first '/', taking the part before as the package name and the part after as the class name. As a special convenience (to use, for example, when parsing component names on the command line), if the '/' is immediately followed by a '.' then the final class name will be the concatenation of the package name with the string following the '/'. Thus "com.foo/.Blah" becomes package="com.foo" class="com.foo.Blah".
On IntelliJ IDEA 2016.1.2
Go to Settings > Editor > General > Appearance then check the Show Line number option
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
For startswith, you can use indexOf:
if(str.indexOf('Hello') == 0) {
...
and you can do the maths based on string length to determine 'endswith'.
if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
You could try scraping whatever you need with PHP or another server side language, then put the iframe to the scraped content. Here's an example with PHP:
scrapedcontent.php:
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
index.html:
<iframe src="scrapedcontent.php"></iframe>
Swift :
func runSpinAnimationOnView(view:UIView , duration:Float, rotations:Double, repeatt:Float ) ->()
{
let rotationAnimation=CABasicAnimation();
rotationAnimation.keyPath="transform.rotation.z"
let toValue = M_PI * 2.0 * rotations ;
// passing it a float
let someInterval = CFTimeInterval(duration)
rotationAnimation.toValue=toValue;
rotationAnimation.duration=someInterval;
rotationAnimation.cumulative=true;
rotationAnimation.repeatCount=repeatt;
view.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
}
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...
quickie example:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
mysql_*
extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
The simpler option is PDO which has a neat helper function fetchColumn()
:
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc()
could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
you want these four lines of code in your Run.bat:
@echo off //this makes it so you have an empty cmd window on startup
javac Main.java //this compiles the .java into a .class
java Main // this runs the .class file
pause //this prevents the window from instantly closing after program end
A WSDL document describes a webservice. It specifies the location of the service and the methods of the service using these major elements: data types using in webservice data elements for each operation describe the operations that can be performed and the messages envolved
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate operating systems to communicate using http and xml.
I have faced with the same issue. The resolve: - Window-->Preferences-->Java-->Installed JREs-->Add... - Right click on your project-->Build Path-->Configure Build Path-->Add library-->JRE system library-->next-->WorkSpace Default JRE
Features color wheel and pallet picker dialogs
gradle --recompile-scripts
seems to do a sync without building anything. you can enable automatic building by
gradle --recompile-scripts --continuous
Please refer the docs for more info:
https://docs.gradle.org/current/userguide/gradle_command_line.html
Simply, your question sounded wrong because the JavaScript variables need to be echoed.
<?php_x000D_
$num = 1;_x000D_
echo $num;_x000D_
echo "<input type='button' value='Click' onclick='readmore()' />";_x000D_
echo "<script> function readmore() { document.write('";_x000D_
$num = 2;_x000D_
echo $num;_x000D_
echo "'); } </script>";_x000D_
?>
_x000D_
On GitHub, you can use HTML directly instead of Markdown:
<a href="url"><img src="http://url.to/image.png" align="left" height="48" width="48" ></a>
This should make it.
Defining static properties and methods of a class is described in 8.2.1 of the Typescript Language Specification:
class Point {
constructor(public x: number, public y: number) {
throw new Error('cannot instantiate using a static class');
}
public distance(p: Point) {
var dx = this.x - p.x;
var dy = this.y - p.y;
return Math.sqrt(dx * dx + dy * dy);
}
static origin = new Point(0, 0);
static distance(p1: Point, p2: Point) {
return p1.distance(p2);
}
}
where Point.distance()
is a static (or "class") method.
An alternative to the cursor.description solution from smallredstone could be to use row.keys():
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row
cursor = connection.execute('select * from bar')
# instead of cursor.description:
row = cursor.fetchone()
names = row.keys()
The drawback: it only works if there is at least a row returned from the query.
The benefit: you can access the columns by their name (row['your_column_name'])
Read more about the Row objects in the python documentation.
Merge two different eloquent collections into one and some objects happen to have the same id, one will overwrite the other. Use push() method instead or rethink your approach to the problem to avoid that. Refer to web
Values not necessarily have to be unique so you have to do a lookup. You can do something like this:
var myKey = types.FirstOrDefault(x => x.Value == "one").Key;
If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.
In a maven project create a file src/main/resources/application.yml
with the following content:
spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>@<host>:<port>/<dbname>
Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)
java -jar -Dspring.profiles.active=integration your-app.jar
or with the production profile (and use your production MongoDB)
java -jar -Dspring.profiles.active=production your-app.jar
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.
Rectangle(int h,int w):
Shape(h,w)
{...}
Will call the other base class constructor.
If your click handler is successfully called then this should work:
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
var url = "/Artists/Details?NestId=" + NestId;
window.location.href = url;
})
EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null
, won't cause any exception at all, given that the ModelBinder won't complain about it.
There are several problems with using scanf
with the %d
conversion specifier to do this:
If the input string starts with a valid integer (such as "12abc"), then the "12" will be read from the input stream and converted and assigned to num
, and scanf
will return 1, so you'll indicate success when you (probably) shouldn't;
If the input string doesn't start with a digit, then scanf
will not read any characters from the input stream, num
will not be changed, and the return value will be 0;
You don't specify if you need to handle non-decimal formats, but this won't work if you have to handle integer values in octal or hexadecimal formats (0x1a). The %i
conversion specifier handles decimal, octal, and hexadecimal formats, but you still have the first two problems.
First of all, you'll need to read the input as a string (preferably using fgets
). If you aren't allowed to use atoi
, you probably aren't allowed to use strtol
either. So you'll need to examine each character in the string. The safe way to check for digit values is to use the isdigit
library function (there are also the isodigit
and isxdigit
functions for checking octal and hexadecimal digits, respectively), such as
while (*input && isdigit(*input))
input++;
(if you're not even allowed to use isdigit
, isodigit
, or isxdigit
, then slap your teacher/professor for making the assignment harder than it really needs to be).
If you need to be able to handle octal or hex formats, then it gets a little more complicated. The C convention is for octal formats to have a leading 0
digit and for hex formats to have a leading 0x
. So, if the first non-whitespace character is a 0, you have to check the next character before you can know which non-decimal format to use.
The basic outline is
isdigit
to check the remaining characters;isodigit
to check the remaining characters;x
or X
, then the input is in hexadecimal format and you will use isxdigit
to check the remaining characters;You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.
Here's a demo on jsbin.
.cut-text {
text-overflow: ellipsis;
overflow: hidden;
width: 160px;
height: 1.2em;
white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
If you don't want to grant admin permission to dashboard service account, you can create cluster admin service account.
$ kubectl create serviceaccount cluster-admin-dashboard-sa
$ kubectl create clusterrolebinding cluster-admin-dashboard-sa \
--clusterrole=cluster-admin \
--serviceaccount=default:cluster-admin-dashboard-sa
And then, you can use the token of just created cluster admin service account.
$ kubectl get secret | grep cluster-admin-dashboard-sa
cluster-admin-dashboard-sa-token-6xm8l kubernetes.io/service-account-token 3 18m
$ kubectl describe secret cluster-admin-dashboard-sa-token-6xm8l
I quoted it from giantswarm guide - https://docs.giantswarm.io/guides/install-kubernetes-dashboard/
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
Swift 3+ & Swift 4 version:
DispatchQueue.main.async {
print("Hello")
}
Swift 3 and Xcode 9.2:
dispatch_async_on_main_queue {
print("Hello")
}
Updated with feedback from Alan Moore
In PCRE and similar variants, you can actually create a regex that matches any line not containing a value:
^(?:(?!Andrea).)*$
This is called a tempered greedy token. The downside is that it doesn't perform well.
here's one way you can do it with awk
curl -sL 'http://twitter.com/users/username.json' | awk -F"," -v k="text" '{
gsub(/{|}/,"")
for(i=1;i<=NF;i++){
if ( $i ~ k ){
print $i
}
}
}'
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.
Check out https://github.com/serratus/quaggaJS
"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."
You could also use Springs PropertyComparator if you have just a String property path to the (nested) property you want to sort:
List<SomeObject> list = ...;
PropertyComparator<HitWithInfo> propertyComparator = new PropertyComparator<>(
"property.nested.myProperty", false, true);
list.sort(propertyComparator);
The drawback is, that this comparator silently ignores properties which does not exist or are not accessible and handles this as null value for comparison. This means, you should carefully test such a comparator or validate the existence of the property path somehow.
That looks like the GitLab issue 5769.
In GitLab, since the repositories always end in
.git
, I must specify.git
at the end of the repository name to make it work, for example:import "example.org/myuser/mygorepo.git"
And:
$ go get example.org/myuser/mygorepo.git
Looks like GitHub solves this by appending
".git"
.
It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go
: go get cannot discover meta tag in HTML5 documents”.
btnTest_Click(new object(), EventArgs.Empty)
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
Yes there is a difference.
The Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
The ProcessBuilder
constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)
So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.
I had the same issue which after setting following path variables got vanished Note AVD Home path is different from other three.
Use the "min-height" property
Be wary of paddings, margins and borders :)
html, body {
margin: 0;
padding: 0;
border: 0;
}
#B, #C, #D {
position: absolute;
}
#A{
top: 0;
width: 100%;
height: 35px;
background-color: #99CC00;
}
#B {
top: 35px;
width: 200px;
bottom: 35px;
background-color: #999999;
z-index:100;
}
#B2 {
min-height: 100%;
height: 100%;
margin-top: -35px;
bottom: 0;
background-color: red;
width: 200px;
overflow: scroll;
}
#B1 {
height: 35px;
width: 35px;
margin-left: 200px;
background-color: #CC0066;
}
#C {
top: 35px;
left: 200px;
right: 0;
bottom: 35px;
background-color: #CCCCCC;
}
#D {
bottom: 0;
width: 100%;
height: 35px;
background-color: #3399FF;
}
Tested out Warkst's third code snippet--worked great, except I changed it to be default input type instead of numeric:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeDefault;
alertTextField.placeholder = @"Enter your name";
[alert show];
Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.
private void initActivityScreenOrientPortrait()
{
// Avoid screen rotations (use the manifests android:screenOrientation setting)
// Set this to nosensor or potrait
// Set window fullscreen
this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DisplayMetrics metrics = new DisplayMetrics();
this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Test if it is VISUAL in portrait mode by simply checking it's size
boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels );
if( !bIsVisualPortrait )
{
// Swap the orientation to match the VISUAL portrait mode
if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
{ this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
}
else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }
}
Works like a charm!
NOTICE:
Change this.activity
by your activity or add it to the main activity and remove this.activity
;-)
The regular expression would be:
.+name="([^"]+)"
Then the grouping would be in the \1
Another way is to add the folder to your source lookup path: http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdebug%2Fref-editsourcelookup.htm
The application/x-www-form-urlencoded
Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:
curl -X DELETE "http://localhost:5000/locations?id=3"
or
curl -X GET "http://localhost:5000/locations?id=3"
Just in case it helps someone - In my scenario, I have some shared libraries (Which have their own TFS projects/solutions) all combined into one solution.
Nuget would restore projects successfully, but the DLL would be missing.
The underlying issue was that, whilst your solution has its own packages folder and has restored them correctly to that folder, the project file (e.g. .csproj) is referencing a different project which may not have the package downloaded. Open the file in a text editor to see where your references are coming from.
This can occur when managing packages on different interlinked shared solutions - since you probably want to make sure all DLLs are on the same level you might set this at the top level. This means it that sometimes it will be looking in a completely different solution for a referenced DLL and so if you don't have all projects/solutions downloaded and up-to-date then you may get the above problem.
This is and old question, but now on PHP 7.1 you can define constant visibility.
EXAMPLE
<?php
class Foo {
// As of PHP 7.1.0
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR . PHP_EOL;
echo Foo::BAZ . PHP_EOL;
?>
Output of the above example in PHP 7.1:
bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.
More info here
You can install it by bower:
Node.js npm install underscore
Meteor.js meteor add underscore
Require.js require(["underscore"], ...
Bower bower install underscore
Component component install jashkenas/underscore
Here's the link to the oficial page http://underscorejs.org/
Some DBMSs support the FROM (SELECT ...) AS alias_name
syntax.
Think of your two original queries as temporary tables. You can query them like so:
SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008"
FROM (query1) as t1, (query2) as t2
WHERE t1.Activity = t2.Activity
You can use 'onclick' attribute like this :
<a ... href="javascript: onclick();" ...>...</a>
There are several things you could do to optimise the script - but maximum success would make it IO-bound rather than CPU-bound:
rtrim($path, '/')
outside the loop.if ($t<>"." && $t<>"..")
the outer test - it doesn't need to stat the pathrtrim($path, '/') . '/' . $t
once per loop - inside 2) and taking 1) into account.explode(' ','B KB MB GB TB PB');
once rather than each call?var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.
To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:
if(yyy == null || !yyy.Any()) return otherValue;
For me this issue was caused by the file encoding format being wrong.
I used another editor and it was saved as UTF-8-BOM
so the very first line I had was @echo off
but there was a hidden character in the front of it.
So I changed the encoding to plain old ANSI
text, and then the issue went away.
Best option is create new table with same properties
CREATE TABLE <NEW.NAME.TABLE> LIKE <TABLE.CRASHED>;
INSERT INTO <NEW.NAME.TABLE> SELECT * FROM <TABLE.CRASHED>;
Rename NEW.NAME.TABLE and TABLE.CRASH
RENAME TABLE <TABLE.CRASHED> TO <TABLE.CRASHED.BACKUP>;
RENAME TABLE <NEW.NAME.TABLE> TO <TABLE.CRASHED>;
After work well, delete
DROP TABLE <TABLE.CRASHED.BACKUP>;
If you want to use the same library folder for several projects, you can reference it in gradle to an external location like this:
settings.gradle:
include 'app', ':volley'
project(':volley').projectDir = new File('../libraries/volley')
in your app build.gradle
dependencies {
...
compile project(':volley')
...}
Just to clarify some of the great answers here, the steps outlined in many of the answers assume that you already have a remote repository somewhere.
Given: an existing git repository, e.g. [email protected]:some-user/full-repo.git
, with one or more directories that you wish to pull independently of the rest of the repo, e.g. directories named app1
and app2
Assuming you have a git repository as the above...
Then: you can run steps like the following to pull only specific directories from that larger repo:
mkdir app1
cd app1
git init
git remote add origin [email protected]:some-user/full-repo.git
git config core.sparsecheckout true
echo "app1/" >> .git/info/sparse-checkout
git pull origin master
I had mistakenly thought that the sparse-checkout options had to be set on the original repository, but this is not the case: you define which directories you want locally, prior to pulling from the remote. The remote repo doesn't know or care about your only wanting to track a part of the repo.
Hope this clarification helps someone else.
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?
$array = array(
"foo" => "bar",
"bar" => "foo"
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
The following line is allowed with the above array but would give an error if it was a dictionary.
print $array[0]
Python has both arrays and dictionaries.
If you decide to use printf or sprintf, note that they use the Round half to even method.
foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
//How to start another application from the current application
Process runProg = new Process();
runProg.StartInfo.FileName = pathToFile; //the path of the application
runProg.StartInfo.Arguments = genArgs; //any arguments you want to pass
runProg.StartInfo.CreateNoWindow = true;
runProg.Start();
//How to end the same application from the current application
int IDstring = System.Convert.ToInt32(runProg.Id.ToString());
Process tempProc = Process.GetProcessById(IDstring);
tempProc.CloseMainWindow();
tempProc.WaitForExit();