EXEC proc_name @paramValue1 = 0, @paramValue2 = 'some text';
GO
If the Stored Procedure objective is to perform an INSERT
on a table that has an Identity field declared, then the field, in this scenario @paramValue1
, should be declared and just pass the value 0, because it will be auto-increment.
Add the below code
input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
If you need only for these button then you can add id name
#paginate input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
One additional benefit to doing it in javascript is you can add / remove the hover effect at different points in time - e.g. hover over table rows changes color, click disables the hover effect and starts edit in place mode.
In addition:
AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location
Simple, use absolute positioning, and instead of specifying a top and a left, specify a top and a right!
For example:
#logo_image {
width:80px;
height:80px;
top:10px;
right:10px;
z-index: 3;
position:absolute;
}
I guess you need a dynamic title that is why you don't set it in IB.
And I presume your viewController object is the one specified in the NIB?
Perhaps trying setting it to a dummy value in IB and then debug the methods to see which controller has the dummy value - assuming it appears as the title...
Here is a minor improvement for Denis Tulskiy answer. It cuts the time by half
public static long[] generateSeed(String goal, long start, long finish) {
char[] input = goal.toCharArray();
int[] dif = new int[input.length - 1];
for (int i = 1; i < input.length; i++) {
dif[i - 1] = input[i] - input[i - 1];
}
mainLoop:
for (long seed = start; seed < finish; seed++) {
Random random = new Random(seed);
int lastChar = random.nextInt(27);
int base = input[0] - lastChar;
for (int d : dif) {
int nextChar = random.nextInt(27);
if (nextChar - lastChar != d) {
continue mainLoop;
}
lastChar = nextChar;
}
if(random.nextInt(27) == 0){
return new long[]{seed, base};
}
}
throw new NoSuchElementException("Sorry :/");
}
HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link
Yes to your second and third questions -- that's what you need to do as you cannot have multiple 'lvalues' on the left of an assignment.
An Outlet is a link from code to UI. If you want to show or hide an UI element, if you want to get the text of a textfield or enable or disable an element (or a hundred other things) you have to define an outlet of that object in the sources and link that outlet through the “interface object” to the UI element. After that you can use the outlet just like any other variable in your coding.
IBAction – a special method triggered by user-interface objects. Interface Builder recognizes them.
@interface Controller
{
IBOutlet id textField; // links to TextField UI object
}
- (IBAction)doAction:(id)sender; // e.g. called when button pushed
For further information please refer Apple Docs
This solution is very similar to those presented above. The only difference is that you are going to be able to delay the prompt of the rating dialog per launches and days. If the remind me later button is pressed, then I will delay the pop up for 3 days and 10 launches. The same is done for those that selected to rate it, however the delays is longer (not to bother the user so soon in case that he has actually rated the app. This can be changed to not be shown again, then you will have to alter the code to your like). Hope it helps somebody!
public class AppRater {
private final static String APP_TITLE = "your_app_name";
private static String PACKAGE_NAME = "your_package_name";
private static int DAYS_UNTIL_PROMPT = 5;
private static int LAUNCHES_UNTIL_PROMPT = 10;
private static long EXTRA_DAYS;
private static long EXTRA_LAUCHES;
private static SharedPreferences prefs;
private static SharedPreferences.Editor editor;
private static Activity activity;
public static void app_launched(Activity activity1) {
activity = activity1;
Configs.sendScreenView("Avaliando App", activity);
PACKAGE_NAME = activity.getPackageName();
prefs = activity.getSharedPreferences("apprater", Context.MODE_PRIVATE);
if (prefs.getBoolean("dontshowagain", false))
return;
editor = prefs.edit();
EXTRA_DAYS = prefs.getLong("extra_days", 0);
EXTRA_LAUCHES = prefs.getLong("extra_launches", 0);
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= (LAUNCHES_UNTIL_PROMPT + EXTRA_LAUCHES))
if (System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000) + EXTRA_DAYS)
showRateDialog();
editor.commit();
}
public static void showRateDialog() {
final Dialog dialog = new Dialog(activity);
dialog.setTitle("Deseja avaliar o aplicativo " + APP_TITLE + "?");
LinearLayout ll = new LinearLayout(activity);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setPadding(5, 5, 5, 5);
TextView tv = new TextView(activity);
tv.setTextColor(activity.getResources().getColor(R.color.default_text));
tv.setText("Ajude-nos a melhorar o aplicativo com sua avaliação no Google Play!");
tv.setWidth(240);
tv.setGravity(Gravity.CENTER);
tv.setPadding(5, 5, 5, 5);
ll.addView(tv);
Button b1 = new Button(activity);
b1.setTextColor(activity.getResources().getColor(R.color.default_text));
b1.setBackground(activity.getResources().getDrawable(R.drawable.rounded_blue_box));
b1.setTextColor(Color.WHITE);
b1.setText("Avaliar aplicativo " + APP_TITLE + "!");
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Configs.sendHitEvents(Configs.APP_RATER, Configs.CATEGORIA_ANALYTICS, "Clique", "Avaliar", activity);
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + PACKAGE_NAME)));
delayDays(60);
delayLaunches(30);
dialog.dismiss();
}
});
ll.addView(b1);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) b1.getLayoutParams();
params.setMargins(5, 3, 5, 3);
b1.setLayoutParams(params);
Button b2 = new Button(activity);
b2.setTextColor(activity.getResources().getColor(R.color.default_text));
b2.setBackground(activity.getResources().getDrawable(R.drawable.rounded_blue_box));
b2.setTextColor(Color.WHITE);
b2.setText("Lembre-me mais tarde!");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Configs.sendHitEvents(Configs.APP_RATER, Configs.CATEGORIA_ANALYTICS, "Clique", "Avaliar Mais Tarde", activity);
delayDays(3);
delayLaunches(10);
dialog.dismiss();
}
});
ll.addView(b2);
params = (LinearLayout.LayoutParams) b2.getLayoutParams();
params.setMargins(5, 3, 5, 3);
b2.setLayoutParams(params);
Button b3 = new Button(activity);
b3.setTextColor(activity.getResources().getColor(R.color.default_text));
b3.setBackground(activity.getResources().getDrawable(R.drawable.rounded_blue_box));
b3.setTextColor(Color.WHITE);
b3.setText("Não, obrigado!");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Configs.sendHitEvents(Configs.APP_RATER, Configs.CATEGORIA_ANALYTICS, "Clique", "Não Avaliar", activity);
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
params = (LinearLayout.LayoutParams) b3.getLayoutParams();
params.setMargins(5, 3, 5, 0);
b3.setLayoutParams(params);
dialog.setContentView(ll);
dialog.show();
}
private static void delayLaunches(int numberOfLaunches) {
long extra_launches = prefs.getLong("extra_launches", 0) + numberOfLaunches;
editor.putLong("extra_launches", extra_launches);
editor.commit();
}
private static void delayDays(int numberOfDays) {
Long extra_days = prefs.getLong("extra_days", 0) + (numberOfDays * 1000 * 60 * 60 * 24);
editor.putLong("extra_days", extra_days);
editor.commit();
}
}
The Buttons have a specific color and background. The background is as shown in this xml file:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle" >
<solid android:color="#2E78B9" />
<corners
android:bottomLeftRadius="6dp"
android:bottomRightRadius="6dp"
android:topLeftRadius="6dp"
android:topRightRadius="6dp" />
</shape>
open file gradle.properties and add these two lines to it:
android.useAndroidX = true
android.enableJetifier = true
clean and build
static
A member declared with the keyword 'static'.
factory methods
Methods that create and return new objects.
in Java
The programming language is relevant to the meaning of 'static' but not to the definition of 'factory'.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
i faced this same, i check in in program and feature. there was an update has install for jdk1.8 which is not compatible with my old setting(jdk1.6.0) for ant in eclipse. I install that update. right now, my ant project is build success.
Try it, hope this will be helpful.
Here is what happened in my case. I was asked to attach files for a database. I was given the file names as follows
I proceeded to attach the files and kept getting the files are in use by another process.
I ran a query against the system view select name, physical_name from sys.master_files; and saw that the exact file names were already in use by another database, thus each time I tried to attach the files, I kept getting the error the files are in use by another process(sql server)
Thus if you are getting such a message, then also query against the system view sys.master_files and see which database may already be using the same name files. Hereafter you will figure out what to do.
thanks.
From my experience (Eclipse):
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
var data = [
["a1", "a2", "a3"],
["b1", "b2", "b3"],
["c1", "c2", "c3"]
];
var col0 = data.map(d => d[0]); // [ 'a1', 'b1', 'c1' ]
var col1 = data.map(d => d[1]); // [ 'a2', 'b2', 'c2' ]
I would also try it this way
1) Create the Java Beans from the JSON schema
2) Use JSON parser libraries to avoid any sort of exception
3) Cast the parse result to the Java object that was created from the initial JSON schema.
Below is an example JSON Schema"
{
"USD" : {"15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68, "symbol" : "$"},
"JPY" : {"15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99, "symbol" : "¥"},
}
public class Container {
private JPY JPY;
private USD USD;
public JPY getJPY ()
{
return JPY;
}
public void setJPY (JPY JPY)
{
this.JPY = JPY;
}
public USD getUSD ()
{
return USD;
}
public void setUSD (USD USD)
{
this.USD = USD;
}
@Override
public String toString()
{
return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
}
}
public class JPY
{
@SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
@Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class USD
{
@SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
{
return fifitenM;
}
public void setFifitenM (double fifitenM)
{
this.fifitenM = fifitenM;
}
public String getSymbol ()
{
return symbol;
}
public void setSymbol (String symbol)
{
this.symbol = symbol;
}
public double getLast ()
{
return last;
}
public void setLast (double last)
{
this.last = last;
}
public double getSell ()
{
return sell;
}
public void setSell (double sell)
{
this.sell = sell;
}
public double getBuy ()
{
return buy;
}
public void setBuy (double buy)
{
this.buy = buy;
}
@Override
public String toString()
{
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
}
}
public class MainMethd
{
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException {
// TODO Auto-generated method stub
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
String res = obj.toString();
Gson gson = new Gson();
Container container = new Container();
container = gson.fromJson(res, Container.class);
System.out.println(container.getUSD());
System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
}
}
Output from the main method is:
ClassPojo [15m = 478.68, symbol = $, last = 478.68, sell = 478.68, buy = 478.55]
Sell Price : $478.68
Buy Price : $478.55
Hope this helps.
When you want to show years and the remaining days:
var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');
This version in C# is reasonably efficient, and it works for non-western digits (like "???????" for example).
static void Main(string[] args)
{
string phoneNumber = null;
if (1 <= args.Length)
phoneNumber = args[0];
if (string.IsNullOrEmpty(phoneNumber))
{
Console.WriteLine("No phone number supplied.");
return;
}
else
{
Console.WriteLine("Alphabetic phone numbers for \"{0}\":", phoneNumber);
foreach (string phoneNumberText in GetPhoneNumberCombos(phoneNumber))
Console.Write("{0}\t", phoneNumberText);
}
}
public static IEnumerable<string> GetPhoneNumberCombos(string phoneNumber)
{
phoneNumber = RemoveNondigits(phoneNumber);
if (string.IsNullOrEmpty(phoneNumber))
return new List<string>();
char[] combo = new char[phoneNumber.Length];
return GetRemainingPhoneNumberCombos(phoneNumber, combo, 0);
}
private static string RemoveNondigits(string phoneNumber)
{
if (phoneNumber == null)
return null;
StringBuilder sb = new StringBuilder();
foreach (char nextChar in phoneNumber)
if (char.IsDigit(nextChar))
sb.Append(nextChar);
return sb.ToString();
}
private static IEnumerable<string> GetRemainingPhoneNumberCombos(string phoneNumber, char[] combo, int nextDigitIndex)
{
if (combo.Length - 1 == nextDigitIndex)
{
foreach (char nextLetter in phoneNumberAlphaMapping[(int)char.GetNumericValue(phoneNumber[nextDigitIndex])])
{
combo[nextDigitIndex] = nextLetter;
yield return new string(combo);
}
}
else
{
foreach (char nextLetter in phoneNumberAlphaMapping[(int)char.GetNumericValue(phoneNumber[nextDigitIndex])])
{
combo[nextDigitIndex] = nextLetter;
foreach (string result in GetRemainingPhoneNumberCombos(phoneNumber, combo, nextDigitIndex + 1))
yield return result;
}
}
}
private static char[][] phoneNumberAlphaMapping = new char[][]
{
new char[] { '0' },
new char[] { '1' },
new char[] { 'a', 'b', 'c' },
new char[] { 'd', 'e', 'f' },
new char[] { 'g', 'h', 'i' },
new char[] { 'j', 'k', 'l' },
new char[] { 'm', 'n', 'o' },
new char[] { 'p', 'q', 'r', 's' },
new char[] { 't', 'u', 'v' },
new char[] { 'w', 'x', 'y', 'z' }
};
According to PHPMailer Manual, full answer would be :
$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
Use Case :
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';
If you want to display an image with a remote URL :
$mail->addStringAttachment(file_get_contents("url"), "filename");
Your best bet would be using the RFC defined mime-type audio/mpeg
.
Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs
or remove them from *args
. Instead, you can define a Base
class which unlike object
, absorbs/ignores arguments:
class Base(object):
def __init__(self, *args, **kwargs): pass
class A(Base):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(Base):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(arg, *args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(arg, *args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(arg, *args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10)
yields
MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']
E arg= 10
C arg= 10
A
D arg= 10
B
Note that for this to work, Base
must be the penultimate class in the MRO.
It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:
Moving existing code to Test Driven Development
I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.
Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).
jQuery Cycle is one of my favourite light weight libraries.
What you want to achieve could be done in just
jQuery("#slideshow").cycle({
timeout:0, // no autoplay
fx: 'fade', //fade effect, although there are heaps
next: '#next',
prev: '#prev'
});
I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.
First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )
I was getting a nil reference to cell.detailTextLabel.text
- After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.
var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).
So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.
Im guesssing your label should always be there?
So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
you can use asctime() function of time.h to get a string simply .
time_t _tm =time(NULL );
struct tm * curtime = localtime ( &_tm );
cout<<"The current date/time is:"<<asctime(curtime);
Sample output:
The current date/time is:Fri Oct 16 13:37:30 2015
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Given enum
public enum PublishMode { Edit, View }
you can do it like here
void MyMethod(PublishMode? mode)
{
var publishMode = mode ?? PublishMode.Edit;
//or
if (mode?? PublishMode.Edit == someValue)
....
}
If you are using Picasso or Glide or Universal-Image-Loader for load image from url.
You can simply get the loaded bitmap by
For Picasso (current version 2.71828
)
Java code
Picasso.get().load(imageUrl).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loaded bitmap is here (bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) { }
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
});
Kotlin code
Picasso.get().load(url).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
// loaded bitmap is here (bitmap)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
})
For Glide
Check How does one use glide to download an image into a bitmap?
For Universal-Image-Loader
Java code
imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener()
{
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
// loaded bitmap is here (loadedImage)
}
});
You should use the Chartjs API function toBase64Image()
instead and call it after the animation is complete. Therefore:
var pieChart, URI;
var options = {
animation : {
onComplete : function(){
URI = pieChart.toBase64Image();
}
}
};
var content = {
type: 'pie', //whatever, not relevant for this example
data: {
datasets: dataset //whatever, not relevant for this example
},
options: options
};
pieChart = new Chart(pieChart, content);
You can check this example and run it
var chart = new Chart(ctx, {_x000D_
type: 'bar',_x000D_
data: {_x000D_
labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
// create 12 datasets, since we have 12 items_x000D_
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
// put 0, if there is no data for the particular bar_x000D_
datasets: [{_x000D_
label: 'Washing and cleaning',_x000D_
data: [0, 8],_x000D_
backgroundColor: '#22aa99'_x000D_
}, {_x000D_
label: 'Traffic tickets',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#994499'_x000D_
}, {_x000D_
label: 'Tolls',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#316395'_x000D_
}, {_x000D_
label: 'Parking',_x000D_
data: [5, 2],_x000D_
backgroundColor: '#b82e2e'_x000D_
}, {_x000D_
label: 'Car tax',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#66aa00'_x000D_
}, {_x000D_
label: 'Repairs and improvements',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#dd4477'_x000D_
}, {_x000D_
label: 'Maintenance',_x000D_
data: [6, 1],_x000D_
backgroundColor: '#0099c6'_x000D_
}, {_x000D_
label: 'Inspection',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#990099'_x000D_
}, {_x000D_
label: 'Loan interest',_x000D_
data: [0, 3],_x000D_
backgroundColor: '#109618'_x000D_
}, {_x000D_
label: 'Depreciation of the vehicle',_x000D_
data: [0, 2],_x000D_
backgroundColor: '#109618'_x000D_
}, {_x000D_
label: 'Fuel',_x000D_
data: [0, 1],_x000D_
backgroundColor: '#dc3912'_x000D_
}, {_x000D_
label: 'Insurance and Breakdown cover',_x000D_
data: [4, 0],_x000D_
backgroundColor: '#3366cc'_x000D_
}]_x000D_
},_x000D_
options: {_x000D_
responsive: false,_x000D_
legend: {_x000D_
position: 'right' // place legend on the right side of chart_x000D_
},_x000D_
scales: {_x000D_
xAxes: [{_x000D_
stacked: true // this should be set to make the bars stacked_x000D_
}],_x000D_
yAxes: [{_x000D_
stacked: true // this also.._x000D_
}]_x000D_
},_x000D_
animation : {_x000D_
onComplete : done_x000D_
} _x000D_
}_x000D_
});_x000D_
_x000D_
function done(){_x000D_
alert(chart.toBase64Image());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
<canvas id="ctx" width="700"></canvas>
_x000D_
Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after
// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });
// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bars = bs })
.SelectMany(
fooBars => fooBars.Bars.DefaultIfEmpty(),
(x,y) => new { Foo = x.Foo, Bar = y });
To display the difference using a simple data set (assuming we're joining on the values themselves):
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };
// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };
// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 } // Misleading, we had multiple matches.
// Which 3 should get selected (not arbitrarily the first)?.
// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
{ A = 3, B = 3 }
Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set.
Be careful that when you using:
curl -H "Authorization: token_str" http://www.example.com
token_str
and Authorization
must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION
environment.
Curl has a mode that is almost equivalent to the default wget.
curl -O <url>
This works just like
wget <url>
And, if you like, you can add this to your .bashrc:
alias wget='curl -O'
It's not 100% compatible, but it works for the most common wget usage (IMO)
under Site setting in Reports manager >Configure system-level role definitions > check ExecuteReport Defination option then Create a System UserGroup, Give the access to that group at Connect to your reporting Services Data base in server properties and add a group and permite the access as System User... It should work
In my opinion setting the "validate_password_policy" to "low" or uninstalling the "validate password plugin" is not the right thing to do. You must never compromise with security of your database (unless you don't really care). I am wondering why people are even suggesting these options when you simply can pick a good password.
To overcome this problem, I executed following command in mysql: SHOW VARIABLES LIKE 'validate_password%' as suggested by @JNevill. My "validate_password_policy" was set to Medium, along with other things. Here is the screenshot of its execution: Validate Password Policy
The result is self explanatory. For a valid password (when Password policy is set to medium):
So a valid password must obey the policy. Examples of valid password for above rules maybe:
You can pick any combination as long as it satisfies the policy.
For other "validate_password_policy" you can simply look the values for different options and pick your password accordingly (I haven't tried for "STRONG").
https://dev.mysql.com/doc/refman/5.6/en/validate-password-options-variables.html
You could do this
Assembly asm = Assembly.GetExecutingAssembly();
string path = System.IO.Path.GetDirectoryName(asm.Location);
It's very easy with fs.
var fs = require('fs');
try{
var sourceUrls = "/sampleFolder/sampleFile.txt";
fs.unlinkSync(sourceUrls);
}catch(err){
console.log(err);
}
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
If you're doing this repeatedly, I would download it locally and pull from the local file. *nix users can use /usr/share/dict/words
.
Example:
word_file = "/usr/share/dict/words"
WORDS = open(word_file).read().splitlines()
If you want to pull from a remote dictionary, here are a couple of ways. The requests library makes this really easy (you'll have to pip install requests
):
import requests
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = requests.get(word_site)
WORDS = response.content.splitlines()
Alternatively, you can use the built in urllib2.
import urllib2
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
With C++17 you can use std::filesystem::is_directory
function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path
object which can be constructed with a unicode path.
I resolved this problem by deleting the registry key under
hkey_current_user\software\Microsoft\VSCommon\12.0\clientservices\tokenstorage\visualstudio\ideuser
mysqli_real_escape_string function requires the connection to your database.
$username = mysqli_real_escape_string($your_connection, $_POST['username']);
P.S.: Do not mix mysql_ functions* and mysqli_ functions*. Please use mysqli_* functions or PDO
because mysql_* functions are deprecated and will be removed in the future.
You can use base_path() to get the base of your application - and then just add your public folder to that:
$path = base_path().'/public';
return File::put($path , $data)
Note: Be very careful about allowing people to upload files into your root of public_html. If they upload their own index.php file, they will take over your site.
Before you return your model from the controller, set your ReturnDate
property to DateTime.Now()
myModel.ReturnDate = DateTime.Now()
return View(myModel)
Your view is not the right place to set values on properties so the controller is the better place for this.
You could even have it so that the getter on ReturnDate
returns the current date/time.
private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
get{
return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
}
set{_returnDate = value;}
}
**In Swift**
var a = 14.123456789
var b = 14.123456789
var c = 14.123456789
var d = 14.123456789
var e = 14.123456789
var f = 14.123456789
a.rounded(.up) //15
b.rounded(.down) //14
c.rounded(.awayFromZero) //15
d.rounded(.towardZero) //14
e.rounded(.toNearestOrAwayFromZero) //14
f.rounded(.toNearestOrEven) //14
If you are using XAMPP rather than WAMP, the path you go to is:
C:\xampp\phpMyAdmin\config.inc.php
I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block
while the div holding the text had display: inline
.
I changed it to both be display: inline
and it worked.
Here's a solution for a basic header section with a logo, title and tagline:
HTML
<div class="site-branding">
<div class="site-branding-logo">
<img src="add/Your/URI/Here" alt="what Is The Image About?" />
</div>
</div>
<div class="site-branding-text">
<h1 id="site-title">Site Title</h1>
<h2 id="site-tagline">Site Tagline</h2>
</div>
CSS
div.site-branding { /* Position Logo and Text */
display: inline-block;
vertical-align: middle;
}
div.site-branding-logo { /* Position logo within site-branding */
display: inline;
vertical-align: middle;
}
div.site-branding-text { /* Position text within site-branding */
display: inline;
width: 350px;
margin: auto 0;
vertical-align: middle;
}
div.site-branding-title { /* Position title within text */
display: inline;
}
div.site-branding-tagline { /* Position tagline within text */
display: block;
}
Put this XML to show only the wheel:
<ProgressBar
android:indeterminate="true"
android:id="@+id/marker_progress"
style="?android:attr/progressBarStyle"
android:layout_height="50dp" />
After upgrading to Xcode 12 I was still able to build for a real device, but not the simulator. The Podfile build was working only for the real device.
I deleted VALID_ARCHS under Build Settings > User-Defined and it worked! Bashing my head for some time before finding this.
In addition to your CORS issue, the server you are trying to access has HTTP basic authentication enabled. You can include credentials in your cross-domain request by specifying the credentials in the URL you pass to the XHR:
url = 'http://username:[email protected]/testpage'
You could subscribe for the onkeypress event:
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
and then define the isNumber
function:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
You can see it in action here.
This is Very Good Example of minus Length of an array in java, i am giving here both examples
public static int linearSearchArray(){
int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
int key = 7;
int i = 0;
int count = 0;
for ( i = 0; i< arrayOFInt.length; i++){
if ( arrayOFInt[i] == key ){
System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
count ++;
}
}
System.out.println("this Element found the ("+ count +") number of Times");
return i;
}
this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.
If the formulas are identical you can use Find and Replace with Match entire cell contents
checked and Look in: Formulas
. Select the range, go into Find and Replace, make your entries and `Replace All.
Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.
The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.
Function RegexFormulaReplace(formula As String)
Dim regex As New RegExp
regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
' Test if a match is found
If regex.Test(formula) = True Then
RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
Else
RegexFormulaReplace = CVErr(xlErrValue)
End If
Set regex = Nothing
End Function
In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer
tab of the main ribbon, select VBA
and then References
from the main toolbar. Scroll down to find the reference to the library and check the box next to it.
One more plugin, to play notification sounds on websites: Ion.Sound
Advantages:
Set up plugin:
// set up config
ion.sound({
sounds: [
{
name: "my_cool_sound"
},
{
name: "notify_sound",
volume: 0.2
},
{
name: "alert_sound",
volume: 0.3,
preload: false
}
],
volume: 0.5,
path: "sounds/",
preload: true
});
// And play sound!
ion.sound.play("my_cool_sound");
Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.
template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
struct ftor {
bool operator()( T const &l, T const &r )
{ return comp( l, r ); }
};
public:
typedef std::set< T, ftor > t;
};
// usage
bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!
Wow, I think that was worth the trouble!
System.Windows.Forms.Application.Exit()
- Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit()
method is typically called from within a message loop, and forces Run()
to return. To exit a message loop for the current thread only, call ExitThread()
. This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run()
.
System.Environment.Exit(exitCode)
- Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode
permissions. If you do not, a SecurityException
error occurs. This is the call to use if you are running a console application.
I hope it is best to use Application.Exit
See also these links:
New version - psql 12 - will support --csv
.
--csv
Switches to CSV (Comma-Separated Values) output mode. This is equivalent to \pset format csv.
csv_fieldsep
Specifies the field separator to be used in CSV output format. If the separator character appears in a field's value, that field is output within double quotes, following standard CSV rules. The default is a comma.
Usage:
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv -P csv_fieldsep='^' postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres > output.csv
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
This code will work it out definitely
function closing() {
var answer = confirm("Do you wnat to close this window ?");
if (answer){
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
window.close();
}
else{
stop;
}
}
-- If you are using a variable for the database name.
-- Try something like this.
DECLARE @DBName varchar(50)
Set @DBName = 'Database1'; /* could be passed in by a parameter. */
IF( @DBName = 'Database1')
Begin
USE [Database1];
SELECT FROM Table1;
End
IF( @DBName = 'Database2')
Begin
USE [Database2];
SELECT FROM Table2;
End
IF( @DBName is null)
Begin
USE [Database1];
End
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.
function print_array($title,$array){
if(is_array($array)){
echo $title."<br/>".
"||---------------------------------||<br/>".
"<pre>";
print_r($array);
echo "</pre>".
"END ".$title."<br/>".
"||---------------------------------||<br/>";
}else{
echo $title." is not an array.";
}
}
Basic usage:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Results:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
I was using /Date=20161003 in the folder path while doing an insert overwrite and it was failing. I changed it to /Dt=20161003 and it worked
One thing I ran into with the above CustomCellBackgroundView code from Mike Akers which might be useful to others:
cell.backgroundView
doesn't get automatically redrawn when cells are reused, and changes to the backgroundView's position var don't affect reused cells. That means long tables will have incorrectly drawn cell.backgroundViews
given their positions.
To fix this without having to create a new backgroundView every time a row is displayed, call [cell.backgroundView setNeedsDisplay]
at the end of your -[UITableViewController tableView:cellForRowAtIndexPath:]
. Or for a more reusable solution, override CustomCellBackgroundView's position setter to include a [self setNeedsDisplay]
.
Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.
To back up my argument I submit the following.
onclick="location.href"
model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
I find that document.getElementById('textbox-id').readOnly=true
sometimes doesn't work reliably.
Instead, try:
document.getElementById('textbox-id').setAttribute('readonly', 'readonly')
and
document.getElementById('textbox-id').removeAttribute('readonly')
.
A little verbose but it seems to be dependable.
When you specify the -Force
flag, PowerShell will not complain if the folder already exists.
One-liner:
Get-ChildItem D:\TopDirec\SubDirec\Project* | `
%{ Get-ChildItem $_.FullName -Filter Revision* } | `
%{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }
BTW, for scheduling the task please check out this link: Scheduling Background Jobs.
The easiest way is to use a StringContent
, with the JSON representation of your JSON object.
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
intersect_all <- function(a,b,...){
all_data <- c(a,b,...)
require(plyr)
count_data<- length(list(a,b,...))
freq_dist <- count(all_data)
intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
intersect_data
}
intersect_all(a,b,c)
UPDATE EDIT A simpler code
intersect_all <- function(a,b,...){
Reduce(intersect, list(a,b,...))
}
intersect_all(a,b,c)
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
When wrapping a pointer in a unique_ptr
you cannot have multiple copies of unique_ptr
. The shared_ptr
holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr
is copied, this counter is incremented. Each time a shared_ptr
is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.
I had the same issue working on a project with Maven. Here how I fixed it: I just put the sources (images, musics and other stuffs) in the resources directory:
src/main/resources
I created the same structure for the packages in the resources directory too. For example:
If my class is on
com.package1.main
In the resources directory I put one package with the same name
com.package1.main
So I use
getClass().getResource("resource.png");
For git repositories, to download the latest commit, you can use:
https://bitbucket.org/owner/repository/get/HEAD.zip
For mercurial repositories:
If you use jQuery and would need an inline solution, this would work very well;
<a href="#" onclick="$(this).closest('form').submit();">submit form</a>
Also, you might want to replace
<a href="#">text</a>
with
<a href="javascript:void(0);">text</a>
so the user does not scroll to the top of your page when clicking the link.
GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.
However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.
For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).
This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.
A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.
The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.
When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.
As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.
In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:
This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.
More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.
But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)
It's only going to get cheaper and more full featured from here on out...
Re: Google maps and such
Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.
Set a listener on your WebView:
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return(event.getAction() == MotionEvent.ACTION_MOVE));
}
});
You can use normal CSS selectors to select an element by name using jquery. Like this:
Button Code
<button type="button" name="mybutton">Click Me!</button>
Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
I'd recommend application/octet-stream
as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".
I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.
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)
First, you need to make certain you have multiple JAVA versions installed. Open a new Terminal window and input:
/usr/libexec/java_home -V
Your output should look like:
Matching Java Virtual Machines (2):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
1.8.0_201, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home
Note that there are two JDKs available. If you don’t notice the Java version you need to switch to, download and install the appropriate one from here (JDK 8 is represented as 1.8) . Once you have installed the appropriate JDK, repeat this step.
Take note of the JDK version you want to switch to. For example, “11.0” and “1.8” are the JDK versions available in the example above.
Switch to the desired version. For example, if you wish to switch to JDK 8, input the following line:
export JAVA_HOME=/usr/libexec/java_home -v 1.8
For 11.0, switch “1.8” with “11.0” 4. Check your JDK version by inputting into Terminal:
java -version
If you have followed all the steps correctly, the JDK version should correlate with the one you specified in the last step. 5. (Optional) To make this the default JDK version, input the following in Terminal:
open ~/.bash_profile
Then, add your Terminal input from step 3 to this file:
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
Save and close the file.
git fetch && git merge origin/develop
Try this:
from pathlib import Path
data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"
f = open(file_to_open)
print(f.read())
Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
proc_label:BEGIN
IF tablename IS NULL THEN
LEAVE proc_label;
END IF;
#proceed the code
END;
Use Shell "program file path file path you want to open"
.
Example:
Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"
Include <tchar.h>
which has the line:
#define _tWinMain wWinMain
You can use jQuery's $.Deferred
var FunctionOne = function () {
// create a deferred object
var r = $.Deferred();
// do whatever you want (e.g. ajax/animations other asyc tasks)
setTimeout(function () {
// and call `resolve` on the deferred object, once you're done
r.resolve();
}, 2500);
// return the deferred object
return r;
};
// define FunctionTwo as needed
var FunctionTwo = function () {
console.log('FunctionTwo');
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
you could also pack multiple deferreds together:
var FunctionOne = function () {
var
a = $.Deferred(),
b = $.Deferred();
// some fake asyc task
setTimeout(function () {
console.log('a done');
a.resolve();
}, Math.random() * 4000);
// some other fake asyc task
setTimeout(function () {
console.log('b done');
b.resolve();
}, Math.random() * 4000);
return $.Deferred(function (def) {
$.when(a, b).done(function () {
def.resolve();
});
});
};
I found an extra
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.28.0" newVersion="2.2.28.0" />
</dependentAssembly>
in my web.config. removed that to get it to work. some other package I installed, and then removed caused the issue.
I can't comment on @omega's comment because I don't have enough reputation but the answer to that question should be something like:
shake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100" <!-- how long the animation lasts -->
android:fromDegrees="-5" <!-- how far to swing left -->
android:pivotX="50%" <!-- pivot from horizontal center -->
android:pivotY="50%" <!-- pivot from vertical center -->
android:repeatCount="10" <!-- how many times to swing back and forth -->
android:repeatMode="reverse" <!-- to make the animation go the other way -->
android:toDegrees="5" /> <!-- how far to swing right -->
Class.java
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
view.startAnimation(shake);
This is just one way of doing what you want, there may be better methods out there.
With c++ you can use static inheritance with the crt method. For the example, it is used widely on window template atl & wtl.
See https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
To be simple, you have a class that is templated from itself like class myclass : public myancestor. From this point the myancestor class can now call your static T::YourImpl function.
To find the name of the current user within an Oracle session, use the USER
function.
Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:
select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
and Constraint_Type = 'R' and Owner = User;
you can use super while extending Exception
if (pass.length() < minPassLength)
throw new InvalidPassException("The password provided is too short");
} catch (NullPointerException e) {
throw new InvalidPassException("No password provided", e);
}
// A custom business exception
class InvalidPassException extends Exception {
InvalidPassException() {
}
InvalidPassException(String message) {
super(message);
}
InvalidPassException(String message, Throwable cause) {
super(message, cause);
}
}
}
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I have found an alternative faster solution:
int j = 0;
for (Iterator i = list.listIterator(); i.hasNext(); ) {
j++;
if (campo.getNome().equals(key)) {
i.remove();
i = list.listIterator(j);
}
}
Here you can set hidden's value at onchange event of dropdown list :
$('#myDropDown').bind('change', function () {
$('#myHidden').val('setted value');
});
your hidden and drop down list :
<input type="hidden" id="myHidden" />
<select id="myDropDown">
<option value="opt 1">Option 1</option>
<option value="opt 2">Option 2</option>
<option value="opt 3">Option 3</option>
</ select>
For the sake of completeness, http://github.com/alex/pyvcs/ is an abstraction layer for all dvcs's. It uses dulwich, but provides interop with the other dvcs's.
If you use "Git for Windows"
>cd c:\Program Files\Git\etc\ssh\
add to ssh_config following:
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_rsa_test
ps. you need ssh version >= 7.2 (date of release 2016-02-28)
Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:
mylist = []
for x in range(5):
mylist.append(x)
mytuple = tuple(mylist)
print mytuple
returns
(0, 1, 2, 3, 4)
I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.
I would take a look at Spring's abstract test classes and mock objects which are talked about here. They provide a powerful way of auto-wiring your Spring managed objects making unit and integration testing easier.
Just Install the oh-my-zsh
plugins as described in this link.
It works best on macOS and Linux.
Basic Installation
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the command-line with either curl
or wget
.
via curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
via wget
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
Every thing is fine.
i just placed call permissions tag before application tag in manifest file
and now every thing is working fine.
Most commands allow args to come in any order. Just move the commented flags to the end of the line:
ls -l -a /etc # -F is turned off
Then to turn it back on, just uncomment and remove the text:
ls -l -a /etc -F
As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.
When defining constructors of a class, they should have the same name as its class. Thus the following code
public class Circle
{
//This part is called the constructor and lets us specify the radius of a
//particular circle.
public Circle(double r)
{
radius = r;
}
....
}
is correct while your code
public class Circle
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public diameter()
{
double d = radius * 2;
return d;
}
}
is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from
public CircleR(double r)
to
public Circle(double r)
or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.
So your new class should be
public class CircleR
{
private double radius;
public CircleR(double r)
{
radius = r;
}
public double diameter()
{
double d = radius * 2;
return d;
}
}
I also added the return type double in your method as pointed out by Froyo and John B.
Refer to this article about constructors.
HTH.
That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:
public class GenericList <T> extends ArrayList<T>
{
private Class<T> genericType;
public GenericList(Class<T> c)
{
this.genericType = c;
}
public Class<T> getGenericType()
{
return genericType;
}
}
One way is to use pcntl_fork()
in a recursive function.
function networkCall(){
$data = processGETandPOST();
$response = makeNetworkCall($data);
processNetworkResponse($response);
return true;
}
function runAsync($times){
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
$times -= 1;
if($times>0)
runAsync($times);
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
networkCall();
posix_kill(getmypid(), SIGKILL);
}
}
runAsync(3);
One thing about pcntl_fork()
is that when running the script by way of Apache, it doesn't work (it's not supported by Apache). So, one way to resolve that issue is to run the script using the php cli, like: exec('php fork.php',$output);
from another file. To do this you'll have two files: one that's loaded by Apache and one that's run with exec()
from inside the file loaded by Apache like this:
apacheLoadedFile.php
exec('php fork.php',$output);
fork.php
function networkCall(){
$data = processGETandPOST();
$response = makeNetworkCall($data);
processNetworkResponse($response);
return true;
}
function runAsync($times){
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
$times -= 1;
if($times>0)
runAsync($times);
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
networkCall();
posix_kill(getmypid(), SIGKILL);
}
}
runAsync(3);
Your TextView Attributes need to be something like,
<TextView ...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right" ../>
Now, Description why these need to be done,
android:layout_width="match_parent"
android:layout_height="match_parent"
Makes your TextView to match_parent
or fill_parent
if You don't want to be it like, match_parent
you have to give some specified values to layout_height
so it get space for vertical center gravity. android:layout_width="match_parent"
necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.
Now, its about android:gravity
which makes the content of Your TextView alignment. android:layout_gravity
makes alignment of TextView respected to its Parent Layout.
Update:
As below comment says use fill_parent
instead of match_parent
. (Problem in some device.)
You can solve using Google CSE (Custom Searche Engine), which can be easily inserted into an iframe. You can create your own search engine, that search selected sites or also in entire Google's database.
The results can be styled as you prefer, also similar to Google style. Google CSE works with web and images search.
google.php
<script>
(function() {
var cx = 'xxxxxxxxxxxxxxxxxxxxxx';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>
yourpage.php
<iframe src="google.php?q=<?php echo urlencode('your query'); ?>"></iframe>
I have made a String prototype which can generate a random String with a given length.
You also can secify if you want special chars and you can avoid some.
/**
* STRING PROTOTYPE RANDOM GENERATOR
* Used to generate a random string
* @param {Boolean} specialChars
* @param {Number} length
* @param {String} avoidChars
*/
String.prototype.randomGenerator = function (specialChars = false, length = 1, avoidChars = '') {
let _pattern = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
_pattern += specialChars === true ? '(){}[]+-*/=' : '';
if (avoidChars && avoidChars.length) {
for (let char of avoidChars) {
_pattern = _pattern.replace(char, '');
}
}
let _random = '';
for (let element of new Array(parseInt(length))) {
_random += _pattern.charAt(Math.floor(Math.random() * _pattern.length));
}
return _random;
};
You can use like this :
// Generate password with specialChars which contains 10 chars and avoid iIlL chars
var password = String().randomGenerator(true, 10, 'iIlL');
Hope it helps.
Please Try with this. I hope it will work for you.
Create Procedure Test
(
@Table VARCHAR(500),
@Column VARCHAR(100),
@Value VARCHAR(300)
)
AS
BEGIN
DECLARE @sql nvarchar(1000)
SET @sql = 'SELECT * FROM ' + @Table + ' WHERE ' + @Column + ' = ' + @Value
--SELECT @sql
exec (@sql)
END
-----execution----
/** Exec Test Products,IsDeposit,1 **/
I had to embed my $location.path()
statement like this because my digest was still running:
function routeMe(data) {
var waitForRender = function () {
if ($http.pendingRequests.length > 0) {
$timeout(waitForRender);
} else {
$location.path(data);
}
};
$timeout(waitForRender);
}
I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.
eg: http://[email protected]/myresource/myid
This way it can also be passed as headers with basic-auth.
I've create a solution, mixed the information of varius post.
Its a form, that contains a label and one textbox. The console output is redirected to the textbox.
There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.
The forms is called FrmConsole. Here are the XAML and the c# code.
The use is very simple:
ConsoleView.Show("Title of the Console");
For open the console. Use:
System.Console.WriteLine("The debug message");
For output text to the console.
Use:
ConsoleView.Close();
For Close the console.
ConsoleView.Release();
Leaves open the console and enables the Close button
XAML
<Window x:Class="CustomControls.FrmConsole"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CustomControls"
mc:Ignorable="d"
Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
</Grid>
<Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>
The code of the Window:
partial class FrmConsole : Window
{
private class ControlWriter : TextWriter
{
private TextBox textbox;
public ControlWriter(TextBox textbox)
{
this.textbox = textbox;
}
public override void WriteLine(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void WriteLine(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.AppendText(Environment.NewLine);
textbox.ScrollToEnd();
}));
}
public override void Write(char value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value.ToString());
textbox.ScrollToEnd();
}));
}
public override void Write(string value)
{
textbox.Dispatcher.Invoke(new Action(() =>
{
textbox.AppendText(value);
textbox.ScrollToEnd();
}));
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
public FrmConsole(string titulo)
{
InitializeComponent();
lblTitulo.Content = titulo;
Clear();
btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
Console.SetOut(new ControlWriter(txtInner));
DesactivarCerrar();
}
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
private void BtnCerrar_Click(object sender, RoutedEventArgs e)
{
Close();
}
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public void ActivarCerrar()
{
btnCerrar.IsEnabled = true;
}
public void Clear()
{
txtInner.Clear();
}
public void DesactivarCerrar()
{
btnCerrar.IsEnabled = false;
}
#endregion
}
the code of ConsoleView class
static public class ConsoleView
{
//DEFINICIONES DE LA CLASE
#region DEFINICIONES DE LA CLASE
static FrmConsole console;
static Thread StatusThread;
static bool isActive = false;
#endregion
//CONSTRUCTORES DE LA CLASE
#region CONSTRUCTORES DE LA CLASE
#endregion
//PROPIEDADES
#region PROPIEDADES
#endregion
//DELEGADOS
#region DELEGADOS
#endregion
//METODOS Y FUNCIONES
#region METODOS Y FUNCIONES
public static void Show(string label)
{
if (isActive)
{
return;
}
isActive = true;
//create the thread with its ThreadStart method
StatusThread = new Thread(() =>
{
try
{
console = new FrmConsole(label);
console.ShowDialog();
//this call is needed so the thread remains open until the dispatcher is closed
Dispatcher.Run();
}
catch (Exception)
{
}
});
//run the thread in STA mode to make it work correctly
StatusThread.SetApartmentState(ApartmentState.STA);
StatusThread.Priority = ThreadPriority.Normal;
StatusThread.Start();
}
public static void Close()
{
isActive = false;
if (console != null)
{
//need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
console.Dispatcher.InvokeShutdown();
console = null;
StatusThread = null;
}
console = null;
}
public static void Release()
{
isActive = false;
if (console != null)
{
console.Dispatcher.Invoke(console.ActivarCerrar);
}
}
#endregion
}
I hope this result usefull.
I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path
and cookie_domain
settings to framework.session
fixed it.
It has a -force
parameter.????
FYI : How to download data in CSV from Kibana:
In Kibana--> 1. Go to 'Discover' in left side
Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )
left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable
Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv
Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV
Go to 'Management' in left side--> 'Reporting'-->download your csv
value_counts()
is now a DataFrame method since pandas 1.1.0
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html
Taking some of the things you have described:
"So you could be sure that some fields in a class are defined for every implementation of this interface."
"If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and not the constructor"
...these requirements are exactly what abstract classes are for.
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
try unpacking in one variable,
python will handle it as a list,
then unpack from the list
def returnATupleWithThreeValues():
return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3
To solve permission issue on ubuntu server, you just run this
sudo chmod 777 -R 'wordpress wp-content file location'
for example.
sudo chmod 777 -R /usr/share/wordpress/wp-content
I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
When you just want to execute one or several HTTP requests without having to wait for the response, there is a simple PHP solution, as well.
In the calling script:
$socketcon = fsockopen($host, 80, $errno, $errstr, 10);
if($socketcon) {
$socketdata = "GET $remote_house/script.php?parameters=... HTTP 1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socketcon, $socketdata);
fclose($socketcon);
}
// repeat this with different parameters as often as you like
On the called script.php, you can invoke these PHP functions in the first lines:
ignore_user_abort(true);
set_time_limit(0);
This causes the script to continue running without time limit when the HTTP connection is closed.
std::fill
is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.
For setting an array of primitive integer types to 0 specifically, memset
is fine, though it may raise eyebrows. Consider also calloc
, though it's a bit inconvenient to use from C++ because of the cast.
For my part, I pretty much always use a loop.
(I don't like to second-guess people's intentions, but it is true that std::vector
is, all things being equal, preferable to using new[]
.)
The &nKByte
creates a temporary value, which cannot be bound to a reference to non-const.
You could change void test(float *&x)
to void test(float * const &x)
or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);
.
Here I have converted Federico A. Ramponi's answer to PHP if anybody is interested:
<?php
# deg2rad and rad2deg are already within PHP
# Semi-axes of WGS-84 geoidal reference
$WGS84_a = 6378137.0; # Major semiaxis [m]
$WGS84_b = 6356752.3; # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
function WGS84EarthRadius($lat)
{
global $WGS84_a, $WGS84_b;
$an = $WGS84_a * $WGS84_a * cos($lat);
$bn = $WGS84_b * $WGS84_b * sin($lat);
$ad = $WGS84_a * cos($lat);
$bd = $WGS84_b * sin($lat);
return sqrt(($an*$an + $bn*$bn)/($ad*$ad + $bd*$bd));
}
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
function boundingBox($latitudeInDegrees, $longitudeInDegrees, $halfSideInKm)
{
$lat = deg2rad($latitudeInDegrees);
$lon = deg2rad($longitudeInDegrees);
$halfSide = 1000 * $halfSideInKm;
# Radius of Earth at given latitude
$radius = WGS84EarthRadius($lat);
# Radius of the parallel at given latitude
$pradius = $radius*cos($lat);
$latMin = $lat - $halfSide / $radius;
$latMax = $lat + $halfSide / $radius;
$lonMin = $lon - $halfSide / $pradius;
$lonMax = $lon + $halfSide / $pradius;
return array(rad2deg($latMin), rad2deg($lonMin), rad2deg($latMax), rad2deg($lonMax));
}
?>
<shameless-plug>
Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here
Feel free to post any issues/suggestions here.
</shameless-plug>
Just define an empty navbar prior to the fixed one, it will create the space needed.
<nav class="navbar navbar-default ">
</nav>
<nav class="navbar navbar-default navbar-fixed-top ">
<div class="container-fluid">
// Your menu code
</div>
</nav>
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
If you are getting this problem when converting wsdl to jave with the cxf-codegen-plugin, then you can solve it by configuring the plugin to fork and provide the additional "-Djavax.xml.accessExternalSchema=all" JVM option.
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<fork>always</fork>
<additionalJvmArgs>
-Djavax.xml.accessExternalSchema=all
</additionalJvmArgs>
why is it that even managed languages provide a finally-block despite resources being deallocated automatically by the garbage collector anyway?
Actually, languages based on Garbage collectors need "finally" more. A garbage collector does not destroy your objects in a timely manner, so it can not be relied upon to clean up non-memory related issues correctly.
In terms of dynamically-allocated data, many would argue that you should be using smart-pointers.
However...
RAII moves the responsibility of exception safety from the user of the object to the designer
Sadly this is its own downfall. Old C programming habits die hard. When you're using a library written in C or a very C style, RAII won't have been used. Short of re-writing the entire API front-end, that's just what you have to work with. Then the lack of "finally" really bites.
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools
SET @sql =
CONCAT( 'INSERT INTO <table_name> (',
(
SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') )
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_name>
AND column_name NOT IN ('id')
), ') SELECT ',
(
SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`'))
FROM information_schema.columns
WHERE table_schema = <database_name>
AND table_name = <table_source_name>
AND column_name NOT IN ('id')
),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );
PREPARE stmt1 FROM @sql;
execute stmt1;
Of course replace <> values with real values, and watch your quotes.
Markdownify converts HTML to Markdown, a plain-text formatting system used on this very site.
Fix memory leaks in your application with help of profile tools like eclipse MAT or VisualVM
With JDK 1.7.x
or later versions, use G1GC
, which spends 10% on garbage collection unlike 2% in other GC algorithms.
Apart from setting heap memory with -Xms1g -Xmx2g
, try `
-XX:+UseG1GC
-XX:G1HeapRegionSize=n,
-XX:MaxGCPauseMillis=m,
-XX:ParallelGCThreads=n,
-XX:ConcGCThreads=n`
Have a look at oracle article for fine-tuning these parameters.
Some question related to G1GC in SE:
Java 7 (JDK 7) garbage collection and documentation on G1
Would add a comment to @Steve Kehlet post but need 50 rep (RIP).
For anyone that has found this post through numerous googling, I found a way to not only find specific files given a time range, but also NOT include the relative paths OR whitespaces that would cause tarring errors. (THANK YOU SO MUCH STEVE.)
find . -name "*.pdf" -type f -mtime 0 -printf "%f\0" | tar -czvf /dir/zip.tar.gz --null -T -
.
relative directory
-name "*.pdf"
look for pdfs (or any file type)
-type f
type to look for is a file
-mtime 0
look for files created in last 24 hours
-printf "%f\0"
Regular -print0
OR -printf "%f"
did NOT work for me. From man pages:
This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use '\0' as a terminator than to use newline, as file names can contain white space and newline characters.
-czvf
create archive, filter the archive through gzip , verbosely list files processed, archive nameEdit 2019-08-14: I would like to add, that I was also able to use essentially use the same command in my comment, just using tar itself:
tar -czvf /archiveDir/test.tar.gz --newer-mtime=0 --ignore-failed-read *.pdf
Needed --ignore-failed-read
in-case there were no new PDFs for today.
Here's a nice method to fill in missing dates into a dataframe, with your choice of fill_value
, days_back
to fill in, and sort order (date_order
) by which to sort the dataframe:
def fill_in_missing_dates(df, date_col_name = 'date',date_order = 'asc', fill_value = 0, days_back = 30):
df.set_index(date_col_name,drop=True,inplace=True)
df.index = pd.DatetimeIndex(df.index)
d = datetime.now().date()
d2 = d - timedelta(days = days_back)
idx = pd.date_range(d2, d, freq = "D")
df = df.reindex(idx,fill_value=fill_value)
df[date_col_name] = pd.DatetimeIndex(df.index)
return df
Try following
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:
#!/usr/bin/python
Underneath which you would have the rest of the code (xx.py
in your case) that you already have. Then run that same command at the terminal:
$ python xx.py
This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python
tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.
string[][] table = { ... };
Open Project properties by selecting project then go to
View>Properties Windows
and make sure Anonymous Authentication is Enabled
From the nodejs documentation you should do this - always remember a string without knowing the encoding is just a bunch of bytes:
var readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', function(chunk) {
assert.equal(typeof chunk, 'string');
console.log('got %d characters of string data', chunk.length);
})
I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.
public static String readLine(Scanner scanner) {
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
String r = scanner.next();
scanner.useDelimiter(oldDelimiter);
return r;
}
pygame
on any platformThe advantage of using pygame
is that it can be made to work on any OS platform. Below example code is for GNU/Linux though.
First install the pygame
module for python3
as explained in detail here.
$ sudo pip3 install pygame
The pygame
module can play .wav
and .ogg
files from any file location. Here is an example:
#!/usr/bin/env python3
import pygame
pygame.mixer.init()
sound = pygame.mixer.Sound('/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga')
sound.play()
Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.
APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.
Reference: https://smartbear.com/learn/performance-monitoring/api-endpoints/
Try to use the empty()
function:
<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
<xsl:text>This should work</xsl:text>
</xsl:if>
This identifies ABC
and DEF
as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).
But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.
Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node
or if you iterate over the parent element of node
.
I had a ton of trouble with this and then found a great solution:
Create a file in a text editor called whoami.php with the below code as it's content, save the file and upload it to public_html (or whatever you root of your webserver directory is named). It should output a useful string that you can use to track down the user the webserver is running as, my output was "php is running as user: nt authority\iusr" which allowed me to track down the permissions I needed to modify to the user "IUSR".
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo 'php is running as user: ' . exec('whoami');
?>
There is a (commercial) product, "localFS" which can be used to read and write entire file-system on client computer.
Small Windows app must be installed and tiny .js file included in your page.
As a security feature, file-system access can be limited to one folder and protected with a secret-key.
Based upon your source variable (sourcePath = "C:\Minecraft\bin\"
) I suspect your hard code is pointing at the wrong place
fso.CopyFile "C:\Minecraft\options.txt", destinationPath, false
should be
fso.CopyFile "C:\Minecraft\bin\options.txt", destinationPath
or
fso.CopyFile sourcePath & "options.txt", destinationPath
first you must create 2 layout xml . after that inside recyclerview adapter TYPE_CALL and TYPE_EMAIL are two static values with 1 and 2 respectively in adapter class.
now Define two static values ??at the Recycler view Adapter class level for example : private static int TYPE_CALL = 1; private static int TYPE_EMAIL = 2;
Now create view holder with multiple views like this:
class CallViewHolder extends RecyclerView.ViewHolder {
private TextView txtName;
private TextView txtAddress;
CallViewHolder(@NonNull View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.txtName);
txtAddress = itemView.findViewById(R.id.txtAddress);
}
}
class EmailViewHolder extends RecyclerView.ViewHolder {
private TextView txtName;
private TextView txtAddress;
EmailViewHolder(@NonNull View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.txtName);
txtAddress = itemView.findViewById(R.id.txtAddress);
}
}
Now code as below in onCreateViewHolder and onBindViewHolder method in recyclerview adapter:
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
View view;
if (viewType == TYPE_CALL) { // for call layout
view = LayoutInflater.from(context).inflate(R.layout.item_call, viewGroup, false);
return new CallViewHolder(view);
} else { // for email layout
view = LayoutInflater.from(context).inflate(R.layout.item_email, viewGroup, false);
return new EmailViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (getItemViewType(position) == TYPE_CALL) {
((CallViewHolder) viewHolder).setCallDetails(employees.get(position));
} else {
((EmailViewHolder) viewHolder).setEmailDetails(employees.get(position));
}
}
I'm just a newbie here so maybe it's pure luck if I found this :
After trying to run a script from the interpreter prompt >>> with the command
execfile('filename.py')
for which I got a "NameError: name 'execfile' is not defined" I tried a very basic
import filename
it worked well :-)
I hope this can be helpful and thank you all for the great hints, examples and all those masterly commented pieces of code that are a great inspiration for newcomers !
I use Ubuntu 16.014 LTS x64. Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux
class MyParent:
def sayHi():
print('Mamma says hi')
from path.to.MyParent import MyParent
class ChildClass(MyParent):
pass
An instance of ChildClass
will then inherit the sayHi()
method.
select * from your_table where MONTH(mont_year) = MONTH(NOW()) and YEAR(mont_year) = YEAR(NOW());
Note: (month_year) means your column that contain date format. I think that will solve your problem. Let me know if that query doesn't works.
I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?
Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.
<img title="<a href="javascript:alert('hello world')">The Link</a>" />
Css classes are here
<style type="text/css">
.mymenu
{
background-color: blue;
color: white;
}
.newmenu
{
background-color: red;
color: white;
}
</style>
Make your HTML like this, Set url as id
<div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
<div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>
Here write javascript, put this javascript after the HTML code.
function menuHighlight() {
var url = window.location.href;
$('#'+tabst).addClass('new_current');
}
menuHighlight();
I was in the same place as you, finally I found a neat answer :
<form action="xx/xx" method="POST">
<input type="hidden" name="what you want" value="what you want">
<input type="image" src="xx.xx">
</form>
1. In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
In angular 4+ we can use innerHTML
property instead of ng-bind-html
.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
An open source GUI tool is available at keystore-explorer.org
KeyStore Explorer
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Following screens will help (they are from the official site)
Default screen that you get by running the command:
shantha@shantha:~$./Downloads/kse-521/kse.sh
And go to Examine
and Examine a URL
option and then give the web URL that you want to import.
The result window will be like below if you give google site link.
This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
The accepted answer is perfect. I had a related but slightly different situation where I had to fill in forward but only within groups. In case someone has the same need, know that fillna works on a DataFrameGroupBy object.
>>> example = pd.DataFrame({'number':[0,1,2,nan,4,nan,6,7,8,9],'name':list('aaabbbcccc')})
>>> example
name number
0 a 0.0
1 a 1.0
2 a 2.0
3 b NaN
4 b 4.0
5 b NaN
6 c 6.0
7 c 7.0
8 c 8.0
9 c 9.0
>>> example.groupby('name')['number'].fillna(method='ffill') # fill in row 5 but not row 3
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
5 4.0
6 6.0
7 7.0
8 8.0
9 9.0
Name: number, dtype: float64
I would take those directions to mean:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}
import os
import os.path
import shutil
You find your current directory:
d = os.getcwd() #Gets the current working directory
Then you change one directory up:
os.chdir("..") #Go up one directory from working directory
Then you can get a tupple/list of all the directories, for one directory up:
o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple
Then you can search the tuple for the directory you want and open the file in that directory:
for item in o:
if os.path.exists(item + '\\testfile.txt'):
file = item + '\\testfile.txt'
Then you can do stuf with the full file path 'file'
You need to open the file again using open()
, but this time passing 'w'
to indicate that you want to write to the file. I would also recommend using with
to ensure that the file will be closed when you are finished writing to it.
with open('Failed.txt', 'w') as f:
for ip in [k for k, v in ips.iteritems() if v >=5]:
f.write(ip)
Naturally you may want to include newlines or other formatting in your output, but the basics are as above.
The same issue with closing your file applies to the reading code. That should look like this:
ips = {}
with open('today','r') as myFile:
for line in myFile:
parts = line.split(' ')
if parts[1] == 'Failure':
if parts[0] in ips:
ips[pars[0]] += 1
else:
ips[parts[0]] = 0
I know this post is kinda old but...
As 'witttness' pointed out.
About Your Own Custom Theme You might choose to modify bootstrap-theme.css when creating your own theme. Doing so may make it easier to make styling changes without accidentally breaking any of that built-in Bootstrap goodness.
I see it as Bootstrap has seen over the years that everyone wants something a bit different than the core styles. While you could modify bootstrap.css it might break things and it could make updating to a newer version a real pain and time consuming. Downloading from a 'theme' site means you have to wait on if that creator updates that theme, big if sometimes, right?
Some build their own 'custom.css' file and that's ok, but if you use 'bootstrap-theme.css' a lot of stuff is already built and this allows you to roll your own theme faster 'without' disrupting the core of bootstrap.css. I for one don't like the 3D buttons and gradients most of the time, so change them using bootstrap-theme.css. Add margins or padding, change the radius to your buttons, and so on...
The problem is the linker is looking for libmagic.so
but you only have libmagic.so.1
A quick hack is to symlink libmagic.so.1
to libmagic.so
A simple solution is to restart the service when the system stops it.
I found this very simple implementation of this method:
It should be emphasized that since Python 3.6, you only need the standard lib to get a timezone aware datetime object that represents local time (the setting of your OS). Using astimezone()
import datetime
datetime.datetime(2010, 12, 25, 10, 59).astimezone()
# e.g.
# datetime.datetime(2010, 12, 25, 10, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))
datetime.datetime(2010, 12, 25, 12, 59).astimezone().isoformat()
# e.g.
# '2010-12-25T12:59:00+01:00'
# I'm on CET/CEST
(see @johnchen902's comment). Note there's a small caveat though, astimezone(None) gives aware datetime, unaware of DST.
I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.
I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.
This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.
You can try to create the AlertDialog
object first, and then use it to set up to change the color of the button and then show it. (Note that on builder
object instead of calling show()
we call create()
to get the AlertDialog
object:
//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).create();
//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT);
}
});
dialog.show()
The reason you have to do it on onShow()
and cannot just get that button after you create your dialog is that the button would not have been created yet.
I changed AlertDialog.BUTTON_POSITIVE
to AlertDialog.BUTTON_NEGATIVE
to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.
When attempting to export data using the accepted answer I got an error:
ERROR 1235 (42000) at line 3367: This version of MySQL doesn't yet support 'multiple triggers with the same action time and event for one table'
As mentioned above:
mysqldump --no-create-info
Will export the data but it will also export the create trigger statements. If like me your outputting database structure (which also includes triggers) with one command and then using the above command to get the data you should also use '--skip-triggers'.
So if you want JUST the data:
mysqldump --no-create-info --skip-triggers
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
Perl solutions:
perl -lpe 'print "Project_Name=sowstest" if $. == 8' file
-l
strips newlines and adds them back in, eliminating the need for "\n"-p
loops over the input file, printing every line-e
executes the code in single quotes$.
is the line number
perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file
-s
enables a rudimentary argument parser--
prevents -n and -s from being parsed by the standard perl argument parserperl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file
setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file
ENV
is the hash which contains all environment variables
perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file
perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file
Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done
If "ReferenceError: Model is not defined" error is raised, then you might try to use the following method:
$(document).ready(function () {
@{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(Model);
}
var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
var id= model.Id;
var mainFloorPlanId = model.MainFloorPlanId ;
var imageDirectory = model.ImageDirectory ;
var iconsDirectory = model.IconsDirectory ;
}
});
Hope this helps...
Just use in your if (key=="smk")
if (key=="smk") { window.open('http://www.smkproduction.eu5.org','_blank'); }
I hope this helps
//Setting default selected menu item and fragment
bottomNavigationView.setSelectedItemId(R.id.action_home);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new HomeFragment()).commit();
It is more of determining the default fragment loaded at the same time with the corresponding bottom navigation menu item. You can include the same in your OnResume callbacks
To see local changes compare to your current branch
git diff .
To see local changed compare to any other existing branch
git diff <branch-name> .
To see changes of a particular file
git diff <branch-name> -- <file-path>
Make sure you run git fetch
at the beginning.
GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.
for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically
For more information and for download
We've used a solution based on timeGetTime in winmm.dll for millisecond accuracy for many years. See http://www.aboutvb.de/kom/artikel/komstopwatch.htm
The article is in German, but the code in the download (a VBA class wrapping the dll function call) is simple enough to use and understand without being able to read the article.
Altova XmlSpy does this well - you can find an overview here
See if this is what you want to do:
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"
Recursion is your friend. I updated the function to account for property arrays:
function getObject(theObject) {
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = getObject(theObject[i]);
if (result) {
break;
}
}
}
else
{
for(var prop in theObject) {
console.log(prop + ': ' + theObject[prop]);
if(prop == 'id') {
if(theObject[prop] == 1) {
return theObject;
}
}
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
result = getObject(theObject[prop]);
if (result) {
break;
}
}
}
}
return result;
}
updated jsFiddle: http://jsfiddle.net/FM3qu/7/
To suppress output, use redirection to NUL
.
There are two kinds of output that console commands use:
standard output, or stdout
,
standard error, or stderr
.
Of the two, stdout
is used more often, both by internal commands, like copy
, and by console utilities, or external commands, like find
and others, as well as by third-party console programs.
>NUL
suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied.
message of the copy
command. An alternative syntax is 1>NUL
. So,
COPY file1 file2 >NUL
or
COPY file1 file2 1>NUL
or
>NUL COPY file1 file2
or
1>NUL COPY file1 file2
suppresses all of COPY
's standard output.
To suppress error messages, which are typically printed to stderr
, use 2>NUL
instead. So, to suppress a File Not Found
message that DEL
prints when, well, the specified file is not found, just add 2>NUL
either at the beginning or at the end of the command line:
DEL file 2>NUL
or
2>NUL DEL file
Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:
IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"
Java was unable to find the class A in runtime. Class A was in maven project ArtClient from a different workspace. So I imported ArtClient to my Eclipse project. Two of my projects was using ArtClient as dependency. I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
If you are using Adobe Acrobat X to make the form, set all the fields as you want them, then click File, Save As, Reader Extended PDF, Enable Additional Features. The resulting PDF form can be saved when filled in, if opened in versions of Adobe Reader before XI.
dynamic_cast should be what you are looking for.
EDIT:
DerivedType m_derivedType = m_baseType; // gives same error
The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.
DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error
You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.
Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):
DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);
If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.
Hope this helps!
Try this :
Bytes.toBytes(x).length
Assuming you declared and initialized x before
Inside Spring Boot
, I always put the webpages inside a folder like public
or webapps
or views
and place it inside src/main/resources
directory as you can see in application.properties
also.
and this is my application.properties
:
server.port=15800
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/hibernatedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
as soon you put the url like servername:15800
and this request received by Spring Boot occupied Servlet dispatcher it will exactly search the index.html
and this name will in case sensitive as the spring.mvc.view.suffix
which would be html, jsp, htm etc.
Hope it would help manyone.
Try the following:
Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);