With Angular 5, I solved a similar problem by ugrading to @angular/cli
1.6.1 from 1.5.5:
"devDependencies": {
"@angular/cli": "1.6.1"
}
During ng serve
the error I got was:
ERROR in Error: No NgModule metadata found for 'AppModule'.
at NgModuleResolver.resolve (/path/to/project/app/node_modules/@angular/compiler/bundles/compiler.umd.js:20247:23)
There is a slight performance benefit to setting the value in the declaration. If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor).
Let’s say we want to add a custom property (using aria-* or data-*) if a condition is true:
{...this.props.isTrue && {'aria-name' : 'something here'}}
Let’s say we want to add a style property if a condition is true:
{...this.props.isTrue && {style : {color: 'red'}}}
You can also cast (n,) to (n,1) by enclosing within brackets [ ].
e.g. Instead of np.append(b,a,axis=0)
use np.append(b,[a],axis=0)
a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)
returns
array([[5, 6],
[7, 8],
[1, 2]])
No, you cannot. Google Plus has been discontinued. Clicking any link for any answer here brings me to this text:
Google+ is no longer available for consumer (personal) and brand accounts
From all of us on the Google+ team,
thank you for making Google+ such a special place.
There is one section that reads that the product is continued for "G Suite," but as of Feb., 2020, the chat and social service listed for G Suite is Hangouts, not Google+.
The format https://plus.google.com/share?url=YOUR_URL_HERE
was documented at https://developers.google.com/+/web/share/
, but this documentation has since been removed, probably because no part of Google+ continues in development. If you are feeling nostalgic, you can see what the API used to say with an Archive.org link.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
I encountered this error using IIS 7.0 with a custom 404 error page, although I suspect this will happen with any 404 page. The server returned an html 404 response with a text/html mime type which could not (rightly) be executed.
This works for me (dont use the extension of the image, just the name):
String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);
str.charCodeAt(index)
Using charCodeAt()
The following example returns 65, the Unicode value for A
.
'ABC'.charCodeAt(0)
// returns 65
Try this, you will know the difference between change and modify,
ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]
ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
CHANGE
.MODIFY
. You cannot change the name of the column using this statement.Hope, I explained well in detail.
I think this thread may be helpful: http://forums.macosxhints.com/archive/index.php/t-70973.html
To paraphrase, you can rename it with the .command extension or create an AppleScript to run the shell.
For me, it turns out that there was an iOS system update pending asking to restart the computer. Restart and let the update finish solved my problem.
If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)
$("div.fetch_results input:text").each(function() {
this.value = "testing";
})?
This will select only the text input boxes within the div with a fetch_results class.
As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script> <script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>
Note: Copy / Pasted from comment. Be sure to like the original post!
Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:
this.props.location.query
It creates a hash of all available query params in the url.
For React-Router v4, see this answer. Basically, use this.props.location.search
to get the query string and parse with the query-string
package or URLSearchParams:
const params = new URLSearchParams(paramsString);
const tags = params.get('tags');
You may be interested by the pack_forget
and grid_forget
methods of a widget. In the following example, the button disappear when clicked
from Tkinter import *
def hide_me(event):
event.widget.pack_forget()
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()
If you have forked a repository fro Delete your forked copy and fork it again from master.
Have you looked in firebug if POST or GET?.
check the console display.
Put in the test script:
console.log(data);
You can see the response from the server, if it shows something.
It's easier and cleaner to do it with CSS.
HTML:
<div ng-repeat="file in files" class="file">
{{ file.name }}
</div>
CSS:
.file:last-of-type {
color: #800;
}
The :last-of-type
selector is currently supported by 98% of browsers
If the object is actually a Boolean
instance, then just cast it:
boolean di = (Boolean) someObject;
The explicit cast will do the conversion to Boolean
, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:
boolean di = ((Boolean) someObject).booleanValue();
If someObject
doesn't refer to a Boolean value though, what do you want the code to do?
Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.
Start with a subset of the original data:
datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200,
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600,
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000,
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct",
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44,
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18,
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88,
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73,
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97,
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75,
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01,
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax",
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")
You can get the desired effect by (and this also cleans up the original plotting code):
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
breaks = c("TempMax", "TempMedia", "TempMin"),
values = c("red", "green", "blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
The idea is that each line is given a color by mapping the colour
aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y
variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes
call; you are creating a mapping to this "variable".
scale_colour_manual
can now map these strings to the appropriate colors. The result is
In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
values = c("TempMedia"="green", "TempMax"="red",
"TempMin"="blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.
ggplot(data = datos, aes(x = fecha)) +
geom_line(aes(y = TempMax, colour = "TempMax")) +
geom_line(aes(y = TempMedia, colour = "TempMedia")) +
geom_line(aes(y = TempMin, colour = "TempMin")) +
scale_colour_manual("",
breaks = c("TempMedia", "TempMax", "TempMin"),
values = c("TempMedia"="green", "TempMax"="red",
"TempMin"="blue")) +
xlab(" ") +
scale_y_continuous("Temperatura (C)", limits = c(-10,40)) +
labs(title="TITULO")
You can throw your own custom errors by extending the Exception class.
class CustomException : Exception {
[string] $additionalData
CustomException($Message, $additionalData) : base($Message) {
$this.additionalData = $additionalData
}
}
try {
throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
# NOTE: To access your custom exception you must use $_.Exception
Write-Output $_.Exception.additionalData
# This will produce the error message: Didn't catch it the second time
throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
The BrightCloud web service API is perfect for this. It's a REST API for doing website lookups just like this. It contains a very large and very accurate web filtering DB and one of the categories, Adult, has over 10M porn sites identified!
ng g c componentname
By using above command New Component will be created in a folder with
(componentname) you specified above.
here's an example for bash:
usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything
where:
-h show this help text
-s set the seed value (default: 42)"
seed=42
while getopts ':hs:' option; do
case "$option" in
h) echo "$usage"
exit
;;
s) seed=$OPTARG
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
To use this inside a function:
"$FUNCNAME"
instead of $(basename "$0")
local OPTIND OPTARG
before calling getopts
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
SET "found=%%a"
SET /a foundpid=!found:~26,8!
IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)
GOTO :EOF
...set PID to suit your circumstance.
Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:
var some_function = function(username, password)
{
return new Promise(function(resolve, reject)
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
}
Then, use it:
some_module.some_function(username, password).then(function(uid)
{
// stuff
})
ES6:
const some_function = (username, password) =>
{
return new Promise((resolve, reject) =>
{
/*stuff using username, password*/
if ( /* everything turned out fine */ )
{
resolve("Stuff worked!");
}
else
{
reject(Error("It broke"));
}
});
};
Use:
some_module.some_function(username, password).then(uid =>
{
// stuff
});
Here is the simple one line fix without css.
{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
I think this is the simplest way:
<select onchange="if (this.value) window.location.href=this.value">
<option value="">Pick one:</option>
<option value="/foo">Foo</option>
<option value="/bar">Bar</option>
</select>
Would like to take credit for this but I found a solution here:
https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable
add the following to the css for the anchor:
a.svg {
position: relative;
display: inline-block;
}
a.svg:after {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left:0;
}
<a href="#" class="svg">
<object data="random.svg" type="image/svg+xml">
<img src="random.jpg" />
</object>
</a>
Link works on the svg and on the fallback.
Okay, I figured this out.
You will need html2canvas and pdfmake. You do NOT need to do any injection in your app.js to either, just include in your script tags
On the div that you want to create the PDF of, add an ID name like below:
<div id="exportthis">
In your Angular controller use the id of the div in your call to html2canvas:
change the canvas to an image using toDataURL()
Then in your docDefinition for pdfmake assign the image to the content.
The completed code in your controller will look like this:
html2canvas(document.getElementById('exportthis'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500,
}]
};
pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
}
});
I hope this helps someone else. Happy coding!
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
If you only want to sort only on the 5th field then use -k5,5
.
Also, use the -t
command line switch to specify the delimiter to tab
. Try this:
sort -k5,5 -r -n -t \t filename
or if the above doesn't work (with the tab
) this:
sort -k5,5 -r -n -t $'\t' filename
The man page for sort states:
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
Finally, this SO question Unix Sort with Tab Delimiter might be helpful.
Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".
In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.
All the answers so far are mathematically wrong. Returning rand() % N
does not uniformly give a number in the range [0, N)
unless N
divides the length of the interval into which rand()
returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand()
are independent: it's possible that they go 0, 1, 2, ...
, which is uniform but not very random. The only assumption it seems reasonable to make is that rand()
puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand()
are nicely scattered.
This means that the only correct way of changing the range of rand()
is to divide it into boxes; for example, if RAND_MAX == 11
and you want a range of 1..6
, you should assign {0,1}
to 1, {2,3}
to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.
The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double
is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.
The correct way is to use integer arithmetic. That is, you want something like the following:
#include <stdlib.h> // For random(), RAND_MAX
// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = random();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random()
rather than rand()
as it has a better distribution (as noted by the man page for rand()
).
If you want to get random values outside the default range [0, RAND_MAX]
, then you have to do something tricky. Perhaps the most expedient is to define a function random_extended()
that pulls n
bits (using random_at_most()
) and returns in [0, 2**n)
, and then apply random_at_most()
with random_extended()
in place of random()
(and 2**n - 1
in place of RAND_MAX
) to pull a random value less than 2**n
, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max]
using min + random_at_most(max - min)
, including negative values.
There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor)
and .AddFromFile(Filename)
. Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile
because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.
The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)
If you are having problems getting the code to run, there are two possible issues.
Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.
Main activity class to take pick and upload
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class MainActivity extends Activity {
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "Paste your URL here";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btpic = (Button) findViewById(R.id.cpic);
btpic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clickpic();
}
});
btnup = (Button) findViewById(R.id.up);
btnup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
upload();
}
});
}
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
//ba1 = Base64.encodeBytes(ba);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
private void clickpic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
imageView.setImageBitmap(photo);
}
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
@Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
}
php code to handle upload image and also create image from base64 encoded data
<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
echo "Image uploaded";
}else{
echo "Error uploading image";
}
}
?>
I was having the same problem. Turns out in my case, I was missing the comma after the last column. 30 minutes of my life wasted, I will never get back!
Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function
It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:
if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
...
fi
(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
According to the standard (§6.4.4.4/10)
The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.
long x = '\xde\xad\xbe\xef'; // yes, single quotes
This is valid ISO 9899:2011 C. It compiles without warning under gcc
with -Wall
, and a “multi-character character constant” warning with -pedantic
.
From Wikipedia:
Multi-character constants (e.g. 'xy') are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into one int is not specified, portable use of multi-character constants is difficult.
For portability sake, don't use multi-character constants with integral types.
SCP Commend
Send File from Local To Remote Server
sudo scp -i ../Downloads/new_bb_key.pem ./dump.zip [email protected]:~/.
Send File from Remote Server To Local
sudo scp -i ~/Downloads/new_bb_key.pem [email protected]:/home/ubuntu/LatestDBdump.zip Downloads/
You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
Append new column in existing csv file using python without header name
default_text = 'Some Text'
# Open the input_file in read mode and output_file in write mode
with open('problem-one-answer.csv', 'r') as read_obj, \
open('output_1.csv', 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
csv_reader = reader(read_obj)
# Create a csv.writer object from the output file object
csv_writer = csv.writer(write_obj)
# Read each row of the input csv file as list
for row in csv_reader:
# Append the default text in the row / list
row.append(default_text)
# Add the updated row / list to the output file
csv_writer.writerow(row)
Thankyou
You can't quite yet from what I read in the FAQ:
Do Go programs link with C/C++ programs?
There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs.
The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.
$ git commit --allow-empty -m "Trigger Build"
A simple method
private boolean isValidEmail(String email)
{
String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if(email.matches(emailRegex))
{
return true;
}
return false;
}
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
--USER and SCHEMA
The both words user and schema are interchangeble,thats why most people get confusion on this words below i explained the difference between them
--User User is a account to connect database(Server). we can create user by using CREATE USER user_name IDENTIFIED BY password .
--Schema
Actually Oracle Database contain logical and physical strucutre to process the data.The Schema Also Logical Structure to process the data in Database(Memory Component). Its Created automatically by oracle when user created.It Contains All Objects created by the user associated to that schema.For Example if i created a user with name santhosh then oracle createts a schema called santhosh,oracle stores all objects created by user santhosh in santhosh schema.
We can create schema by CREATE SCHEMA statement ,but Oracle Automatically create a user for that schema.
We can Drop the schema by using DROP SCHEMA schama_name RESTRICT statement but it can not delete scehema contains objects,so to drop schema it must be empty.here the restrict word forcely specify that schema with out objects.
If we try to drop a user contain objects in his schema we must specify CASCADE word because oracle does not allow you to delete user contain objects. DROP USER user_name CASCADE so oracle deletes the objects in schema and then it drops the user automatically,Objects refered to this schema objects from other schema like views and private synonyms goes to invalid state.
I hope now you got the difference between them,if you have any doubts on this topic,please feel free to ask.
Thank you.
I found that adding "-i" to the commit command fixes this problem for me. The -i basically tells it to stage additional files before committing. That is:
git commit -i myfile.php
I like Dan Moulding's answer, I'll just add a bit of C++ style to it:
#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>
int to_int(const std::string &s, int base = 0)
{
char *end;
errno = 0;
long result = std::strtol(s.c_str(), &end, base);
if (errno == ERANGE || result > INT_MAX || result < INT_MIN)
throw std::out_of_range("toint: string is out of range");
if (s.length() == 0 || *end != '\0')
throw std::invalid_argument("toint: invalid string");
return result;
}
It works for both std::string and const char* through the implicit conversion. It's also useful for base conversion, e.g. all to_int("0x7b")
and to_int("0173")
and to_int("01111011", 2)
and to_int("0000007B", 16)
and to_int("11120", 3)
and to_int("3L", 34);
would return 123.
Unlike std::stoi
it works in pre-C++11. Also unlike std::stoi
, boost::lexical_cast
and stringstream
it throws exceptions for weird strings like "123hohoho".
NB: This function tolerates leading spaces but not trailing spaces, i.e. to_int(" 123")
returns 123 while to_int("123 ")
throws exception. Make sure this is acceptable for your use case or adjust the code.
Such function could be part of STL...
Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.
To get the cell value, you need to read it directly from DataGridView1
using e.RowIndex
and e.ColumnIndex
properties.
Eg:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If IsDBNull(value) Then
TextBox1.Text = "" ' blank if dbnull values
Else
TextBox1.Text = CType(value, String)
End If
End Sub
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
Multiline comment in django templates use as follows ex: for .html etc.
{% comment %} All inside this tags are treated as comment {% endcomment %}
find . -name "*.ear" | xargs ls -sh
Clone your fork:
git clone [email protected]:YOUR-USERNAME/YOUR-FORKED-REPO.git
Add remote from original repository in your forked repository:
cd into/cloned/fork-repo
git remote add upstream git://github.com/ORIGINAL-DEV-USERNAME/REPO-YOU-FORKED-FROM.git
git fetch upstream
Updating your fork from original repo to keep up with their changes:
git pull upstream master
git push
Another way to do this for the whole app is using reflection based on this answer
public class TypefaceUtil {
/**
* Using reflection to override default typefaces
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE
* OVERRIDDEN
*
* @param typefaces map of fonts to replace
*/
public static void overrideFonts(Map<String, Typeface> typefaces) {
try {
final Field field = Typeface.class.getDeclaredField("sSystemFontMap");
field.setAccessible(true);
Map<String, Typeface> oldFonts = (Map<String, Typeface>) field.get(null);
if (oldFonts != null) {
oldFonts.putAll(typefaces);
} else {
oldFonts = typefaces;
}
field.set(null, oldFonts);
field.setAccessible(false);
} catch (Exception e) {
Log.e("TypefaceUtil", "Can not set custom fonts");
}
}
public static Typeface getTypeface(int fontType, Context context) {
// here you can load the Typeface from asset or use default ones
switch (fontType) {
case BOLD:
return Typeface.create(SANS_SERIF, Typeface.BOLD);
case ITALIC:
return Typeface.create(SANS_SERIF, Typeface.ITALIC);
case BOLD_ITALIC:
return Typeface.create(SANS_SERIF, Typeface.BOLD_ITALIC);
case LIGHT:
return Typeface.create(SANS_SERIF_LIGHT, Typeface.NORMAL);
case CONDENSED:
return Typeface.create(SANS_SERIF_CONDENSED, Typeface.NORMAL);
case THIN:
return Typeface.create(SANS_SERIF_MEDIUM, Typeface.NORMAL);
case MEDIUM:
return Typeface.create(SANS_SERIF_THIN, Typeface.NORMAL);
case REGULAR:
default:
return Typeface.create(SANS_SERIF, Typeface.NORMAL);
}
}
}
then whenever you want to override the fonts you can just call the method and give it a map of typefaces as follows:
Typeface regular = TypefaceUtil.getTypeface(REGULAR, context);
Typeface light = TypefaceUtil.getTypeface(REGULAR, context);
Typeface condensed = TypefaceUtil.getTypeface(CONDENSED, context);
Typeface thin = TypefaceUtil.getTypeface(THIN, context);
Typeface medium = TypefaceUtil.getTypeface(MEDIUM, context);
Map<String, Typeface> fonts = new HashMap<>();
fonts.put("sans-serif", regular);
fonts.put("sans-serif-light", light);
fonts.put("sans-serif-condensed", condensed);
fonts.put("sans-serif-thin", thin);
fonts.put("sans-serif-medium", medium);
TypefaceUtil.overrideFonts(fonts);
for full example check
This only works for Android SDK 21 and above for earlier versions check the full example
I find that using Apache Commons IO makes my life much easier.
String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");
You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.
Take a look at the PDOStatement.fetchAll
method. You could also use fetch
in an iterator pattern.
Code sample for fetchAll
, from the PHP documentation:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Results:
Array
(
[0] => Array
(
[NAME] => pear
[COLOUR] => green
)
[1] => Array
(
[NAME] => watermelon
[COLOUR] => pink
)
)
Azure DB, Azure Data WH and from SQL Server 2016, you can use STRING_SPLIT to achieve a similar result to what was described by @sparrow.
Recycling code from @sparrow
WHERE user_id IN (SELECT value FROM STRING_SPLIT( @user_id_list, ',')
Simple and effective way of accepting a list of values into a Stored Procedure
This will return query parameters as an associative array
var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
if(query[i]){
var temp = query[i].split("=");
queryParams[temp[0]] = temp[1]
}
}
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
You can delete newlines with tr
:
var=`hg st -R "$path" | tr -d '\n'`
if [ -n $var ]; then
echo $var
done
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
If you are using pgAdmin3, expand 'Sequences,' right click on a sequence, go to 'Properties,' and in the 'Definition' tab change 'Current value' to whatever value you want. There is no need for a query.
My problem ended up being that I did not understand the signtool options. I had provided the /n option with something that did not match my certificate. When I removed that it stopped complaining.
I got the same problem, but things got complicated when I added few other libraries like appcompat.v7, recyclerView, CardView.
Removing appcompat.v4 from lib did not work for me.
I had to create project from start and first step I did is to remove appcompat.v4 from libs folder, and this worked.
I had just started the project so creating a new project wasn't a big issue for me!!!
The code below resolved the issue
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3
First you have to sort
the dataframe
by the count
column max
to min
if it's not sorted that way already. In your post, it is in the right order already but I will sort
it anyways:
dataframe.sort_index(by='count', ascending=[False])
col count
0 apple 5
1 sausage 2
2 banana 2
3 cheese 1
Then you can output the col
column to a list:
dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']
This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.
What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.
The latter alternative is used for methods on mocks that return void
.
Please have a look, for example, here: How to make mock to void methods with mockito
Adding this for completeness. If you (like me) use a script in your package.json
file, just add the --timeout
option to mocha:
"scripts": {
"test": "mocha 'test/**/*.js' --timeout 10000",
"test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},
Then you can run npm run test
to run your test suite with the timeout set to 10,000 milliseconds.
Why invent wheels yourself while there is a car ready for you? I just find this tools super easy and intuitive to use: Advanced Installer. This one minute video should be enough to impress you. Here is the illustrative user guide.
It depends on the time format of the user's operating system when the web browser was launched.
So:
<input type="time">
element as --:--
(time range: 00:00–23:59). --:-- --
(time range: 12:00 AM – 11:59 PM). And (as of this writing), browser support is only about 75% (caniuse). Yay: Edge, Chrome, Opera, Android. Boo: IE, Firefox, Safari).
You can do something like this:
<html>
<head><title>My Glossary</title></head>
<body style="margin:0px;">
<div id="top" style="position:fixed;background:white;width:100%;">
<a href="#A">A</a> |
<a href="#B">B</a> |
<a href="#Z">Z</a>
</div>
<div id="term-defs" style="padding-top:1em;">
<dl>
<span id="A"></span>
<dt>foo</dt>
<dd>This is the sound made by a fool</dd>
<!-- and so on ... ->
</dl>
</div>
</body>
</html>
It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.
Hope this helps.
The error message depends on distribution / compiler version:
Ubuntu Saucy:
/usr/bin/ld: /mnt/root/ffmpeg-2.1.1//libavformat/libavformat.a(http.o): undefined reference to symbol 'inflateInit2_'
/lib/x86_64-linux-gnu/libz.so.1: error adding symbols: DSO missing from command line
Ubuntu Raring: (more informative)
/usr/bin/ld: note: 'uncompress' is defined in DSO /lib/x86_64-linux-gnu/libz.so.1 so try adding it to the linker command line
Solution: You may be missing a library in your compilation steps, during the linking stage. In my case, I added '-lz' to makefile / GCC flags.
Background: DSO is a dynamic shared object or a shared library.
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
I was trying something similar to ensure the -ggdb
flag was present.
Call make in a clean directory and grep the flag you are looking for. Looking for debug
rather than ggdb
I would just write.
make VERBOSE=1 | grep debug
The -ggdb
flag was obscure enough that only the compile commands popped up.
I had the same problem. The solution was to update IntelliJ to the newest version.
the solution is you have to change the time out value to at least 15000ms(milliseconds)as milli is less than seconds, it will be in an instance.. no need of restarting. We should give some time for emulator to upload files for complete run. It depends on our system configurations.
Go to windows->perspectives->android->DDMS->timeout
to 15000.
this will work...change the time if it is not working.increase the heap size and try to manipulate the Api minimum level.
A friend function is not a member function, so the problem is that you declare operator<<
as a friend of A
:
friend ostream& operator<<(ostream&, A&);
then try to define it as a member function of the class logic
ostream& logic::operator<<(ostream& os, A& a)
^^^^^^^
Are you confused about whether logic
is a class or a namespace?
The error is because you've tried to define a member operator<<
taking two arguments, which means it takes three arguments including the implicit this
parameter. The operator can only take two arguments, so that when you write a << b
the two arguments are a
and b
.
You want to define ostream& operator<<(ostream&, const A&)
as a non-member function, definitely not as a member of logic
since it has nothing to do with that class!
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a.number;
}
You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:
throw;
If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.
Basically, it should be deemed a criminal offense to use "throw ex".
The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).
So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.
If you have a text box to type the file path, just use sendkeys to input the file path and click on submit button. If there is no text box to type the file path and only able to click on browse button and to select the file from windows popup, you can use AutoIt tool, see the step below to use AutoIt for the same,
Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/
Open Programs -> Autoit tool -> SciTE Script Editor.
Paste the following code in Autoit editor and save it as “filename.exe “(eg: new.exe)
Then compile and build the file to make it exe. (Tools ? Compile)
Autoit Code:
WinWaitActive("File Upload"); Name of the file upload window (Windows Popup Name: File Upload)
Send("logo.jpg"); File name
Send("{ENTER}")
Then Compile and Build from Tools menu of the Autoit tool -> SciTE Script Editor.
Paste the below Java code in Eclipse editor and save
Java Code:
driver.findElement(By.id("uploadbutton")).click; // open the Upload window using selenium
Thread.sleep("20000"); // wait for page load
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Documents and Settings\\new.exe"); // Give path where the exe is saved.
The accepted convention of passing C-strings to functions is to use a pointer:
void function(char* name)
When the function modifies the string you should also pass in the length:
void function(char* name, size_t name_length)
Your first example:
char *functionname(char *string name[256])
passes an array of pointers to strings which is not what you need at all.
Your second example:
char functionname(char string[256])
passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:
char functionname(char *string)
See also this question for more details on array arguments in C.
If you want to jump directly to the desired position in a listView just use
listView.setSelection(int position);
and if you want to jump smoothly to the desired position in listView just use
listView.smoothScrollToPosition(int position);
Have you tried driver.implicitly_wait
. It is like a setting for the driver, so you only call it once in the session and it basically tells the driver to wait the given amount of time until each command can be executed.
driver = webdriver.Chrome()
driver.implicitly_wait(10)
So if you set a wait time of 10 seconds it will execute the command as soon as possible, waiting 10 seconds before it gives up. I've used this in similar scroll-down scenarios so I don't see why it wouldn't work in your case. Hope this is helpful.
To be able to fix this answer, I have to add new text. Be sure to use a lower case 'w' in implicitly_wait
.
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
@nombre_row :nombre ligne par page
@page:numero de la page
//--------------code sql---------------
declare @page int,@nombre_row int;
set @page='2';
set @nombre_row=5;
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY etudiant_ID ) AS RowNum, *
FROM etudiant
) AS RowConstrainedResult
WHERE RowNum >= ((@page-1)*@nombre_row)+1
AND RowNum < ((@page)*@nombre_row)+1
ORDER BY RowNum
Adding spring.jpa.database-platform=org.hibernate.dialect.MariaDB53Dialect
to my properties file worked for me.
PS: i'm using MariaDB
CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit
-prefixed declarations, and WebKit-based browsers will not understand -moz
-prefixed declarations.
Because of this, we can simply declare width
twice:
elem {
width: 100%;
width: -moz-available; /* WebKit-based browsers will ignore this. */
width: -webkit-fill-available; /* Mozilla-based browsers will ignore this. */
width: fill-available;
}
The width: 100%
declared at the start will be used by browsers which ignore both the -moz
and -webkit
-prefixed declarations or do not support -moz-available
or -webkit-fill-available
.
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
The selected answer is only for Safari. At the moment it's not possible to do real remote debugging in Chrome on iOS, but as with most mobile browsers you can use WeInRe for some simple debugging. It's a bit work to set up, but lets you inspect the DOM, see styling, change DOM and play with the console.
To setup:
npm install -g weinre
weinre --boundHost -all-
The bookmarklet is a bit more of an hassle to install. It's easiest if you have bookmark-sync turned on for both desktop and mobile Chrome. Copy the bookmarklet url from the local weinre server (same as above). Unfortunately it doesn't work because it's not url-encoded properly. So open the JavaScript console and type in:
copy(encodeURI('')); // paste bookmarklet inside quotes
You should now have the url-encoded bookmarklet in your clipboard. Paste it into a new bookmark under Mobile Bookmarks. Call it weinre or something simple to type. It should be synced to your mobile pretty fast, so load the page you want to inspect. Then type in the bookmark name in the url-bar, and you should see the bookmarklet as an auto-complete-suggestion. Click it to run bookmarklet code :)
Here are a few additional tips on testing rules that may ease the debugging for users on shared hosting
When testing a new rule, add a condition to only execute it with a fake
user-agent that you will use for your requests. This way it will not affect anyone else on your site.
e.g
#protect with a fake user agent
RewriteCond %{HTTP_USER_AGENT} ^my-fake-user-agent$
#Here is the actual rule I am testing
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [L,R=302]
If you are using Firefox, you can use the User Agent Switcher to create the fake user agent string and test.
I have seen so many posts where people are still testing their rules and they are using 301's. DON'T.
If you are not using suggestion 1 on your site, not only you, but anyone visiting your site at the time will be affected by the 301.
Remember that they are permanent, and aggressively cached by your browser. Use a 302 instead till you are sure, then change it to a 301.
If your rule does not work and it looks right to you, and you were not using suggestions 1 and 2, then re-test after clearing your browser cache or while in private browsing.
Use a HTTP capture tool like Fiddler to see the actual HTTP traffic between your browser and the server.
While others might say that your site does not look right
, you could instead see and report that all of the images, css and js are returning 404 errors
, quickly narrowing down the problem.
While others will report that you started at URL A and ended at URL C
, you will be able to see that they started at URL A, were 302 redirected to URL B and 301 redirected to URL C
. Even if URL C was the ultimate goal, you will know that this is bad for SEO and needs to be fixed.
You will be able to see cache headers that were set on the server side, replay requests, modify request headers to test ....
Let's say you have a path with a file in this format:
/dirA/dirB/dirC/filename.file
Now you only want the path which includes four "/". Type
$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"
and your output will be
/dirA/dirB/dirC
The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type
$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"
your output would be
/dirA/dirB
Though you can do the same from the other side of the string, it would not make that much sense in this case as typing
$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"
results in
dirA/dirB/dirC
In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
Anybody can try the following (mailto function only accepts plaintext but here i show how to use HTML innertext properties and how to add an anchor as mailto body params):
//Create as many html elements you need.
const titleElement = document.createElement("DIV");
titleElement.innerHTML = this.shareInformation.title; // Just some string
//Here I create an <a> so I can use href property
const titleLinkElement = document.createElement("a");
titleLinkElement.href = this.shareInformation.link; // This is a url
...
let mail = document.createElement("a");
// Using es6 template literals add the html innerText property and anchor element created to mailto body parameter
mail.href =
`mailto:?subject=${titleElement.innerText}&body=${titleLinkElement}%0D%0A${abstractElement.innerText}`;
mail.click();
// Notice how I use ${titleLinkElement} that is an anchor element, so mailto uses its href and renders the url I needed
You can use HeaderTemplate property to setup the head programatically or use ListView instead if you are using .NET 3.5.
Personally, I prefer ListView over GridView and DetailsView if possible, it gives you more control over your html.
You can use regular expressions to get the occurrences:
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
If you don't like the mangled name, you can dictate your own name:
@objc(CalendarViewController) class CalendarViewController : UIViewController {
// ...
}
However, it would be better in the long run to learn to parse the mangled name. The format is standard and meaningful and won't change.
In addition you can add
profile.setPreference("browser.download.panel.shown",false);
To remove the downloaded file list that gets shown by default and covers up part of the web page.
My total settings are:
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.merge(capabillities);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setPreference("browser.download.folderList", 4);
profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.panel.shown",false);
dc.setCapability(FirefoxDriver.PROFILE, profile);
this.driver = new FirefoxDriver(dc);
This is most likely because you have multiple accounts, like one private, one for work with GitHub.
SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub
SOLUTION OnMac, issue following on terminal:
git remote set-url origin https://[email protected]/username/repo-name.git
by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
Put the div in another div and set the parent div's style to position:relative;
Then on the child div set the following CSS properties: position:absolute; bottom:0;
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
If you'd like to get the option with a value of 2, use
$("#list option[value='2']").text();
If you'd like to get whichever option is currently selected, use
$("#list option:selected").text();
Answer to your first question is : both are similar,
Answer to your second question is: one-to-many --> a MAN(MAN table) may have more than one wife(WOMEN table) many-to-one --> more than one women have married one MAN.
Now if you want to relate this relation with two tables MAN and WOMEN, one MAN table row may have many relations with rows in the WOMEN table. hope it clear.
this is an out of topic answer, but, for those who are interested, it maybe valuable.
As in @John Kugelman's answer, % is related to job specification. how to efficiently find that? use less's &pattern command, seems man use less pager (not that sure), in man bash type &% then type Enter will only show lines that containing '%', to reshow all, type &. then Enter.
You could use a single ActionResult
to deal with both Post
and Get
:
public ActionResult Example() {
if (Request.HttpMethod.ToUpperInvariant() == "GET") {
// GET
}
else if (Request.HttpMethod.ToUpperInvariant() == "POST") {
// Post
}
}
Useful if your Get
and Post
methods have matching signatures.
?vector
X <- vector(mode="character", length=10)
This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default
displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.
> X[5] <- "character element in 5th position"
> X
[1] "" ""
[3] "" ""
[5] "character element in 5th position" ""
[7] "" ""
[9] "" ""
> nchar(X)
[1] 0 0 0 0 33 0 0 0 0 0
> length(X)
[1] 10
https://developers.google.com/chrome-developer-tools/docs/settings
Here are some differences between the two:
*Though APM is a separated tool, it's bundled and installed automatically with Atom
you must check these few things:
I had the same problem, and it solved after I changed username to ubuntu. In AWS documentation was mentioned to user ec2-user but somehow does not work for me.
select 1 from table
will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:
if exists(select 1 from table where some_column = 'some_value')
What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:
1) performance & you might retrieve more data than you actually need.
2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.
Jut use
ArrayAdapter<String> adaptername = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, your array list);
For Linux Users
Your app is not getting the path of android-sdk, so If you are using linux (ubuntu), than you need to add a file named "local.properties" and save it inside the android folder, which is created inside your app folder.
You need to add below line inside local.properties file, which is the path of your android-sdk lies inside your system inside system in order to run the app.
sdk.dir=/opt/android-sdk/
save and rerun the command react-native run-android
OR
you can open terminal, type
sudo nano ~/.bashrc
and paste the below path at the end of the file
export ANDROID_HOME="/opt/android-sdk/"
and restart your computer and run again react-native run-android after that.
Note:- If you put set path in .bashrc file, then you don't even need to create local.properties file.
You can try this. :) simple solution!
=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")
Yes, mobile device management would bring its own problems, but i bet 'Failure' is a dos2unix problem. On my Linux machines, adb is appending a DOS newline which causes 'Failure' because uninstall thinks the CR character is part of the package name. Also remove '-1.apk' from the end of the package-1.apk filename.
adb root
adb shell
pm list packages
pm uninstall com.android.chrome
In my case, i have a phone that is in permanent 'Safe mode' so only apps under /system/app/ have a chance of running. So i install them to get the .apk files copied off, then uninstall in bulk and copy to /system/app/, wipe the /cache and reboot. Now i have more apps running even though in safe mdoe.
# adb root
# pm list packages -3 > /root/bulkuninstall.txt
# vi /root/bulkuninstall.txt and check ^M characters at end of each line.
If ^M, then must run dos2unix /root/bulkuninstall.txt.
Remove '-1.apk' using vi search and replace:
:%s/-1\.apk//g
Or sed...
# cp /data/app/* /storage/sdcard1/APKs/
# for f in `cat /root/bulkuninstall.txt`; do echo $f; pm uninstall $f; done;
#
# echo Now remount system and copy the APK files to /system/app/
# mount | grep system
# mount -o remount,rw /dev/block/(use block device from previous step) /system
# cp /storage/sdcard1/APKs/* /system/app/
# reboot
wipe cache power on.
You can limit mongod process usage using cgroups on Linux.
Using cgroups, our task can be accomplished in a few easy steps.
Create control group:
cgcreate -g memory:DBLimitedGroup
(make sure that cgroups binaries installed on your system, consult your favorite Linux distribution manual for how to do that)
Specify how much memory will be available for this group:
echo 16G > /sys/fs/cgroup/memory/DBLimitedGroup/memory.limit_in_bytes
This command limits memory to 16G (good thing this limits the memory for both malloc allocations and OS cache)
Now, it will be a good idea to drop pages already stayed in cache:
sync; echo 3 > /proc/sys/vm/drop_caches
And finally assign a server to created control group:
cgclassify -g memory:DBLimitedGroup \`pidof mongod\`
This will assign a running mongod process to a group limited by only 16GB memory.
source: Using Cgroups to Limit MySQL and MongoDB memory usage
In addition to what was said by Howard
You have to keep in mind that Google encodes spaces as +
To avoid this, the ulr must be encoded in RFC 3986, which means spaces encoded at %20
, for example:
https://example.com/My Folder/image 1.jpg
tohttps://example.com/My%20Folder/image%201.jpg
If you want to use global variable i of file1.c in file2.c, then below are the points to remember:
I install with npm install --save-dev webpack-dev-server
then I set package.json and webpack.config.js like this:
setting.
Then I run webpack-dev-server and get this error error.
If I don't use npm install -g webpack-dev-server
to install, then how to fix it?
I fixed the error configuration has an unknown property 'colors'
by removing colors:true
. It worked!
Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover
(which will allow the image to extend out from the sides) or contain
(which does not allow the image to extend out at all), just set the CSS like so:
body {
background-image: url(img.jpg);
background-position: center top;
background-size: 100% auto;
}
This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.
EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.
Hopefully soon you'll be able to use the new srcset attribute on the img
element. If you want to use img
elements now, the currently accepted answer is probably best.
However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height
to 0 and set the padding-bottom
to a percentage of the element's own width, like so:
.foo {
height: 0;
padding: 0; /* remove any pre-existing padding, just in case */
padding-bottom: 75%; /* for a 4:3 aspect ratio */
background-image: url(foo.png);
background-position: center center;
background-size: 100%;
background-repeat: no-repeat;
}
In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.
If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:
# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
UPDATE: If you are still not scared then try to use the .NET reader:
$reader = [System.IO.File]::OpenText("my.log")
try {
for() {
$line = $reader.ReadLine()
if ($line -eq $null) { break }
# process the line
$line
}
}
finally {
$reader.Close()
}
UPDATE 2
There are comments about possibly better / shorter code. There is nothing wrong with the original code with for
and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is
$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
$line
}
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
Quoted from https://developer.mozilla.org/en/DOM/element.click
The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.
Non–Gecko DOMs may behave differently.
Unfortunately it sounds like you have already discovered the best solution to your problem.
As a side note, I agree that your solution seems less than ideal, but if you encapsulate the functionality inside a method (much like JQuery would do) it is not so bad.
Probably you need an array?
var Game = {
status: [
["val", "val","val"],
["val", "val", "val"]
]
}
alert(Game.status[0][0]);
This simulates a character array but you can substitute SUBSTR for ELT to simulate a string array
declare t_tipos varchar(255) default 'ABCDE';
declare t_actual char(1);
declare t_indice integer default 1;
while t_indice<length(t_tipos)+1 do
set t_actual=SUBSTR(t_tipos,t_indice,1);
select t_actual;
set t_indice=t_indice+1;
end while;
You can stablish specific toolbar for div
div::-webkit-scrollbar {
width: 12px;
}
div::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
}
see demo in jsfiddle.net
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
You can still continue to use the same View resolver but set the suffix to empty.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix="" />
Now your code can choose to return either index.html or index.jsp as shown in below sample -
@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
return "/test.jsp";
}
@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
return "/test.html";
}
You can do socket = undefined
in erase which socket you have connected. So when want to connected do socket(url)
So it will look like this
const socketClient = require('socket.io-client');
let socket;
// Connect to server
socket = socketClient(url)
// When want to disconnect
socket = undefined;
To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.
Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.
By Using underscore.js
var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
var resultArr = _.reject(arr,{id:3});
console.log(resultArr);
The result will be :: [{id:1name:'a'},{id:2,name:'c'}]
tl;dr
post-JDK8 : Use AssertJ or custom lambdas to assert exceptional behaviour.
pre-JDK8 : I will recommend the old good try
-catch
block. (Don't forget to add a fail()
assertion before the catch
block)
Regardless of Junit 4 or JUnit 5.
the long story
It is possible to write yourself a do it yourself try
-catch
block or use the JUnit tools (@Test(expected = ...)
or the @Rule ExpectedException
JUnit rule feature).
But these ways are not so elegant and don't mix well readability wise with other tools. Moreover, JUnit tooling does have some pitfalls.
The try
-catch
block you have to write the block around the tested behavior and write the assertion in the catch block, that may be fine but many find that this style interrupts the reading flow of a test. Also, you need to write an Assert.fail
at the end of the try
block. Otherwise, the test may miss one side of the assertions; PMD, findbugs or Sonar will spot such issues.
The @Test(expected = ...)
feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. But this approach is lacking in some areas.
Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that PMD, findbugs or Sonar will give hints on such code.
@Test(expected = WantedException.class)
public void call2_should_throw_a_WantedException__not_call1() {
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
The ExpectedException
rule is also an attempt to fix the previous caveats, but it feels a bit awkward to use as it uses an expectation style, EasyMock users know very well this style. It might be convenient for some, but if you follow Behaviour Driven Development (BDD) or Arrange Act Assert (AAA) principles the ExpectedException
rule won't fit in those writing style. Aside from that it may suffer from the same issue as the @Test
way, depending on where you place the expectation.
@Rule ExpectedException thrown = ExpectedException.none()
@Test
public void call2_should_throw_a_WantedException__not_call1() {
// expectations
thrown.expect(WantedException.class);
thrown.expectMessage("boom");
// init tested
tested.call1(); // may throw a WantedException
// call to be actually tested
tested.call2(); // the call that is supposed to raise an exception
}
Even the expected exception is placed before the test statement, it breaks your reading flow if the tests follow BDD or AAA.
Also, see this comment issue on JUnit of the author of ExpectedException
. JUnit 4.13-beta-2 even deprecates this mechanism:
Pull request #1519: Deprecate ExpectedException
The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition, the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case.
So these above options have all their load of caveats, and clearly not immune to coder errors.
There's a project I became aware of after creating this answer that looks promising, it's catch-exception.
As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. And you can use any assertion library like Hamcrest or AssertJ.
A rapid example taken from the home page :
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
when(myList).get(1);
// then: we expect an IndexOutOfBoundsException
then(caughtException())
.isInstanceOf(IndexOutOfBoundsException.class)
.hasMessage("Index: 1, Size: 0")
.hasNoCause();
As you can see the code is really straightforward, you catch the exception on a specific line, the then
API is an alias that will use AssertJ APIs (similar to using assertThat(ex).hasNoCause()...
). At some point the project relied on FEST-Assert the ancestor of AssertJ. EDIT: It seems the project is brewing a Java 8 Lambdas support.
Currently, this library has two shortcomings :
At the time of this writing, it is noteworthy to say this library is based on Mockito 1.x as it creates a mock of the tested object behind the scene. As Mockito is still not updated this library cannot work with final classes or final methods. And even if it was based on Mockito 2 in the current version, this would require to declare a global mock maker (inline-mock-maker
), something that may not what you want, as this mock maker has different drawbacks that the regular mock maker.
It requires yet another test dependency.
These issues won't apply once the library supports lambdas. However, the functionality will be duplicated by the AssertJ toolset.
Taking all into account if you don't want to use the catch-exception tool, I will recommend the old good way of the try
-catch
block, at least up to the JDK7. And for JDK 8 users you might prefer to use AssertJ as it offers may more than just asserting exceptions.
With the JDK8, lambdas enter the test scene, and they have proved to be an interesting way to assert exceptional behaviour. AssertJ has been updated to provide a nice fluent API to assert exceptional behaviour.
And a sample test with AssertJ :
@Test
public void test_exception_approach_1() {
...
assertThatExceptionOfType(IOException.class)
.isThrownBy(() -> someBadIOOperation())
.withMessage("boom!");
}
@Test
public void test_exception_approach_2() {
...
assertThatThrownBy(() -> someBadIOOperation())
.isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
@Test
public void test_exception_approach_3() {
...
// when
Throwable thrown = catchThrowable(() -> someBadIOOperation());
// then
assertThat(thrown).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
With a near-complete rewrite of JUnit 5, assertions have been improved a bit, they may prove interesting as an out of the box way to assert properly exception. But really the assertion API is still a bit poor, there's nothing outside assertThrows
.
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek());
Assertions.assertEquals("...", t.getMessage());
}
As you noticed assertEquals
is still returning void
, and as such doesn't allow chaining assertions like AssertJ.
Also if you remember name clash with Matcher
or Assert
, be prepared to meet the same clash with Assertions
.
I'd like to conclude that today (2017-03-03) AssertJ's ease of use, discoverable API, the rapid pace of development and as a de facto test dependency is the best solution with JDK8 regardless of the test framework (JUnit or not), prior JDKs should instead rely on try
-catch
blocks even if they feel clunky.
This answer has been copied from another question that don't have the same visibility, I am the same author.
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
Another option is to use the Apache Maven Shade Plugin: This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.
add this to your build plugins section
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.
http://www.ab-d.fr/date/2008-07-12/
It is in french, but the code is javascript :)
This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList
I have seen the same error message after upgrading to git1.8.5.2:
Simply make a search for all msys-1.0.dll
on your C:\
drive, and make the one used by Git comes first.
For instance, in my case I simply changed the order of:
C:\prgs\Gow\Gow-0.7.0\bin\msys-1.0.dll
C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\msys-1.0.dll
By making the Git path C:\prgs\git\PortableGit-1.8.5.2-preview20131230\bin\
come first in my %PATH%
, the error message disappeared.
No need to reboot or to even change the DOS session.
Once the %PATH%
is updated in that DOS session, the git commands just work.
Note that carmbrester and Sixto Saez both report below (in the comments) having to reboot in order to fix the issue.
Note: First, also removing any msys-1.0.dll
, like one in %LOCALAPPDATA%
You can use jquery for this by utilizing addClass() method
CSS
.defaultInput
{
width: 100px;
height:25px;
padding: 5px;
}
.error
{
border:1px solid red;
}
<input type="text" class="defaultInput"/>
Jquery Code
$(document).ready({
$('.defaultInput').focus(function(){
$(this).addClass('error');
});
});
Update: You can remove that error class using
$('.defaultInput').removeClass('error');
It won't remove that default style. It will remove .error class only
SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox
- as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.
So increasing the width
of the img
won't make the icons any taller if the height is restricted. You'll just end up with the img
horizontally centred in a wider box.
I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:
width
and height
defined, orwidth
and height
both set to "100%"
.That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.
Let's, just as example:
public class Test { public Test() { System.out.println("NO ARGS"); } public Test(String s) { this(); System.out.println("1 ARG"); } public static void main(String args[]) { Test t = new Test("s"); } }
It will print
>>> NO ARGS >>> 1 ARG
The correct way to call the constructor is by:
this();
You can as long as
Here you go:
var life={
users:{
guys:function(){ life.mameAndDestroy(life.users.girls); },
girls:function(){ life.kiss(life.users.guys); }
},
mameAndDestroy : function(group){
alert("mameAndDestroy");
group();
},
kiss : function(group){
alert("kiss");
//could call group() here, but would result in infinite loop
}
};
life.users.guys();
life.users.girls();
Also, make sure you don't have a comma after the "girls" definition. This will cause the script to crash in IE (any time you have a comma after the last item in an array in IE it dies).
I run my MySQL on a virtual machine in Ubuntu, So what had happened was when I restarted my host and the VM, The IP had changed. I had configured mysql to run on IP 192.168.0.5 and now due to dynamic allocation of IP, my new IP was 192.168.0.8
If you have the same problem just check your ip with the command ifconfig
.
Check your MySQL binding with the command cat /etc/mysql/my.cnf | grep bind-address
If both IP are the Same, then reinstall your mysql server
If not, then change your IP in /etc/network/interfaces
using nano, vi, vim or anything of your preference.
I prefer sudo nano /etc/network/interfaces
and enter the following
auto eth0
iface eth0 inet static
address 192.168.0.5
netmask 255.255.255.0
Save the interfaces file, restart your interface sudo ifdown eth0
&& sudo ifup eth0
replace "eth0" with your network interface
Restart MySQL sudo service mysql stop
followed by sudo service mysql start
If you have the same issue as mine, You are good to go!
I got this error when trying to create a new Eclipse project inside a newly cloned Git repo folder.
This worked for me:
1) clone the Git repo (in my case it was to a subfolder of the Eclipse default workspace)
2) create the new Eclipse project in the default workspace (one level above the cloned Git repo folder)
3) export the new Eclipse project from the default workspace to the cloned repo directory:
a) right click on project --> Export --> General --> File System
b) select the new Eclipse project
c) set the destination directory to export to (as the Git repo folder)
4) remove the Eclipse project form the workspace (because it's still the one that uses the default workspace)
right click on project and select "Delete"
5) open the exported Eclipse project from inside the Git repo directory
a) File --> Open Project from File System or Archive
b) set the "Import source" folder as the Git repo folder
c) check the project to import (that you just exported there)
I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.
new GenericAsyncTask(context,new AsyncTaskCompleteListener()
{
public void onTaskComplete(String response)
{
// do your work.
}
}).execute();
Interface
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result);
}
GenericAsyncTask
class GenericAsyncTask extends AsyncTask<String, Void, String>
{
private AsyncTaskCompleteListener<String> callback;
public A(Context context, AsyncTaskCompleteListener<String> cb) {
this.context = context;
this.callback = cb;
}
protected void onPostExecute(String result) {
finalResult = result;
callback.onTaskComplete(result);
}
}
Have a look at this , this question for more details.
boolean flag = true;
while(flag) {
s = s.replaceAll(" ", "");
if (!s.contains(" "))
flag = false;
}
return s;
You need to dynamically allocate your matrix. For instance:
int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));
This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.
You want DateTime.Today.AddDays(1)
.
how did you install easy_install/pip? make sure that you installed it for the upgraded version of python. what could have happened here is that the old (default) python install might be linked to your pip install. you might wanna try running the default version and importing the newly installed modules.
for the example in the second
Answer
I used this technique for the same URL
http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("q", params[0])
.appendQueryParameter("mode", "json")
.appendQueryParameter("units", "metric")
.appendQueryParameter("cnt", "7")
.appendQueryParameter("APPID", BuildConfig.OPEN_WEATHER_MAP_API_KEY);
then after finish building it get it as URL
like this
URL url = new URL(builder.build().toString());
and open a connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
and if link is simple
like location uri, for example
geo:0,0?q=29203
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon()
.appendQueryParameter("q",29203).build();
On Mac OS X using the python.org installer as you apparently have, you need to invoke Python 3 with python3
, not python
. That is currently reserved for Python 2 versions. You could also use python3.2
to specifically invoke that version.
$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ cd /Library/Frameworks/Python.framework/Versions/3.2/bin/
$ ls -l
total 384
lrwxr-xr-x 1 root admin 8 Apr 28 15:51 2to3@ -> 2to3-3.2
-rwxrwxr-x 1 root admin 140 Feb 20 11:14 2to3-3.2*
lrwxr-xr-x 1 root admin 7 Apr 28 15:51 idle3@ -> idle3.2
-rwxrwxr-x 1 root admin 138 Feb 20 11:14 idle3.2*
lrwxr-xr-x 1 root admin 8 Apr 28 15:51 pydoc3@ -> pydoc3.2
-rwxrwxr-x 1 root admin 123 Feb 20 11:14 pydoc3.2*
-rwxrwxr-x 2 root admin 25624 Feb 20 11:14 python3*
lrwxr-xr-x 1 root admin 12 Apr 28 15:51 python3-32@ -> python3.2-32
lrwxr-xr-x 1 root admin 16 Apr 28 15:51 python3-config@ -> python3.2-config
-rwxrwxr-x 2 root admin 25624 Feb 20 11:14 python3.2*
-rwxrwxr-x 1 root admin 13964 Feb 20 11:14 python3.2-32*
lrwxr-xr-x 1 root admin 17 Apr 28 15:51 python3.2-config@ -> python3.2m-config
-rwxrwxr-x 1 root admin 25784 Feb 20 11:14 python3.2m*
-rwxrwxr-x 1 root admin 1865 Feb 20 11:14 python3.2m-config*
lrwxr-xr-x 1 root admin 10 Apr 28 15:51 pythonw3@ -> pythonw3.2
lrwxr-xr-x 1 root admin 13 Apr 28 15:51 pythonw3-32@ -> pythonw3.2-32
-rwxrwxr-x 1 root admin 25624 Feb 20 11:14 pythonw3.2*
-rwxrwxr-x 1 root admin 13964 Feb 20 11:14 pythonw3.2-32*
If you also installed a Python 2 from python.org, it would have a similar framework bin directory with no overlapping file names (except for 2to3).
$ open /Applications/Python\ 2.7/Update\ Shell\ Profile.command
$ sh -l
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.2/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ cd /Library/Frameworks/Python.framework/Versions/2.7/bin
$ ls -l
total 288
-rwxrwxr-x 1 root admin 150 Jul 3 2010 2to3*
lrwxr-x--- 1 root admin 7 Nov 8 23:14 idle@ -> idle2.7
-rwxrwxr-x 1 root admin 138 Jul 3 2010 idle2.7*
lrwxr-x--- 1 root admin 8 Nov 8 23:14 pydoc@ -> pydoc2.7
-rwxrwxr-x 1 root admin 123 Jul 3 2010 pydoc2.7*
lrwxr-x--- 1 root admin 9 Nov 8 23:14 python@ -> python2.7
lrwxr-x--- 1 root admin 16 Nov 8 23:14 python-config@ -> python2.7-config
-rwxrwxr-x 1 root admin 33764 Jul 3 2010 python2.7*
-rwxrwxr-x 1 root admin 1663 Jul 3 2010 python2.7-config*
lrwxr-x--- 1 root admin 10 Nov 8 23:14 pythonw@ -> pythonw2.7
-rwxrwxr-x 1 root admin 33764 Jul 3 2010 pythonw2.7*
lrwxr-x--- 1 root admin 11 Nov 8 23:14 smtpd.py@ -> smtpd2.7.py
-rwxrwxr-x 1 root admin 18272 Jul 3 2010 smtpd2.7.py*
Try this...
function urlChange(url) {
var site = url+'?toolbar=0&navpanes=0&scrollbar=0';
document.getElementById('iFrameName').src = site;
}
<a href="javascript:void(0);" onClick="urlChange('www.mypdf.com/test.pdf')">TEST </a>
To make the code more clear that Kahia wrote in (it is clear but gets tricky when you want to add more text to it)...try this simple solution.
if (Math.Round((decimal)user.CurrentPoints) == user.CurrentPoints)
ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0}",user.CurrentPoints);
else
ViewBag.MyCurrentPoints = String.Format("Your current Points: {0:0.0}",user.CurrentPoints);
I had to add the extra cast (decimal) to have Math.Round compare the two decimal variables.
This will work with iPad on Safari on iOS 7.1.x from my testing, I'm not sure about iOS 6 though. However, it will not work on Firefox. There is a jQuery plugin which aims to be cross browser compliant called jScrollPane.
Also, there is a duplicate post here on Stack Overflow which has some other details.
Which WebControl are you using? Did you try?
DateTime.Now.ToString("yyyy-MM-dd");
You should use background instead of image.
.pdflink:after {
content: "";
background-image:url(your-image-url.png);
background-size: 100% 100%;
display: inline-block;
/*size of your image*/
height: 25px;
width:25px;
/*if you want to change the position you can use margins or:*/
position:relative;
top:5px;
}
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
$("#goal-input").focus();
});
</script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast', function() {
$("#name").focus();
});
});
}
This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.'
and the slash '/'
.
Instead of writing:
D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"
Write:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
switch ($value)
{
case 1:
case 2:
echo 'the value is either 1 or 2';
break;
}
Make sure you are not naming your source file random.py, and that there is not a file in your working directory called random.pyc.. either could cause your program to try and import your local random.py file instead of pythons random module.
For everyone using Eclipse, this is how you should do it.
Eclipse -> import -> existing android code -> browse -> navigate to google-play-services_lib FOLDER (android-sdk/extras/google/google_play_services/libproject).
Then, on your project
control click -> properties -> android -> libraries, add -> select the project you just imported -> ok
It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).
Native methods were used in the past to write performance critical sections but with Java getting faster this is now less common. Native methods are currently needed when
You need to call a library from Java that is written in other language.
You need to access system or hardware resources that are only reachable from the other language (typically C). Actually, many system functions that interact with real computer (disk and network IO, for instance) can only do this because they call native code.
See Also Java Native Interface Specification
Swift 3 syntax:
tableView.tableFooterView = UIView(frame: .zero)
Swift syntax: < 2.0
tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
Swift 2.0 syntax:
tableView.tableFooterView = UIView(frame: CGRect.zero)
The mainly problem are corrupted jars.
To find the corrupted one, you need to add a Java Exception Breakpoint in the Breakpoints View of Eclipse, or your preferred IDE, select the java.util.zip.ZipException
class, and restart Tomcat instance.
When the JVM suspends at ZipException
breakpoint you must go to
JarFile.getManifestFromReference()
in the stack trace, and check attribute name
to see the filename.
After that, you should delete the file from file system and then right click your project, select Maven, Update Project, check on Force Update of Snapshots/Releases.
Set IFS to newline, like this:
IFS='
'
for x in `ls -l $1`; do echo $x; done
Put a sub-shell around it if you don't want to set IFS permanently:
(IFS='
'
for x in `ls -l $1`; do echo $x; done)
Or use while | read instead:
ls -l $1 | while read x; do echo $x; done
One more option, which runs the while/read at the same shell level:
while read x; do echo $x; done << EOF
$(ls -l $1)
EOF
As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.
Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.
Typically, this is how I handle this case:
val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics
val df = spark.read.table("some_table").
.select(columnOfInterests.map(c => col(c)):_*)
.groupBy(dimensions.map(d => col(d)): _*)
.agg(metrics.map( m => m -> "sum").toMap)
.toDF(columnOfInterests:_*) // that's the interesting part
The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2)
and sum(col3)
to simply col2
and col3
.
Always use mongoose.Types.ObjectId('your id')
for conditions in your query it will validate the id field before running your query as a result your app will not crash.
select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable
where "ImagePath" is my column Name.
"NewImagePath" is temporery column Name insted of "ImagePath"
"~/" is my current string.(old string)
"../" is my requried string.(new string)
"tblMyTable" is my table in database.
There is a little known feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins - which are like interfaces with an associated implenentation).
More information on TypeScript Mixins
I think you could use this technique to share common components between many classes in your game and to re-use many of these components from a single class in your game:
Here is a quick Mixins demo... first, the flavours that you want to mix:
class CanEat {
public eat() {
alert('Munch Munch.');
}
}
class CanSleep {
sleep() {
alert('Zzzzzzz.');
}
}
Then the magic method for Mixin creation (you only need this once somewhere in your program...)
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
And then you can create classes with multiple inheritance from mixin flavours:
class Being implements CanEat, CanSleep {
eat: () => void;
sleep: () => void;
}
applyMixins (Being, [CanEat, CanSleep]);
Note that there is no actual implementation in this class - just enough to make it pass the requirements of the "interfaces". But when we use this class - it all works.
var being = new Being();
// Zzzzzzz...
being.sleep();
You can build a wrapper function like this:
function get_something(name in varchar2,
ignore_notfound in varchar2) return varchar2
is
begin
return get_something (name, (upper(ignore_notfound) = 'TRUE') );
end;
then call:
select get_something('NAME', 'TRUE') from dual;
It's up to you what the valid values of ignore_notfound are in your version, I have assumed 'TRUE' means TRUE and anything else means FALSE.
It works:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
No there isn't. You can specify a background image but that's not the same thing.
For thoose who want to use a better maintainable solution than disruptive lightyear-long RegEx matches, I wrote up a few lines of code. Thoose who want to save bytes, stick to the RegEx variant :)
This restricts:
Anyways, it's still possible to leak through, so be sure you combine this with a server-side validation + email-link verification.
Here's the JSFiddle
//validate email
var emailInput = $("#email").val(),
emailParts = emailInput.split('@'),
text = 'Enter a valid e-mail address!';
//at least one @, catches error
if (emailParts[1] == null || emailParts[1] == "" || emailParts[1] == undefined) {
yourErrorFunc(text);
} else {
//split domain, subdomain and tld if existent
var emailDomainParts = emailParts[1].split('.');
//at least one . (dot), catches error
if (emailDomainParts[1] == null || emailDomainParts[1] == "" || emailDomainParts[1] == undefined) {
yourErrorFunc(text);
} else {
//more than 2 . (dots) in emailParts[1]
if (!emailDomainParts[3] == null || !emailDomainParts[3] == "" || !emailDomainParts[3] == undefined) {
yourErrorFunc(text);
} else {
//email user
if (/[^a-z0-9!#$%&'*+-/=?^_`{|}~]/i.test(emailParts[0])) {
yourErrorFunc(text);
} else {
//double @
if (!emailParts[2] == null || !emailParts[2] == "" || !emailParts[2] == undefined) {
yourErrorFunc(text);
} else {
//domain
if (/[^a-z0-9-]/i.test(emailDomainParts[0])) {
yourErrorFunc(text);
} else {
//check for subdomain
if (emailDomainParts[2] == null || emailDomainParts[2] == "" || emailDomainParts[2] == undefined) {
//TLD
if (/[^a-z]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}
} else {
//subdomain
if (/[^a-z0-9-]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
//TLD
if (/[^a-z]/i.test(emailDomainParts[2])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}}}}}}}}}
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){
declare("MyWidget", [_WidgetBase], {
field1: [],
field2: "",
function1: function(),
function2: function()
});
});
I found that when the fields are initialised with []
then it would be shared by all Model objects. Making changes to one affects all others.
This doesn't happen initialising them with new Array()
. Same for the initialisation of Objects ({}
vs new Object()
)
TBH I am not sure if its a problem with the framework we were using (Dojo)
curl 'http://$artiserver/artifactory/api/storage/$repokey/$path/$version/?lastModified'
The above command responds with a JSON with two elements - "uri" and "lastModified"
Fetching the link in the uri returns another JSON which has the "downloadUri" of the artifact.
Fetch the link in the "downloadUri" and you have the latest artefact.
(Requires Pro) to resolve and download latest artifact, if Jenkins Artifactory plugin was used to publish to artifactory in another job:
${repokey}:**/${component}*.jar;status=${STATUS}@${PUBLISH_BUILDJOB}#LATEST=>${targetDir}
You can also simulate the radiobutton behavior using only checkboxes:
<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />
Then, you can use this simple code to work for you:
$(".fakeRadio").click(function(){
$(".fakeRadio").prop( "checked", false );
$(this).prop( "checked", true );
});
It works fine and you have more control over the behavior of each button.
You can try it by yourself at: http://jsfiddle.net/almircampos/n1zvrs0c/
This fork also let's you unselect all as requested in a comment: http://jsfiddle.net/5ry8n4f4/
To figure out the modular multiplicative inverse I recommend using the Extended Euclidean Algorithm like this:
def multiplicative_inverse(a, b):
origA = a
X = 0
prevX = 1
Y = 1
prevY = 0
while b != 0:
temp = b
quotient = a/b
b = a%b
a = temp
temp = X
a = prevX - quotient * X
prevX = temp
temp = Y
Y = prevY - quotient * Y
prevY = temp
return origA + prevY
That's a bad practice to use the ==
equality operator instead of ===
.
undefined === undefined // true
null == undefined // true
null === undefined // false
The object.x === undefined
should return true
if x
is unknown property.
In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:
If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.
In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like
value = myObject[name]; if (value == null) { alert(name + ' not found.'); }
It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:
value = myObject[name]; if (value === undefined) { alert(name + ' not found.'); }
=TEXT(A1,"DD/MM/YYYY hh:mm:ss")
(24 hour time)
=TEXT(A1,"DD/MM/YYYY hh:mm:ss AM/PM")
(standard time)
rio()
would be very suitable for this - it uses the file extension of a file name to determine what kind of file it is, so it will work with a large variety of file types. I've also used unzip()
to list the file names within the zip file, so its not necessary to specify the file name(s) manually.
library(rio)
# create a temporary directory
td <- tempdir()
# create a temporary file
tf <- tempfile(tmpdir=td, fileext=".zip")
# download file from internet into temporary location
download.file("http://download.companieshouse.gov.uk/BasicCompanyData-part1.zip", tf)
# list zip archive
file_names <- unzip(tf, list=TRUE)
# extract files from zip file
unzip(tf, exdir=td, overwrite=TRUE)
# use when zip file has only one file
data <- import(file.path(td, file_names$Name[1]))
# use when zip file has multiple files
data_multiple <- lapply(file_names$Name, function(x) import(file.path(td, x)))
# delete the files and directories
unlink(td)
Give the form
an id
, and then:
document.getElementById("yourFormId").submit();
Best practice would probably be to give your link an id
too, and get rid of the event handler:
document.getElementById("yourLinkId").onclick = function() {
document.getElementById("yourFormId").submit();
}
The most convenient way according to me is:
(Val in X[:, col_num])
where Val is the value that you want to check for and X is the array. In your example, suppose you want to check if the value 8 exists in your the third column. Simply write
(8 in X[:, 2])
This will return True if 8 is there in the third column, else False.