I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.
If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.
One has to create a new MySQL User
and assign privileges as below in Query prompt
via phpMyAdmin or command prompt:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost' WITH GRANT OPTION;
CREATE USER 'username'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
Once done with all four queries, it should connect with username / password
If you are in the same directory as the file:
ls "`pwd`/file.txt"
Replace file.txt
with your target filename.
There is the .update() method :)
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.
When a program is loaded into memory, it’s organized into different segments. One of the segment is DATA segment. The Data segment is further sub-divided into two parts:
Initialized data segment: All the global, static and constant data are stored here.
Uninitialized data segment(BSS): All the uninitialized data are stored in this segment.
Here is a diagram to explain this concept:
here is very good link explaining these concepts:
I hope this will help you:
final TextView t1=new TextView(this);
t1.setText("Hello Android");
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
t1.setTextSize(progress);
Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();
}
});
With all the solutions above even though you're hiding the code, you'll still get the [<matplotlib.lines.Line2D at 0x128514278>]
crap above your figure which you probably don't want.
If you actually want to get rid of the input rather than just hiding it, I think
the cleanest solution is to save your figures to disk in hidden cells, and then just including the images in Markdown cells using e.g. ![Caption](figure1.png)
.
if (Request.Params["__EVENTTARGET"] != null)
{
if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
{
DoWhateverYouWant();
}
}
Check your project folder. You may have there a file called gradle.properties and in there, check to see if you don't have this line:
org.gradle.jvmargs=-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
In my case, I just deleted the file, but check the contents to see if you don't actually want to keep some of the settings.
The text inside $type is substituted directly into the insert string, therefore MySQL gets this:
... VALUES(testing, 'john', 'whatever')
Notice that there are no quotes around testing, you need to put these in like so:
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:
Also useful is the coalesce operator ??:
VB:
Return Iif( s IsNot Nothing, s, "My Default Value" )
C#:
return s ?? "My Default Value";
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
An alternative list comprehension method that uses list index values:
stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]
This returns:
['b', 'c', 'e', 'f']
In ruby Fixnums are automatically converted to Bignums.
To find the highest possible Fixnum you could do something like this:
class Fixnum
N_BYTES = [42].pack('i').size
N_BITS = N_BYTES * 8
MAX = 2 ** (N_BITS - 2) - 1
MIN = -MAX - 1
end
p(Fixnum::MAX)
Shamelessly ripped from a ruby-talk discussion. Look there for more details.
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
The object you're saving should have a correct Id
after propagating changes into database.
I had the same problem. My customer ordered me Python 3.4 script that updates XLS (not XLSX) Excel files.
The 1st package xlrd was installed by "pip install" without problems in my Python home.
The 2nd one xlwt needed to say "pip install xlwt-future" to be compatible.
The 3rd one xlutils has no support for Python 3, but I adapted it a little bit and now it works at least for dummy script:
#!C:\Python343\python
from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd
from xlwt import easyxf # http://pypi.python.org/pypi/xlwt
file_path = 'C:\Dev\Test_upd.xls'
rb = open_workbook('C:\Dev\Test.xls',formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy
w_sheet.write(1, 1, 'Value')
wb.save(file_path)
I attached the file here: http://ifolder.su/43507580
Write to [email protected] if it got expired.
P.S.: Some functions are not called in the dummy example, so maybe they will need for an adaptation also. Who wants to do it, fix exceptions one-by-one with a google help. It's not a very difficult task, because the package code is small...
For WINDOWS (shell) users with Notepad++ (checked with v6.8.3) you can correct the specific file using the option - Edit -> EOL conversion -> Unix/OSX format
And save your file again.
Edit: still works in v7.5.1 (Aug 29 2017)
If you would like to combine the matrix with some visualisations I can recommend (I am using the built in iris
dataset):
library(psych)
pairs.panels(iris[1:4]) # select columns 1-4
The Performance Analytics basically does the same but includes significance indicators by default.
library(PerformanceAnalytics)
chart.Correlation(iris[1:4])
Or this nice and simple visualisation:
library(corrplot)
x <- cor(iris[1:4])
corrplot(x, type="upper", order="hclust")
Using pdfbox we can achive this
Example :
public static void main(String args[]) {
PDFParser parser = null;
PDDocument pdDoc = null;
COSDocument cosDoc = null;
PDFTextStripper pdfStripper;
String parsedText;
String fileName = "E:\\Files\\Small Files\\PDF\\JDBC.pdf";
File file = new File(fileName);
try {
parser = new PDFParser(new FileInputStream(file));
parser.parse();
cosDoc = parser.getDocument();
pdfStripper = new PDFTextStripper();
pdDoc = new PDDocument(cosDoc);
parsedText = pdfStripper.getText(pdDoc);
System.out.println(parsedText.replaceAll("[^A-Za-z0-9. ]+", ""));
} catch (Exception e) {
e.printStackTrace();
try {
if (cosDoc != null)
cosDoc.close();
if (pdDoc != null)
pdDoc.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
You can use [ActionName("NewActionName")] to use the same method with a different name:
public class HomeController : Controller
{
public ActionResult GetEmpName()
{
return Content("This is the test Message");
}
[ActionName("GetEmpWithCode")]
public ActionResult GetEmpName(string EmpCode)
{
return Content("This is the test Messagewith Overloaded");
}
}
If you remove directives attribute it should work.
@Component({
selector: 'parent',
template: `
<h1>Parent Component</h1>
<child></child>
`
})
export class ParentComponent{}
@Component({
selector: 'child',
template: `
<h4>Child Component</h4>
`
})
export class ChildComponent{}
Directives are like components but they are used in attributes. They also have a declarator @Directive
. You can read more about directives Structural Directives and Attribute Directives.
There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.
A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.
Also if you are open the glossary you can find that components are also directives.
Directives fall into one of the following categories:
Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.
Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.
Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.
The difference that components have a template. See Angular Architecture overview.
A directive is a class with a
@Directive
decorator. A component is a directive-with-a-template; a@Component
decorator is actually a@Directive
decorator extended with template-oriented features.
The @Component
metadata doesn't have directives
attribute. See Component decorator.
just simple as this:
float num = 23658; // for example
num = num.ToString("N0"); // Returns 23,658
more info is in Here
Use This function to set all Type of margins
public void setViewMargins(Context con, ViewGroup.LayoutParams params,
int left, int top , int right, int bottom, View view) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel_left = (int) (left * scale + 0.5f);
int pixel_top = (int) (top * scale + 0.5f);
int pixel_right = (int) (right * scale + 0.5f);
int pixel_bottom = (int) (bottom * scale + 0.5f);
ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);
view.setLayoutParams(params);
}
I found a solution which works, although it is a bit ugly. It also won't work in every situation, but it works for me. Since I'm adapting the size of the user interface to the iPad's window size, the user is normally unable to scroll. In other words, if I set the window's scrollTop, it will remain at 0.
If, on the other hand, the keyboard is shown, scrolling suddenly works. So I can set scrollTop, immediately test its value, and then reset it. Here's how that might look in code, using jQuery:
$(document).ready(function(){
$('input').bind('focus',function() {
$(window).scrollTop(10);
var keyboard_shown = $(window).scrollTop() > 0;
$(window).scrollTop(0);
$('#test').append(keyboard_shown?'keyboard ':'nokeyboard ');
});
});
Normally, you would expect this to not be visible to the user. Unfortunately, at least when running in the Simulator, the iPad visibly (though quickly) scrolls up and down again. Still, it works, at least in some specific situations.
I've tested this on an iPad, and it seems to work fine.
Yet another approach to the same problem. As it is not recommended to store any kind of credential within the source code, we decided to set the passwords for the key store and key alias in a separate properties file as follows:
key.store.password=[STORE PASSWORD]
key.alias.password=[KEY PASSWORD]
If you use git, you can create a text file called, for example, secure.properties. You should make sure to exclude it from your repository (if using git, adding it to the .gitignore file). Then, you would need to create a signing configuration, like some of the other answers indicate. The only difference is in how you would load the credentials:
android {
...
signingConfigs {
...
release {
storeFile file('[PATH TO]/your_keystore_file.jks')
keyAlias "your_key_alias"
File propsFile = file("[PATH TO]/secure.properties");
if (propsFile.exists()) {
Properties props = new Properties();
props.load(new FileInputStream(propsFile))
storePassword props.getProperty('key.store.password')
keyPassword props.getProperty('key.alias.password')
}
}
...
}
buildTypes {
...
release {
signingConfig signingConfigs.release
runProguard true
proguardFile file('proguard-rules.txt')
}
...
}
}
Never forget to assign the signingConfig to the release build type manually (for some reason I sometimes assume it will be used automatically). Also, it is not mandatory to enable proguard, but it is recommendable.
We like this approach better than using environment variables or requesting user input because it can be done from the IDE, by switching to the realease build type and running the app, rather than having to use the command line.
I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.
The way that I have gotten around it in the past is I have done things like this:
$user = createUser();
$role = $user->role;
$role->rolename = 'Test';
now if you do this:
echo $user->role->rolename;
you should see 'Test'
This is a Pythonic way to do it:
import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
print "Hmmm, no last-modified data was returned from the URL."
print "Returned header:"
print yaml.dump(dict(r.getheaders()), default_flow_style=False)
The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
About the libraries you could use are.
And there could be many more, but that are what I've used
About the json I don't now maybe something like this
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
why can't I use a property like self.myView
instead of a local variable like myView?
try using:
NSDictionaryOfVariableBindings(_view)
instead of self.view
Like @Franz answer you can also do it with a select. For example:
<select>
<option></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
With this you can also give a concrete value that will be send with the form, I think that with javascript indeterminate version of checkbox, it will send the underline value of the checkbox.
At least, you can use it as a callback when javascript is disabled. For example, give it an id and in the load event change it to the javascript version of the checkbox with indeterminate status.
May I present my guess, since this is not a open technology.
Google says it's about combing information from before, during, after to distinguish human from robot. But I am more interested about that final click on the check box.
Say, the POST data (solved CAPTCHA) has a field called fingerprint, a string calculated from user behavior. I think there may be a field about that check box location. I guess this check box is in a coordinate system randomly generated by Google back-end and encrypted by the public key of my site. So, a robot may "guess/calculate" a location about this box, but when site owner makes the GET query with private key to verify user identity, Google will decrypt the coordinate system and say if the user click on the right place. So, only one possible right click(with some offsets, it's a square box) location in this random coordinate system owned by only Google and site owners.
There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.
I would suggest something like this:
int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
printf( "%d", my_array[index][jdex] );
printf( "\n" );
}
}
The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Use hypertext reference and the ID tag,
Some paragraph text
Target Text<h1><a href="#target">Target Text Title</a></h1>
<p id="target">Target Text</p>
It is a good idea to verify if the device has these packages installed:
mListPackageName.add("com.google.android.launcher.layouts.genymotion");
mListPackageName.add("com.bluestacks");
mListPackageName.add("com.vphone.launcher");
mListPackageName.add("com.bignox.app");
And then simply check against the package manager till it finds one.
private static boolean isEmulByPackage(Context context) {
final PackageManager pm = context.getPackageManager();
for (final String pkgName : mListPackageName) {
return isPackageInstalled(pkgName, pm);
}
return false;
}
private static boolean isPackageInstalled(final String packageName, final PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
PHP is server-side language, so you can not refresh the page with PHP, but JavaScript is the best option to refresh the page:
location.reload();
The visit Location reload() method.
Used these lines:
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
the length of array accounts is always 0.
spinner code:
<TextView
android:id="@+id/spinner"
android:gravity="bottom"
android:layout_marginTop="16dp"
android:background="@drawable/spinner_selector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingLeft="16dp"
android:textSize="16sp"
android:text="TextView" />
spinner_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/spinner_enable" android:state_enabled="true" android:state_pressed="false" /> <!-- enable -->
<item android:drawable="@drawable/spinner_clicked" android:state_pressed="true" android:state_enabled="true" />
<item android:drawable="@drawable/spinner_disable" android:state_enabled="false" /> <!-- disable -->
</selector>
spinner_disable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#ddf" />
<padding android:bottom="1dp" />
</shape>
</item>
<item android:bottom="1dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:right="8dp">
<layer-list>
<item
android:width="12dp"
android:height="12dp"
android:bottom="10dp"
android:gravity="center">
<rotate
android:fromDegrees="45"
android:toDegrees="45">
<shape android:shape="rectangle">
<solid android:color="#ddf" />
<stroke
android:width="1dp"
android:color="#aaaaaa" />
</shape>
</rotate>
</item>
<item
android:width="30dp"
android:height="10dp"
android:bottom="21dp"
android:gravity="center">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
</shape>
</item>
</layer-list>
</item>
</layer-list>
spinner_clicked.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="1dp" />
</shape>
</item>
<item android:bottom="1dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:right="8dp">
<layer-list>
<item
android:width="12dp"
android:height="12dp"
android:bottom="10dp"
android:gravity="center">
<rotate
android:fromDegrees="45"
android:toDegrees="45">
<shape android:shape="rectangle">
<solid android:color="#00f" />
<stroke
android:width="1dp"
android:color="#aaaaaa" />
</shape>
</rotate>
</item>
<item
android:width="30dp"
android:height="10dp"
android:bottom="21dp"
android:gravity="center">
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
</shape>
</item>
</layer-list>
</item>
</layer-list>
spinner_enable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="1dp" />
</shape>
</item>
<item android:bottom="1dp">
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
</shape>
</item>
<item
android:gravity="center_vertical|right"
android:right="8dp">
<layer-list>
<item
android:width="12dp"
android:height="12dp"
android:bottom="10dp"
android:gravity="center">
<rotate
android:fromDegrees="45"
android:toDegrees="45">
<shape android:shape="rectangle">
<solid android:color="#00f" />
<stroke
android:width="1dp"
android:color="#aaaaaa" />
</shape>
</rotate>
</item>
<item
android:width="30dp"
android:height="10dp"
android:bottom="21dp"
android:gravity="center">
<shape android:shape="rectangle">
<solid android:color="#BBDEFB" />
</shape>
</item>
</layer-list>
</item>
</layer-list>
this my how I solved you shoud give return false;
$(document).on('keypress',function(e) {
if(e.which == 13) {
$('#sub_btn').trigger('click');
alert('You pressed a "enter" key in somewhere');
return false;
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
<div class="modal-header">
<button type="button" class="close" id="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Subscribe to our Technical Analysis</h4>
</div>
<div class="modal-body">
<p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
<div class="input-group">
<input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
</div>
<span id="save-error"></span>
</div>
<div class="modal-footer">
<div class="input-group-append">
<input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
</div>
</div>
</form>
_x000D_
`
int *array = new int[n];
It declares a pointer to a dynamic array of type int
and size n
.
A little more detailed answer: new
allocates memory of size equal to sizeof(int) * n
bytes and return the memory which is stored by the variable array
. Also, since the memory is dynamically allocated using new
, you've to deallocate it manually by writing (when you don't need anymore, of course):
delete []array;
Otherwise, your program will leak memory of at least sizeof(int) * n
bytes (possibly more, depending on the allocation strategy used by the implementation).
This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.
See in addition this blogpost: http://blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html
I find the m2eclipse plugin to be more useful. This provides nice tools like the POM editor and creating a Maven project from within Eclipse.
I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:
"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."
So, for example, this function definition:
def geocode(s, api_key='', geocoder='google', list_geocoders=False):
is turned into this optparse help text:
Options:
-h, --help show this help message and exit
-l, --list-geocoders
-a API_KEY, --api-key=API_KEY
-g GEOCODER, --geocoder=GEOCODER
I think sometimes stupid mistakes can give us this error.
<div id="#main"> <--- id with hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
To
<div id="main"> <--- id without hashtag
<div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>
private <A, B> Map<B, A> invertMap(Map<A, B> map) {
Map<B, A> reverseMap = new HashMap<>();
for (Map.Entry<A, B> entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
return reverseMap;
}
It's important to remember that put
replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.
To remove disabled attribute use,
$("#elementID").removeAttr('disabled');
and to add disabled attribute use,
$("#elementID").prop("disabled", true);
Enjoy :)
Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.
If you don't believe me look at the String.Concat
definition using reflector.
The last lines are...
int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;
As you can see the FastAllocateString
returns an empty but allocated string and then it is modified by FillStringChecked
Actually the FastAllocateString
is an extern method and the FillStringChecked
is unsafe so it uses pointers to copy the bytes.
Maybe there are better examples but this is the one I have found so far.
If the type implements IDisposable, it automatically disposes that type.
Given:
public class SomeDisposableType : IDisposable
{
...implmentation details...
}
These are equivalent:
SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}
using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}
The second is easier to read and maintain.
As of OpenCV 2.2.0, the package name for the Python bindings is "cv".The old bindings named "opencv" are not maintained any longer. You might have to adjust your code. See http://opencv.willowgarage.com/wiki/PythonInterface.
The official OpenCV installer does not install the Python bindings into your Python directory. There should be a Python2.7 directory inside your OpenCV 2.2.0 installation directory. Copy the whole Lib folder from OpenCV\Python2.7\ to C:\Python27\ and make sure your OpenCV\bin directory is in the Windows DLL search path.
Alternatively use the opencv-python installers at http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv.
As an alternative you can also query the information_schema
database and retrieve the data from the global_variables
(and global_status
of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.
For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size
in bytes and megabytes:
SELECT
variable_name,
variable_value AS innodb_log_buffer_size_bytes,
ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE 'innodb_log_buffer_size';
As a result you get:
+------------------------+------------------------------+---------------------------+
| variable_name | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456 | 256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
@Erik's answer didn't fly for me.
Following did:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus doing this manually under field I had to add error message container
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
Hope this saves you some time.
jQuery by default assumes UTF-8, to change this default do:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$.ajaxSettings.mimeType="*/*; charset=ISO-8859-15";// set you charset
</script>
This works fine for me!... ;))...
if [ $var1 != $var2 ]
then
echo "$var1"
else
echo "$var2"
fi
If you do <form action="identification" >
for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post">
and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........
in swift 3.0 this is how we can convert Int
to String
and String
to Int
//convert Integer to String in Swift 3.0
let theIntegerValue :Int = 123 // this can be var also
let theStringValue :String = String(theIntegerValue)
//convert String to Integere in Swift 3.0
let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
.desc()
function in your query just like thisquery = (model.Session.query(model.Entry)
.join(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(id=c.row.id)
.order_by(model.Entry.amount.desc())
)
This will order by amount in descending order or
query = session.query(
model.Entry
).join(
model.ClassificationItem
).join(
model.EnumerationValue
).filter_by(
id=c.row.id
).order_by(
model.Entry.amount.desc()
)
)
from sqlalchemy import desc
query = session.query(
model.Entry
).join(
model.ClassificationItem
).join(
model.EnumerationValue
).filter_by(
id=c.row.id
).order_by(
desc(model.Entry.amount)
)
)
sqlalchemy.sql.expression.desc(column) Produce a descending ORDER BY clause element.
e.g.:
from sqlalchemy import desc stmt = select([users_table]).order_by(desc(users_table.c.name))
will produce SQL as:
SELECT id, name FROM user ORDER BY name DESC
The desc() function is a standalone version of the ColumnElement.desc() method available on all SQL expressions, e.g.:
stmt = select([users_table]).order_by(users_table.c.name.desc())
Parameters column – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation.
See also
asc()
nullsfirst()
nullslast()
Select.order_by()
For VB.NET, you can place the following before your web request:
Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12
This solved my security issue on .NET 3.5.
Here is the example from the SocketServer documentation which would make an excellent starting point
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Try it from a terminal like this
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.
You'll probably need to use A Forking or Threading Mixin too
I had the exact same error and it was so annoying to see the alert every time I stared Android Studio. I tried the solution mentioned above including invalidating cache, restart etc, nothing made it go away.
In my case, we had a module that was deleted from source and the reference also removed from settings.gradle
. Turns out, .idea/modules.xml
was still referencing that module.
All I needed to do was remove that line from <modules>
in .idea/modules.xml
and it made it all go away.
I tried all of the above methods. I wasn't running Avast, tried Oracle VirtualBox, and then tried to install the HAXM software from the intel link.
None of these worked, I was still getting the same error.
What did work (and I'm not sure why) was to install another Android simulator that is available from Genymotion. I was actually very surprised that it did work because during the process of creating the Android virtual device, I received an error that the Hypervisor was not turned on. However, setup continued and the Genymotion simulator runs successfully. Genymotion is free for personal use.
This was on a Lenova T430 laptop.
Another way to define a 2-d vector is to declare a vector of pair's.
vector < pair<int,int> > v;
**To insert values**
cin >> x >>y;
v.push_back(make_pair(x,y));
**Retrieve Values**
i=0 to size(v)
x=v[i].first;
y=v[i].second;
For 3-d vectors take a look at tuple and make_tuple.
This is a question of style (or preference) since the interpreter does not care. Personally I would try not to make the final statement of a function which returns a value at an indent level other than the function base. The else in example 1 obscures, if only slightly, where the end of the function is.
By preference I use:
return A+1 if (A > B) else A-1
As it obeys both the good convention of having a single return statement as the last statement in the function (as already mentioned) and the good functional programming paradigm of avoiding imperative style intermediate results.
For more complex functions I prefer to break the function into multiple sub-functions to avoid premature returns if possible. Otherwise I revert to using an imperative style variable called rval. I try not to use multiple return statements unless the function is trivial or the return statement before the end is as a result of an error. Returning prematurely highlights the fact that you cannot go on. For complex functions that are designed to branch off into multiple subfunctions I try to code them as case statements (driven by a dict for instance).
Some posters have mentioned speed of operation. Speed of Run-time is secondary for me since if you need speed of execution Python is not the best language to use. I use Python as its the efficiency of coding (i.e. writing error free code) that matters to me.
$cfg['Servers'][$i]['AllowNoPassword'] = false;
After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?
//Check to see if we get rows back, if we do just bind.
if (dtFunding.Rows.Count != 0)
{
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
}
else
{
//Other wise add a emtpy "New Row" to the datatable and then hide it after binding.
dtFunding.Rows.Add(dtFunding.NewRow());
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
grdFunding.Rows[0].Visible = false;
}
I think it's not possible. Though I found an app from google play called PHONE MUSIC which claims to : "Thus whenver someone puts you on hold just hit the hovering musical note and start playing music. Or play music while someones on the phone with you. "
I just ran into the same problem, but I manage to have my query working in SQLite like this:
@shows = Show.order("datetime(date) ASC, attending DESC")
I hope this might help someone save some time
When running the python file, you would normally do this
python app.py
This will display these messages.
To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.
export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run
This should work perfectlly. :) :)
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be
With New FileSystemObject
If .FileExists(yourFilePath) Then
.DeleteFile yourFilepath
End If
End With
Same effect but fewer (well, none at all) variable declarations.
The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).
My problem was the same as one commenter above. I had to change the binary parser to the correct one (PE for windows, ELF for Linux, mach for mac)
I fixed this by adding another div in the one that overflows. Then you compare the heights of the 2 divs.
<div class="AAAA overflow-hidden" style="height: 20px;" >
<div class="BBBB" >
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
and the js
if ($('.AAAA').height() < $('.BBBB').height()) {
console.log('we have overflow')
} else {
console.log('NO overflow')
}
This looks easier...
Install
npm i graph-fs
Use
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
directory.exists; // <--
You can do this pretty easily using Docker, so no extra libs required. Just run this command:
docker run --rm -it -v "$GOPATH":/go -w /go/src/github.com/iron-io/ironcli golang:1.4.2-cross sh -c '
for GOOS in darwin linux windows; do
for GOARCH in 386 amd64; do
echo "Building $GOOS-$GOARCH"
export GOOS=$GOOS
export GOARCH=$GOARCH
go build -o bin/ironcli-$GOOS-$GOARCH
done
done
'
You can find more details in this post: https://medium.com/iron-io-blog/how-to-cross-compile-go-programs-using-docker-beaa102a316d
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
I don't know why but you have to add a setTimeout with at least for me 200ms:
setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );
Tested with Firefox / Chrome / Edge.
I got this issue while deploying on Heroku. The problem is on Heroku the don't include the devDependencies on its own. To fix this issue, simply run the command in the terminal:
heroku config:set NPM_CONFIG_PRODUCTION=false
Make sure to include nodemon in your devDependencies
"devDependencies": {
"nodemon": "^2.0.6"
}
I would suggest uninstalling nodemon and then reinstalling it
https://www.npmjs.com/package/nodemon
Or try changing the script
"scripts": {
"start": "nodemon fileName.js",
"start:dev": "nodemon fileName.js"
}
Hope it would help :)
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){_x000D_
var dfd = new $.Deferred();_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 1"); _x000D_
method2(dfd); _x000D_
}, 5000);_x000D_
return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 2"); _x000D_
method3(dfd); _x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 3"); _x000D_
dfd.resolve();_x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method4(){ _x000D_
console.log("Inside Method - 4"); _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
To find them, you can use this
;WITH cte AS
(
SELECT 0 AS CharCode
UNION ALL
SELECT CharCode + 1 FROM cte WHERE CharCode <31
)
SELECT
*
FROM
mytable T
cross join cte
WHERE
EXISTS (SELECT *
FROM mytable Tx
WHERE Tx.PKCol = T.PKCol
AND
Tx.MyField LIKE '%' + CHAR(cte.CharCode) + '%'
)
Replacing the EXISTS with a JOIN will allow you to REPLACE them, but you'll get multiple rows... I can't think of a way around that...
You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select
Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.
= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}
The magic method __getitem__
is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.
Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__
method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.
import copy
# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1
class Person(object):
def __init__(self, name, age, dob):
self.name = name
self.age = age
self.dob = dob
def __getitem__(self, indx):
print ("Calling __getitem__")
p = copy.copy(self)
p.name = p.name.split(" ")[indx]
p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
return p
Suppose one user input is as follows:
p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
With the help of __getitem__
method, the user can access the indexed attributes. e.g.,
print p[0].name # print first (or last) name
print p[Y].dob # print (Date or Month or ) Year of the 'date of birth'
Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io
Or package name may be something like docker-ce
.
Try running
dpkg -l | grep -i docker
to identify what installed package you have
So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io
it would be:
sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean
It adds:
The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:
sudo rm -rf /var/lib/docker
Remove docker from apparmor.d:
sudo rm /etc/apparmor.d/docker
Remove docker group:
sudo groupdel docker
Can't you do it inline?
var sizes = subject.Split(new char[] { ' ', '\t' });
Otherwise, if you do this exact thing often, you could always create constant or something containing that char array.
As others have noted you can according to the documentation also use null
or an empty array. When you do that it will use whitespace characters automatically.
var sizes = subject.Split(null);
I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
You probably can combine the two tests on the second line into one with:
if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a
' and do recommend using separate simple tests combined with &&
. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).
You can find the details of these, and other related shell parameter expansions, the test
or [
command and conditional expressions in the Bash manual.
I was recently asked by email about this answer with the question:
You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
Wouldn't this accomplish the same?
if [ -z "${VAR}" ]; then echo VAR is not set at all; fi
Fair question - the answer is 'No, your simpler alternative does not do the same thing'.
Suppose I write this before your test:
VAR=
Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ]; then echo MP:2 VAR is not set at all; fi
)
The output is:
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value}
and ${VAR:=value}
notations make. Ditto for ${VAR-value}
and ${VAR:-value}
, and ${VAR+value}
and ${VAR:+value}
, and so on.
As Gili points out in his answer, if you run bash
with the set -o nounset
option, then the basic answer above fails with unbound variable
. It is easily remedied:
if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi
Or you could cancel the set -o nounset
option with set +u
(set -u
being equivalent to set -o nounset
).
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
Cross apply works well with an XML field as well. If you wish to select node values in combination with other fields.
For example, if you have a table containing some xml
<root> <subnode1> <some_node value="1" /> <some_node value="2" /> <some_node value="3" /> <some_node value="4" /> </subnode1> </root>
Using the query
SELECT
id as [xt_id]
,xmlfield.value('(/root/@attribute)[1]', 'varchar(50)') root_attribute_value
,node_attribute_value = [some_node].value('@value', 'int')
,lt.lt_name
FROM dbo.table_with_xml xt
CROSS APPLY xmlfield.nodes('/root/subnode1/some_node') as g ([some_node])
LEFT OUTER JOIN dbo.lookup_table lt
ON [some_node].value('@value', 'int') = lt.lt_id
Will return a result
xt_id root_attribute_value node_attribute_value lt_name
----------------------------------------------------------------------
1 test1 1 Benefits
1 test1 4 FINRPTCOMPANY
public static class MyGlobals
{
public static string Global1 = "Hello";
public static string Global2 = "World";
}
public class Foo
{
private void Method1()
{
string example = MyGlobals.Global1;
//etc
}
}
The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.
I had to solve it as follows today: Project A was in bitbucket and Project B was in code commit .. both are the same projects but had to merge changes from A to B. (The trick is to create the same name branch in Project A, same as in Project B)
I think your confusion is with C# properties vs. fields/variables. In C# you cannot define abstract fields, even in an abstract class. You can, however, define abstract properties as these are effectively methods (e.g. compiled to get_TAG()
and set_TAG(...)
).
As some have reminded, you should never have public fields/variables in your classes, even in C#. Several answers have hinted at what I would recommend, but have not made it clear. You should translate your idea into Java as a JavaBean property, using getTAG(). Then your sub-classes will have to implement this (I also have written a project with table classes that do this).
So you can have an abstract class defined like this...
public abstract class AbstractTable {
public abstract String getTag();
public abstract void init();
...
}
Then, in any concrete subclasses you would need to define a static final variable (constant) and return that from the getTag()
, something like this:
public class SalesTable extends AbstractTable {
private static final String TABLE_NAME = "Sales";
public String getTag() {
return TABLE_NAME;
}
public void init() {
...
String tableName = getTag();
...
}
}
EDIT:
You cannot override inherited fields (in either C# or Java). Nor can you override static members, whether they are fields or methods. So this also is the best solution for that. I changed my init method example above to show how this would be used - again, think of the getXXX method as a property.
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
Or you could do it the evil way.
var a = [1,2,3,4,5,6,7,8,9];
sum = eval(a.join("+"));
;)
Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume
statement to clear the Error Handler. The Resume
also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.
Block 3 fails because there is no Resume
statement so any attempt at error handling after that will fail.
Every error handler must be ended by exiting the procedure or a Resume
statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.
But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.
Sub InLineErrorHandling()
'code without error handling
BeginTry1:
'activate inline error handler
On Error GoTo ErrHandler1
'code block that may result in an error
Dim a As String: a = "Abc"
Dim c As Integer: c = a 'type mismatch
ErrHandler1:
'handle the error
If Err.Number <> 0 Then
'the error handler has deactivated the previous error handler
MsgBox (Err.Description)
'Resume (or exit procedure) is the only way to get out of an error handling block
'otherwise the following On Error statements will have no effect
'CAUTION: it also reactivates the previous error handler
Resume EndTry1
End If
EndTry1:
'CAUTION: since the Resume statement reactivates the previous error handler
'you must ALWAYS use an On Error GoTo statement here
'because another error here would cause an endless loop
'use On Error GoTo 0 or On Error GoTo <Label>
On Error GoTo 0
'more code with or without error handling
End Sub
Sources:
The key to making this work is to use a Resume
statement immediately followed by another On Error
statement. The Resume
is within the error handler and diverts code to the EndTry1
label. You must immediately set another On Error
statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.
To avoid using the previous error handler again you need to set On Error
to a new error handler or simply use On Error Goto 0
to cancel all error handling.
In case if you are looking for one liner
For primitives
this.items.indexOf(item) === -1) && this.items.push(item);
For objects
this.items.findIndex((item: ItemType) => item.var === checkValue) === -1 && this.items.push(item);
Easily you can do it.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Credits: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e
Swift 4, 4.2 and 5
[![@IBOutlet var detailTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
detailTextView.delegate = self
}
extension ContactUsViewController : UITextViewDelegate {
public func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == "Write your message here..." {
detailTextView.text = ""
detailTextView.textColor = UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.86)
}
textView.becomeFirstResponder()
}
public func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == "" {
detailTextView.text = "Write your message here..."
detailTextView.textColor = UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.30)
}
textView.resignFirstResponder()
}
[![}][1]][1]
So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.
find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.
For swift 3 purposes
theImageView.image = theImageView.image!.withRenderingMode(.alwaysTemplate)
theImageView.tintColor = UIColor.red
Sending email programmatically with Kotlin.
I also found this list of email POP services really helpful:
How to use:
val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
val to = listOf(InternetAddress("[email protected]"))
val from = InternetAddress("[email protected]")
val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
val emailService = EmailService("yourSmtpServer", 587)
GlobalScope.launch { // or however you do background threads
emailService.send(email)
}
The code:
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
class EmailService(private var server: String, private var port: Int) {
data class Email(
val auth: Authenticator,
val toList: List<InternetAddress>,
val from: Address,
val subject: String,
val body: String
)
class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(username, password)
}
}
fun send(email: Email) {
val props = Properties()
props["mail.smtp.auth"] = "true"
props["mail.user"] = email.from
props["mail.smtp.host"] = server
props["mail.smtp.port"] = port
props["mail.smtp.starttls.enable"] = "true"
props["mail.smtp.ssl.trust"] = server
props["mail.mime.charset"] = "UTF-8"
val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
msg.setFrom(email.from)
msg.sentDate = Calendar.getInstance().time
msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
// msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
// msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
msg.replyTo = arrayOf(email.from)
msg.addHeader("X-Mailer", CLIENT_NAME)
msg.addHeader("Precedence", "bulk")
msg.subject = email.subject
msg.setContent(MimeMultipart().apply {
addBodyPart(MimeBodyPart().apply {
setText(email.body, "iso-8859-1")
//setContent(email.htmlBody, "text/html; charset=UTF-8")
})
})
Transport.send(msg)
}
companion object {
const val CLIENT_NAME = "Android StackOverflow programmatic email"
}
}
Gradle:
dependencies {
implementation 'com.sun.mail:android-mail:1.6.4'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}
AndroidManifest:
<uses-permission name="android.permission.INTERNET" />
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
I have a generic method that would take any types include float, and it's been unit-tested, hope it helps:
/// <summary>
/// Breaks the list into groups with each group containing no more than the specified group size
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="values">The values.</param>
/// <param name="groupSize">Size of the group.</param>
/// <returns></returns>
public static List<List<T>> SplitList<T>(IEnumerable<T> values, int groupSize, int? maxCount = null)
{
List<List<T>> result = new List<List<T>>();
// Quick and special scenario
if (values.Count() <= groupSize)
{
result.Add(values.ToList());
}
else
{
List<T> valueList = values.ToList();
int startIndex = 0;
int count = valueList.Count;
int elementCount = 0;
while (startIndex < count && (!maxCount.HasValue || (maxCount.HasValue && startIndex < maxCount)))
{
elementCount = (startIndex + groupSize > count) ? count - startIndex : groupSize;
result.Add(valueList.GetRange(startIndex, elementCount));
startIndex += elementCount;
}
}
return result;
}
getDimensions(id) {
var obj = questions.filter(function(node) {
return node.id==id;
});
return obj;
}
The solution:
error : The requested URL returned error : 503 while Accessing
The error might be resolved by deleting the existing git folder.
If the service is running via brew, you can stop it using the following command:
brew services stop mongodb
I've had the same problem before recognized that I've put the code after closing the body tag. After moving it into tag, it's OK now
<body>
$(document).ready(function(){
$('.multiple-items').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 3
});
});
</body>
You're confusing the braces. Do it like this:
target.write("%s \n %s \n %s \n" % (line1, line2, line3))
Or even better, use writelines
:
target.writelines([line1, line2, line3])
I'll add the data.table
version for anyone else Googling it (i.e., @BondedDust's solution translated to data.table
and pared down a tad):
library(data.table)
setDT(temp)
temp[ , quartile := cut(value,
breaks = quantile(value, probs = 0:4/4),
labels = 1:4, right = FALSE)]
Which is much better (cleaner, faster) than what I had been doing:
temp[ , quartile :=
as.factor(ifelse(value < quantile(value, .25), 1,
ifelse(value < quantile(value, .5), 2,
ifelse(value < quantile(value, .75), 3, 4))]
Note, however, that this approach requires the quantiles to be distinct, e.g. it will fail on rep(0:1, c(100, 1))
; what to do in this case is open ended so I leave it up to you.
A combination of line styles, markers, and qualitative colors from matplotlib
:
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
UPDATE: Supporting not only ListedColormap
, but also LinearSegmentedColormap
import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})
Assuming headers are on the first row of the sheet starting at A1, and you know how many of them there are, this was my solution:
$header = array(
'Header 1',
'Header 2'
);
$objPHPExcel = new PHPExcel();
$objPHPExcelSheet = $objPHPExcel->getSheet(0);
$objPHPExcelSheet->fromArray($header, NULL);
$first_letter = PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = PHPExcel_Cell::stringFromColumnIndex(count($header)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$objPHPExcelSheet->getStyle($header_range)->getFont()->setBold(true);
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
Base on this I was able to solve this by changing the constructor of XmlSerializer
I was using instead of changing the classes.
Instead of using something like this (suggested in the other answers):
[XmlInclude(typeof(Derived))]
public class Base {}
public class Derived : Base {}
public void Serialize()
{
TextWriter writer = new StreamWriter(SchedulePath);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>));
xmlSerializer.Serialize(writer, data);
writer.Close();
}
I did this:
public class Base {}
public class Derived : Base {}
public void Serialize()
{
TextWriter writer = new StreamWriter(SchedulePath);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>), new[] { typeof(Derived) });
xmlSerializer.Serialize(writer, data);
writer.Close();
}
A general purpose set of functions to render any python data structure (dicts and lists nested together) as HTML.
from IPython.display import HTML, display
def _render_list_html(l):
o = []
for e in l:
o.append('<li>%s</li>' % _render_as_html(e))
return '<ol>%s</ol>' % ''.join(o)
def _render_dict_html(d):
o = []
for k, v in d.items():
o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v)))
return '<table>%s</table>' % ''.join(o)
def _render_as_html(e):
o = []
if isinstance(e, list):
o.append(_render_list_html(e))
elif isinstance(e, dict):
o.append(_render_dict_html(e))
else:
o.append(str(e))
return '<html><body>%s</body></html>' % ''.join(o)
def render_as_html(e):
display(HTML(_render_as_html(e)))
You need to do something with the return value...
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] B = numbers();
System.out.println(Arrays.toString(B));
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store.
select cast (10 as number(1,2)) from dual
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
select cast (15.33 as number(3,2)) from dual
*
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column
Anything at the lower end gets truncated (silently)
select cast (5.33333333 as number(3,2)) from dual;
CAST(5.33333333ASNUMBER(3,2))
-----------------------------
5.33
Since PostgreSQL JDBC driver version 8.4-701 the PreparedStatement#getGeneratedKeys()
is finally fully functional. We use it here almost one year in production to our full satisfaction.
In "plain JDBC" the PreparedStatement
needs to be created as follows to make it to return the keys:
statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
You can download the current JDBC driver version here (which is at the moment still 8.4-701).
You see the same symptoms if you are working in Xamarin Studio and you are referencing a portable library for which you need to do the PCL bait and switch trick for. This occurs if the referencing project is out of date with respect to the referenced library. I found that I had updated my common library to a newer framework, updated my packages but hadn't updated my iOS packages to match. Updating the packages solved this error for me.
PROMPT> gem uninstall cocoapods
Select gem to uninstall:
1. cocoapods-0.32.1
2. cocoapods-0.33.1
3. cocoapods-0.36.0.beta.2
4. cocoapods-0.38.2
5. cocoapods-0.39.0
6. cocoapods-1.0.0
7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>
Drive letters can be used in the target like
scp some_file user@host:/c/temp
where c
is the drive letter. It's treated like a directory.
Maybe this works on the source, too.
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function hello() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onclick="hello()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
Use the keys
method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]
it suggests that you fail to link the explicitly instantiated basetype public gameCore (whereas the header file forward declares it).
Since we know nothing about your build config/library dependencies, we can't really tell which link flags/source files are missing, but I hope the hint alone helps you fix ti.
Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.
A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt
and jshint
.
These lines add more meaning
Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.
Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:
There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.
Please Note that grunt plugin is also an npm package.
Question-1
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.
Question-2
When should I ever install packages explicitly like that without adding them to the file that manages dependencies
It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request
, then you have two options:
OR
npm install --save request
--save
options adds the dependency to package.json file as well. If you don't specify --save
option, it will only download the package but the json file will be unaffected.
You can do this either way, there will not be a substantial difference.
Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:
Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)
Sign the application using your keystore and the jarsigner tool (follow below steps):
Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"
Now enter belwo command in cmd:
jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias
It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:
jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk
It should come back with: jar verified.
Method 2
If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.
These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.
In CentOS7,I try this: yum install php-mysql
, then edit php.ini
If you want to fill your super view then I suggest the swifty way:
view.translatesAutoresizingMaskIntoConstraints = false
let attributes: [NSLayoutAttribute] = [.top, .bottom, .right, .left]
NSLayoutConstraint.activate(attributes.map {
NSLayoutConstraint(item: view, attribute: $0, relatedBy: .equal, toItem: view.superview, attribute: $0, multiplier: 1, constant: 0)
})
Other wise if you need non equal constraints check out NSLayoutAnchor as of iOS 9. Its often much easier to read that using NSLayoutConstraint directly:
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: view.superview!.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: view.superview!.bottomAnchor).isActive = true
view.leadingAnchor.constraint(equalTo: view.superview!.leadingAnchor, constant: 10).isActive = true
view.trailingAnchor.constraint(equalTo: view.superview!.trailingAnchor, constant: 10).isActive = true
If you happen to be working with a application which has a mix of Windows Forms and WPF you might have the additional complication of trying to convert a System.Drawing.Color to a System.Windows.Media.Color. I'm not sure if there is an easier way to do this, but I did it this way:
System.Drawing.Color MyColor = System.Drawing.Color.Red;
System.Windows.Media.Color = ConvertColorType(MyColor);
System.Windows.Media.Color ConvertColorType(System.Drawing.Color color)
{
byte AVal = color.A;
byte RVal = color.R;
byte GVal = color.G;
byte BVal = color.B;
return System.Media.Color.FromArgb(AVal, RVal, GVal, BVal);
}
Then you can use one of the techniques mentioned previously to convert to a Brush.
s.erase(std::remove(s.begin(), s.end(), '\n'), s.end());
Add "ref" to h1 tag :
<h1 ref="source">Hey there.</h1>
and
const { source } = this.props;
change to const { source } = this.refs;
The json
module is a better solution whenever there is a stringified list of dictionaries. The json.loads(your_data)
function can be used to convert it to a list.
>>> import json
>>> x = '[ "A","B","C" , " D"]'
>>> json.loads(x)
['A', 'B', 'C', ' D']
Similarly
>>> x = '[ "A","B","C" , {"D":"E"}]'
>>> json.loads(x)
['A', 'B', 'C', {'D': 'E'}]
Take for example a game where lots of cars are spawned.. each belongs to the class CCar. When a car is instantiated, it makes a call to
[CCar registerCar:self]
So the CCar class, can make a list of every CCar instantiated.
Let's say the user finishes a level, and wants to remove all cars... you could either:
1- Go through a list of every CCar you created manually, and do whicheverCar.remove();
or
2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();
Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup. Without the class method, you might have to do something like
fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();
With the class method, you could get away with [FontHandler getDefaultFontSize]
.
As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.
e.g. myString.removeVowels()
and String.removeVowels(myString)
(in ObjC that would be [String removeVowels:myString]
).
In this case the instance likely calls the class method, so both are available. i.e.
public function toLower():String{
return String.toLower();
}
public static function toLower( String inString):String{
//do stuff to string..
return newString;
}
basically, myString.toLower()
calls [String toLower:ownValue]
There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.
Here is a simple way using the date function:
select *
from hockey_stats
where date(game_date) between date('2012-11-03') and date('2012-11-05')
order by game_date desc
By definition, an element only has height if it's visible.
Just curious: why do you need the height of a hidden element?
One alternative is to effectively hide an element by putting it behind (using z-index) an overlay of some kind).
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
This is what I ended up doing:
CoffeeScript:
$("input").focus ->
$("html, body").css "overflow-y","hidden"
$(document).on "scroll.stopped touchmove.stopped mousewheel.stopped", (event) ->
event.preventDefault()
$("input").blur ->
$("html, body").css "overflow-y","auto"
$(document).off "scroll.stopped touchmove.stopped mousewheel.stopped"
Javascript:
$("input").focus(function() {
$("html, body").css("overflow-y", "hidden");
$(document).on("scroll.stopped touchmove.stopped mousewheel.stopped", function(event) {
return event.preventDefault();
});
});
$("input").blur(function() {
$("html, body").css("overflow-y", "auto");
$(document).off("scroll.stopped touchmove.stopped mousewheel.stopped");
});
You can declare like this
CREATE PROCEDURE MyProcName
@Parameter1 INT = 1,
@Parameter2 VARCHAR (100) = 'StringValue',
@Parameter3 VARCHAR (100) = NULL
AS
/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
/* whatever code you desire for a missing parameter*/
INSERT INTO ........
END
/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter
The ability to search commits has recently been added to GitHub.
To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master
), or the "Issues" tab to see pull requests containing the commit.
To be more explicit you can add the hash:
prefix to the search, but it's not really necessary.
There is also a REST API (at the time of writing it is still in preview).
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
So apparently, all I needed was the "build-essential" package, then to run autoconf
first, which made the Makefile.pre.in
, then the ./configure
then the make
which works perfectly...
You can try something like this.
<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>
Its working fine for me.
For what it's worth, here's a list of all .NET attributes. There are several hundred.
I don't know about anyone else but I have some serious RTFM to do!
You can use $http.get()
method to fetch your JSON
file. Then assign response data to a $scope
object. In HTML
to create table use ng-repeat for $scope object. ng-repeat
will loop the rows in-side this loop you can bind data to columns dynamically.
I have checked your code and you have created static table
<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>
so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..
I found that when I made my binding more specific, it began to work on iOS. I had:
$(document).on('click tap', 'span.clickable', function(e){ ... });
When I changed it to:
$("div.content").on('click tap', 'span.clickable', function(e){ ... });
iOS began responding.
I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components html.
I followed some of the solutions proposed on this page but any of them worked for me, at least not completely.
What did actually solve my error was to write the below code snippet inside the father html tag of the elements .
I was binding to the variable.
Code:
*ngIf="variable-name"
The error was caused, apparently by the project trying to render the page, apparently at the moment of evaluating the variable, the project just could no find its value. With the above code snippet you make sure that before rendering the page you ask if the variable has being initialized.
This is my component.ts code:
import { Component, OnInit } from '@angular/core';
import { InvitationService } from 'src/app/service/invitation.service';
import { BusinessService } from 'src/app/service/business.service';
import { Invitation } from 'src/app/_models/invitation';
import { forEach } from '@angular/router/src/utils/collection';
@Component({
selector: 'app-invitation-details',
templateUrl: './invitation-details.component.html',
styleUrls: ['./invitation-details.component.scss']
})
export class InvitationDetailsComponent implements OnInit {
invitationsList: any;
currentInvitation: any;
business: any;
invitationId: number;
invitation: Invitation;
constructor(private InvitationService: InvitationService, private BusinessService:
BusinessService) {
this.invitationId = 1; //prueba temporal con invitacion 1
this.getInvitations();
this.getInvitationById(this.invitationId);
}
ngOnInit() {
}
getInvitations() {
this.InvitationService.getAllInvitation().subscribe(result => {
this.invitationsList = result;
console.log(result);
}, error => {
console.log(JSON.stringify(error));
});
}
getInvitationById(invitationId:number){
this.InvitationService.getInvitationById(invitationId).subscribe(result => {
this.currentInvitation = result;
console.log(result);
//this.business=this.currentInvitation['business'];
//console.log(this.currentInvitation['business']);
}, error => {
console.log(JSON.stringify(error));
});
}
...
Here is my html markup:
<div class="container-fluid mt--7">
<div class="row">
<div class="container col-xl-10 col-lg-8">
<div class="card card-stats ">
<div class="card-body container-fluid form-check-inline"
*ngIf="currentInvitation">
<div class="col-4">
...
I hope this can be helpful.
You can use CSS3 media query for this. Write like this:
CSS
.wrapper {
border : 2px solid #000;
overflow:hidden;
}
.wrapper div {
min-height: 200px;
padding: 10px;
}
#one {
background-color: gray;
float:left;
margin-right:20px;
width:140px;
border-right:2px solid #000;
}
#two {
background-color: white;
overflow:hidden;
margin:10px;
border:2px dashed #ccc;
min-height:170px;
}
@media screen and (max-width: 400px) {
#one {
float: none;
margin-right:0;
width:auto;
border:0;
border-bottom:2px solid #000;
}
}
HTML
<div class="wrapper">
<div id="one">one</div>
<div id="two">two</div>
</div>
Check this for more http://jsfiddle.net/cUCvY/1/
Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.
Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.
Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.
Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.
I'll not address the order of tests, sorry. Others already did it. Also, if you know about "ordered tests" - well, this is MS VS's response to the problem. I know that those ordered-tests are no fun. But they thought it will be "it" and there's really nothing more in MSTest about that.
I write about one of your assumptions:
as there is no way to tear down the static class.
Unless your static class represents some process-wide external state external to your code (like ie. the state of an unmanaged native DLL library thats P/Invoked by the rest of your code), your assumption that there is no way
is not true.
If your static class refers to this, then sorry, you are perfectly right, the rest of this anwer is irrelevant. Still, as you didn't say that, I assume your code is "managed".
Think and check the AppDomain
thingy. Rarely it is needed, but this is exactly the case when you'd probably like to use them.
You can create a new AppDomain, and instantiate the test there, and run the test method there. Static data used by managed code will isolated there and upon completion, you will be able to unload the AppDomain and all the data, statics included, will evaporate. Then, next test would initialize another appdomain, and so on.
This will work unless you have external state that you must track. AppDomains only isolate the managed memory. Any native DLL will still be load per-process and their state will be shared by all AppDomains.
Also, creating/tearing down the appdomains will, well, slow down the tests. Also, you may have problems with assembly resolution in the child appdomain, but they are solvable with reasonable amount of reusable code.
Also, you may have small problems with passing test data to - and back from - the child AppDomain. Objects passed will either have to be serializable in some way, or be MarshalByRef
or etc. Talking cross-domain is almost like IPC.
However, take care here, it will be 100% managed talking. If you take some extra care and add a little work to the AppDomain setup, you will be able to even pass delegates and run them in the target domain. Then, instead of making some hairy cross-domain setup, you can wrap your tests with to something like:
void testmethod()
{
TestAppDomainHelper.Run( () =>
{
// your test code
});
}
or even
[IsolatedAppDomain]
void testmethod()
{
// your test code
}
if your test framework supports creating such wrappers/extensions. After some initial research and work, using them is almost trivial.
I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:
foreach (var line in File.ReadLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
{
current = new List<string>();
current.Add(line);
}
else if (line.Contains("CustomerEN") && current != null)
{
current.Add(line);
}
}
string s = String.Join(",", current);
MessageBox.Show(s);
Following this guide I had the same issue. To expand on Eric Moore's ridiculously vague answer,
Right click > TortoiseGit > Settings > Network
Down the bottom in the "SSH" section, hit Browse and find your TortoiseGit\bin\TortoisePlink.exe
file. In my case the path was under Programs
as opposed to Program Files
Here's another implementation of replaceAll. Hope it helps someone.
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Then you can use it:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");
I have done this one by Passing ArrayList in form of String.
Add compile 'com.google.code.gson:gson:2.2.4'
in dependencies block build.gradle.
Click on Sync Project with Gradle Files
Cars.java:
public class Cars {
public String id, name;
}
When you want to pass ArrayList:
List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));
Gson gson = new Gson();
String jsonCars = gson.toJson(cars);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);
Get CarsModel by Function:
private Cars getCarModel(String id, String name){
Cars cars = new Cars();
cars.id = id;
cars.name = name;
return cars;
}
You have to import java.lang.reflect.Type
;
on onCreate() to retrieve ArrayList:
String carListAsString = getIntent().getStringExtra("list_as_string");
Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
Log.i("Car Data", cars.id+"-"+cars.name);
}
Hope this will save time, I saved it.
Done
Using Hex
in Apache Commons:
String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Changing keystore password
$ keytool -storepasswd -keystore keystorename
Enter keystore password: <old password>
New keystore password: <new password>
Re-enter new keystore password: <new password>
Changing keystore alias password
$keytool -keypasswd -keystore keystorename -alias aliasname
Enter keystore password:
New key password for <aliasname>:
Re-enter new key password for <aliasname>:
Note:
**Keystorename**: name of your keystore(with path if you are indifferent folder)
**aliasname**: alias name you used when creating (if name has space you can use \)
for example: $keytool -keypasswd -keystore keystorename -alias stop\ watch
You could see the response in Fiddler: http://www.fiddler2.com/fiddler2/
That's nice tool for such things!
Using generics:
static bool IsNullOrDefault<T>(T value)
{
return object.Equals(value, default(T));
}
//...
double d = 0;
IsNullOrDefault(d); // true
MyClass c = null;
IsNullOrDefault(c); // true
If T
it's a reference type, value
will be compared with null
( default(T)
), otherwise, if T
is a value type
, let's say double, default(t)
is 0d, for bool is false
, for char is '\0'
and so on...
None of the above solutions worked for me. Append method didn't give error when i tried but it didn't solve my problem. In the end i solved my problem with data property of select2. I used json and got the array and then give it in select2 element initialize. For more detail you can see my answer at below post.
Remember that Raspberry Pi does not have real time clock. So even you are connected to internet have to set the time every time you power on or restart.
This is how it works:
sudo raspi-config
in the Raspberry Pi command lineNext thing you can set time using this command
sudo date -s "Mon Aug 12 20:14:11 UTC 2014"
More about data and time
man date
When Pi is connected to computer should have to manually set data and time
To run your application in PowerShell (since &&
is disallowed):
($env:NODE_ENV="production") -and (node myapp/app.js)
Note that the text output of what the server's doing is suppressed, and I am not sure if that's fixable. (Expanding on @jsalonen's answer.)
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
You can use Series.isin
:
df = df[~df.datecolumn.isin(a)]
While the error message suggests that all()
or any()
can be used, they are useful only when you want to reduce the result into a single Boolean value. That is however not what you are trying to do now, which is to test the membership of every values in the Series against the external list, and keep the results intact (i.e., a Boolean Series which will then be used to slice the original DataFrame).
You can read more about this in the Gotchas.
I use the following to dynamically adjust height of the select2 dropdown element so it nicely fits the amount of options:
$('select').on('select2:open', function (e) {
var OptionsSize = $(this).find("option").size(); // The amount of options
var HeightPerOption = 36; // the height in pixels every option should be
var DropDownHeight = OptionsSize * HeightPerOption;
$(".select2-results__options").height(DropDownHeight);
});
Make sure to unset the (default) max-height in css:
.select2-container--default .select2-results>.select2-results__options {
max-height: inherit;
}
(only tested in version 4 of select2)
for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){
double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT;
}
if you want to get around the + 1 issue
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
The quick generic answer:
std::vector<double> vec(carray,carray+carray_size);
or question specific:
std::vector<double> w_(w,w+len);
based on above: Don't forget that you can treat pointers as iterators
I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore
the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.
On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.
Getting the idea from PHP Symfony 3 framework that has a parameters.yml
(.gitignored) and a parameters.yml.dist
(which is a sample that creates the first one through composer install
),
I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.
Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:
spring:
profiles:
active: local/dev/prod
datasource:
username:
password:
url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: verysecretpassword
url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
profiles:
active: dev
datasource:
username: root
password: rootroot
url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring:
datasource:
testWhileIdle: true
validationQuery: SELECT 1
jpa:
show-sql: true
format-sql: true
hibernate:
ddl-auto: create-droop
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL57InnoDBDialect
Same can be done with .properties
How about sapply
(not really necessary for this simple case):
newData<- sapply(data, function(x) x^2)
When you have a function in the base class, you can Redefine
or Override
it in the derived class.
Redefining a method :
A new implementation for the method of base class is given in the derived class. Does not facilitate Dynamic binding
.
Overriding a method:
Redefining
a virtual method
of the base class in the derived class. Virtual method facilitates Dynamic Binding.
So when you said :
But earlier in the book, when learning about basic inheritance, I was able to override base methods in derived classes without using 'virtual'.
you were not overriding it as the method in the base class was not virtual, rather you were redefining it
You can try with the code that is below.
It will make the default date become the date you are looking for.
$('#birthdate').datepicker("setDate", new Date(1985,01,01) );
Here is how I have done it in Kotlin.
Inject room db in the activity using DI (Koin).
private val appDB: AppDB by inject()
Then you can simply call clearAllTables()
private fun clearRoomDB() {
GlobalScope.launch {
appDB.clearAllTables()
preferences.put(PreferenceConstants.IS_UPLOADCATEGORIES_SAVED_TO_DB, false)
preferences.put(PreferenceConstants.IS_MEMBERHANDBOOK_SAVED_TO_DB, false)
}
}
class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)
def testMultiplication (self):
return (self.a * self.b)
then
temp = MathsOperations()
print(temp.testAddition())
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
set(a) & set(xyz)
set([0, 9, 4, 6, 7])
var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";
You can find out more about placeholder
here: http://help.dottoro.com/ljgugboo.php
It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.
char *buff;
size_t buff_size = 100;
int choice;
do{
buff = (char *)malloc(buff_size *sizeof(char));
getline(&buff, &buff_size, stdin);
choice = atoi(buff);
free(buff);
}while((choice<1)&&(choice>9));
For the mocks initialization, using the runner or the MockitoAnnotations.initMocks
are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner :
JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.
The first solution (with the MockitoAnnotations.initMocks
) could be used when you have already configured a specific runner (SpringJUnit4ClassRunner
for example) on your test case.
The second solution (with the MockitoJUnitRunner
) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of automatic validation of framework usage (described by @David Wallace in this answer).
Both solutions allows to share the mocks (and spies) between the test methods. Coupled with the @InjectMocks
, they allow to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example:
@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {
@Mock private ArticleCalculator calculator;
@Mock(name = "database") private ArticleDatabase dbMock;
@Spy private UserProvider userProvider = new ConsumerUserProvider();
@InjectMocks private ArticleManager manager;
@Test public void shouldDoSomething() {
manager.initiateArticle();
verify(database).addListener(any(ArticleListener.class));
}
@Test public void shouldDoSomethingElse() {
manager.finishArticle();
verify(database).removeListener(any(ArticleListener.class));
}
}
Pros: The code is minimal
Cons: Black magic. IMO it is mainly due to the @InjectMocks annotation. With this annotation "you loose the pain of code" (see the great comments of @Brice)
The third solution is to create your mock on each test method. It allow as explained by @mlk in its answer to have "self contained test".
public class ArticleManagerTest {
@Test public void shouldDoSomething() {
// given
ArticleCalculator calculator = mock(ArticleCalculator.class);
ArticleDatabase database = mock(ArticleDatabase.class);
UserProvider userProvider = spy(new ConsumerUserProvider());
ArticleManager manager = new ArticleManager(calculator,
userProvider,
database);
// when
manager.initiateArticle();
// then
verify(database).addListener(any(ArticleListener.class));
}
@Test public void shouldDoSomethingElse() {
// given
ArticleCalculator calculator = mock(ArticleCalculator.class);
ArticleDatabase database = mock(ArticleDatabase.class);
UserProvider userProvider = spy(new ConsumerUserProvider());
ArticleManager manager = new ArticleManager(calculator,
userProvider,
database);
// when
manager.finishArticle();
// then
verify(database).removeListener(any(ArticleListener.class));
}
}
Pros: You clearly demonstrate how your api works (BDD...)
Cons: there is more boilerplate code. (The mocks creation)
My recommandation is a compromise. Use the @Mock
annotation with the @RunWith(MockitoJUnitRunner.class)
, but do not use the @InjectMocks
:
@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
@Spy private UserProvider userProvider = new ConsumerUserProvider();
@Test public void shouldDoSomething() {
// given
ArticleManager manager = new ArticleManager(calculator,
userProvider,
database);
// when
manager.initiateArticle();
// then
verify(database).addListener(any(ArticleListener.class));
}
@Test public void shouldDoSomethingElse() {
// given
ArticleManager manager = new ArticleManager(calculator,
userProvider,
database);
// when
manager.finishArticle();
// then
verify(database).removeListener(any(ArticleListener.class));
}
}
Pros: You clearly demonstrate how your api works (How my ArticleManager
is instantiated). No boilerplate code.
Cons: The test is not self contained, less pain of code
database_name -> Operations -> Remove database -> click on drop the database (DROP)
For more solution i have completed the solution of (the great) Tiago Gouvêa exposed before only for strings and arrays
i used md_convert_encoding() function instead of utf8_encode(), it works for me : (12 hours loosed ...)
// this object return me a big array who have multiple arrays imbricated
$get_days = program::get_days($ARR, $client);
// and i use this function for well parsing what the server return *
function convert_to_utf8_recursively($dat){
if( is_string($dat) ){
return mb_convert_encoding($dat, 'UTF-8', 'UTF-8');
}
elseif( is_array($dat) ){
$ret = [];
foreach($dat as $i => $d){
$ret[$i] = convert_to_utf8_recursively($d);
}
return $ret;
}
else{
return $dat;
}
}
// use
$data = convert_to_utf8_recursively($get_days);
You should use toString() Method of java script for the convert into string before because replace method is a string function.
Use this:
while IFS= read -r file ; do rm -- "$file" ; done < delete.list
If you need glob expansion you can omit quoting $file
:
IFS=""
while read -r file ; do rm -- $file ; done < delete.list
But be warned that file names can contain "problematic" content and I would use the unquoted version. Imagine this pattern in the file
*
*/*
*/*/*
This would delete quite a lot from the current directory! I would encourage you to prepare the delete list in a way that glob patterns aren't required anymore, and then use quoting like in my first example.
Use html_entity_decode
to convert HTML entities.
You'll need to set charset to make it work correctly.
If your grid is bound to a DataTable
, I believe you can just do:
// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");
If it isn't bound to a table, you could easily make it so:
var table = new DataTable();
table.Columns.Add("type", typeof(string));
table.Columns.Add("count", typeof(int));
// This will automatically create the DataGridView's columns.
dataGridView.DataSource = table;
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
You have to use image
.listStyle {
list-style: none;
background: url(bullet.jpg) no-repeat left center;
padding-left: 40px;
}
If you multiply the numerator and denominator of one Fraction with the denominator of the other and vice versa, you end up with two fractions (that are still the same values) with the same denominator and you can compare the numerators directly. Therefore you wouldn't need to calculate the double value:
public int compareTo(Fraction frac) {
int t = this.numerator * frac.getDenominator();
int f = frac.getNumerator() * this.denominator;
if(t>f) return 1;
if(f>t) return -1;
return 0;
}
https://developer.mozilla.org/en/CSS/vertical-align
<table style="height: 275px; width: 188px">
<tr>
<td style="width: 259px; vertical-align:top">
main page
</td>
</tr>
</table>
?
Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode
. $contractorCompanies
contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies)
doesn't escape them because its valid JSON.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
Here is a noise-free version of the solution which is to use with_items:
- name: add lines
lineinfile:
dest: fruits.txt
line: '{{ item }}'
with_items:
- 'Orange'
- 'Apple'
- 'Banana'
For each item, if the item exists in fruits.txt no action is taken.
If the item does not exist it will be appended to the end of the file.
Easy-peasy.
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries.
Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.
ev
icon next to elements
Within the Firefox Developer Tools' Inspector panel lists all events bound to an element.
First select an element with Ctrl + Shift + C, e.g. Stack Overflow's upvote arrow.
Click on the ev
icon to the right of the element, and a dialogue opens:
Click on the pause sign ||
symbol for the event you want, and this opens the debugger on the line of the handler.
You can now place a breakpoint there as usual in the debugger, by clicking on the left margin of the line.
This is mentioned at: https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_event_listeners
Unfortunately, I couldn't find a way for this to play nicely with prettyfication, it just seems to open at the minified line: How to beautify Javascript and CSS in Firefox / Firebug?
Tested on Firefox 42.
this is what I did:
html, body {
height:100%;
background: #014298 ;
}
body {
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#5c9cf2), color-stop(100%,#014298));
background: -moz-linear-gradient(top, rgba(92,156,242,1) 0%, rgba(1,66,152,1) 100%);
background: -o-linear-gradient(top, #5c9cf2 0%,#014298 100%);
/*I added these codes*/
margin:0;
float:left;
position:relative;
width:100%;
}
before I floated the body, there was a gap on top, and it was showing the background color of html. if I remove the bgcolor of html, when I scroll down, the gradient is cut. so I floated the body and set it's position to relative and the width to 100%. it worked on safari, chrome, firefox, opera, internet expl.. oh wait. :P
what do you guys think?
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
Strangely enough, the reason for my failure was about the CamelCase that I was applying to the component name. MyComponent
was giving me this error but then I renamed it to Mycomponent
and voila, it worked!!!
Strictly speaking, the difference between Database and Schema is inexisting in MySql.
However, this is not the case in other database engines such as SQL Server. In SQL server:,
Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)
By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:
SELECT *
FROM your_table
which is equivalent to:
SELECT *
FROM dbo.your_table
Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.
For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).
The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).
There are special schemas in SQL Server. To quote the same book:
There are several built-in database schemas, and they can't be dropped or altered:
1) dbo, the default schema.
2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.
3) INFORMATION_SCHEMA, used by the Information Schema Views
4) sys, reserved for SQL Server internal use exclusively
Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.
Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT
permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts
(just an example, you get the idea).
Finally, and quoting the same book again:
It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition