I don't think the order can be guaranteed, otherwise it would be easy enough to slice the second half of Object.entries
result and map from there.
The only (very minor) issues with the answers above is that
type StandardEnum = { [id: string]: number | string; [nu: number]: string;}
function enumToList<T extends StandardEnum> (enm: T) : { id: number; description: string }[] {
return Object.entries(enm).reduce((accum, kv) => {
if (typeof kv[1] === 'number') {
accum.push({ id: kv[1], description: kv[0] })
}
return accum
}, []) // if enum is huge, perhaps pre-allocate with new Array(entries.length / 2), however then push won't work, so tracking an index would also be required
}
The http.delete(url, options)
does accept a body. You just need to put it within the options object.
http.delete('/api/something', new RequestOptions({
headers: headers,
body: anyObject
}))
Reference options interface:
https://angular.io/api/http/RequestOptions
UPDATE:
The above snippet only works for Angular 2.x, 4.x and 5.x.
For versions 6.x onwards, Angular offers 15 different overloads. Check all overloads here: https://angular.io/api/common/http/HttpClient#delete
Usage sample:
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: {
id: 1,
name: 'test',
},
};
this.httpClient
.delete('http://localhost:8080/something', options)
.subscribe((s) => {
console.log(s);
});
You should use hasOwnProperty
. For example:
myObj.hasOwnProperty('myKey');
Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:
Object.prototype.hasOwnProperty.call(myObj, 'myKey');
The way I know how to convert an integer into a string is by using the following code:
Integer.toString(int);
and
String.valueOf(int);
If you had an integer i, and a string s, then the following would apply:
int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);
If you wanted to convert a string "s" into an integer "i", then the following would work:
i = Integer.valueOf(s).intValue();
Just put two inputs inside a div with class form-group
and set display flex on the div style
<form method="post">
<div class="form-group" style="display: flex;"><input type="text" class="form-control" name="nome" placeholder="Nome e sobrenome" style="margin-right: 4px;" /><input type="text" class="form-control" style="margin-left: 4px;" name="cpf" placeholder="CPF" /></div>
<div class="form-group" style="display: flex;"><input type="email" class="form-control" name="email" placeholder="Email" style="margin-right: 4px;" /><input type="tel" class="form-control" style="margin-left: 4px;" name="telephone" placeholder="Telefone" /></div>
<div class="form-group"><input type="password" class="form-control" name="password" placeholder="Password" /></div>
<div class="form-group"><input type="password" class="form-control" name="password-repeat" placeholder="Password (repeat)" /></div>
<div class="form-group">
<div class="form-check"><label class="form-check-label"><input type="checkbox" class="form-check-input" />I agree to the license terms.</label></div>
</div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></div><a class="already" href="#">You already have an account? Login here.</a></form>
Using base graphics, we can use at =
to control box position , combined with boxwex =
for the width of the boxes. The 1st boxplot
statement creates a blank plot. Then add the 2 traces in the following two statements.
Note that in the following, we use df[,-1]
to exclude the 1st (id) column from the values to plot. With different data frames, it may be necessary to change this to subset for whichever columns contain the data you want to plot.
boxplot(df[,-1], boxfill = NA, border = NA) #invisible boxes - only axes and plot area
boxplot(df[df$id=="Good", -1], xaxt = "n", add = TRUE, boxfill="red",
boxwex=0.25, at = 1:ncol(df[,-1]) - 0.15) #shift these left by -0.15
boxplot(df[df$id=="Bad", -1], xaxt = "n", add = TRUE, boxfill="blue",
boxwex=0.25, at = 1:ncol(df[,-1]) + 0.15) #shift to the right by +0.15
Some dummy data:
df <- data.frame(
id = c(rep("Good",200), rep("Bad", 200)),
F1 = c(rnorm(200,10,2), rnorm(200,8,1)),
F2 = c(rnorm(200,7,1), rnorm(200,6,1)),
F3 = c(rnorm(200,6,2), rnorm(200,9,3)),
F4 = c(rnorm(200,12,3), rnorm(200,8,2)))
As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &
. That also requires using parentheses so that &
wouldn't take precedence.
It would go something like this:
mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
In order to avoid that, you can build series for lower and upper limits:
low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
Now you can slice it as follows:
mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
And for assignment you can use np.where:
df['class'] = np.where(mask, 'excellent', 'critical')
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
Properties are used to expose field. They use accessors(set, get) through which the values of the private fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.
Using properties we can set validation on the type of data that is set on a field.
For example we have private integer field age on that we should allow positive values since age cannot be negative.
We can do this in two ways using getter and setters and using property.
Using Getter and Setter
// field
private int _age;
// setter
public void set(int age){
if (age <=0)
throw new Exception();
this._age = age;
}
// getter
public int get (){
return this._age;
}
Now using property we can do the same thing. In the value is a key word
private int _age;
public int Age{
get{
return this._age;
}
set{
if (value <= 0)
throw new Exception()
}
}
Auto Implemented property if we don't logic in get and set accessors we can use auto implemented property.
When use auto-implemented property compiles creates a private, anonymous field that can only be accessed through get and set accessors.
public int Age{get;set;}
Abstract Properties An abstract class may have an abstract property, which should be implemented in the derived class
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
// overriden something like this
// Declare a Name property of type string:
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
We can privately set a property In this we can privately set the auto property(set with in the class)
public int MyProperty
{
get; private set;
}
You can achieve same with this code. In this property set feature is not available as we have to set value to field directly.
private int myProperty;
public int MyProperty
{
get { return myProperty; }
}
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
I share my solution (assuming everything is already configured to connect to google bucket in flask)
from google.cloud import storage
@app.route('/upload/', methods=['POST'])
def upload():
if request.method == 'POST':
# FileStorage object wrapper
file = request.files["file"]
if file:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = app.config['GOOGLE_APPLICATION_CREDENTIALS']
bucket_name = "bucket_name"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Upload file to Google Bucket
blob = bucket.blob(file.filename)
blob.upload_from_string(file.read())
My post
Instead of using pull-right
class, it is better to use text-right
class in the column, because pull-right
creates problems sometimes while resizing the page.
This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype
It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"
or
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"
Ref :Youtube Video Download (Android/Java)
Edit 3
You can use the Lib : https://github.com/HaarigerHarald/android-youtubeExtractor
Ex :
String youtubeLink = "http://youtube.com/watch?v=xxxx";
new YouTubeExtractor(this) {
@Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
if (ytFiles != null) {
int itag = 22;
String downloadUrl = ytFiles.get(itag).getUrl();
}
}
}.extract(youtubeLink, true, true);
They decipherSignature using :
private boolean decipherSignature(final SparseArray<String> encSignatures) throws IOException {
// Assume the functions don't change that much
if (decipherFunctionName == null || decipherFunctions == null) {
String decipherFunctUrl = "https://s.ytimg.com/yts/jsbin/" + decipherJsFileName;
BufferedReader reader = null;
String javascriptFile;
URL url = new URL(decipherFunctUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
try {
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(" ");
}
javascriptFile = sb.toString();
} finally {
if (reader != null)
reader.close();
urlConnection.disconnect();
}
if (LOGGING)
Log.d(LOG_TAG, "Decipher FunctURL: " + decipherFunctUrl);
Matcher mat = patSignatureDecFunction.matcher(javascriptFile);
if (mat.find()) {
decipherFunctionName = mat.group(1);
if (LOGGING)
Log.d(LOG_TAG, "Decipher Functname: " + decipherFunctionName);
Pattern patMainVariable = Pattern.compile("(var |\\s|,|;)" + decipherFunctionName.replace("$", "\\$") +
"(=function\\((.{1,3})\\)\\{)");
String mainDecipherFunct;
mat = patMainVariable.matcher(javascriptFile);
if (mat.find()) {
mainDecipherFunct = "var " + decipherFunctionName + mat.group(2);
} else {
Pattern patMainFunction = Pattern.compile("function " + decipherFunctionName.replace("$", "\\$") +
"(\\((.{1,3})\\)\\{)");
mat = patMainFunction.matcher(javascriptFile);
if (!mat.find())
return false;
mainDecipherFunct = "function " + decipherFunctionName + mat.group(2);
}
int startIndex = mat.end();
for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0 && startIndex + 5 < i) {
mainDecipherFunct += javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
decipherFunctions = mainDecipherFunct;
// Search the main function for extra functions and variables
// needed for deciphering
// Search for variables
mat = patVariableFunction.matcher(mainDecipherFunct);
while (mat.find()) {
String variableDef = "var " + mat.group(2) + "={";
if (decipherFunctions.contains(variableDef)) {
continue;
}
startIndex = javascriptFile.indexOf(variableDef) + variableDef.length();
for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0) {
decipherFunctions += variableDef + javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
}
// Search for functions
mat = patFunction.matcher(mainDecipherFunct);
while (mat.find()) {
String functionDef = "function " + mat.group(2) + "(";
if (decipherFunctions.contains(functionDef)) {
continue;
}
startIndex = javascriptFile.indexOf(functionDef) + functionDef.length();
for (int braces = 0, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0 && startIndex + 5 < i) {
decipherFunctions += functionDef + javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
}
if (LOGGING)
Log.d(LOG_TAG, "Decipher Function: " + decipherFunctions);
decipherViaWebView(encSignatures);
if (CACHING) {
writeDeciperFunctToChache();
}
} else {
return false;
}
} else {
decipherViaWebView(encSignatures);
}
return true;
}
Now with use of this library High Quality Videos Lossing Audio so i use the MediaMuxer for Murging Audio
and Video for Final Output
Edit 1
https://stackoverflow.com/a/15240012/9909365
Why the previous answer not worked
Pattern p2 = Pattern.compile("sig=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
}
As of November 2016, this is a little rough around the edges, but displays the basic principle. The url_encoded_fmt_stream_map today does not have a space after the colon (better make this optional) and "
sig
" has been changed to "signature
"and while i am debuging the code i found the new keyword its
signature&s
in many video's URL
here edited answer
private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();
initTypeMap(); call first
class Meta {
public String num;
public String type;
public String ext;
Meta(String num, String ext, String type) {
this.num = num;
this.ext = ext;
this.type = type;
}
}
class Video {
public String ext = "";
public String type = "";
public String url = "";
Video(String ext, String type, String url) {
this.ext = ext;
this.type = type;
this.url = url;
}
}
public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
throws IOException {
if (ytUrl == null) {
return null;
}
// Remove any query params in query string after the watch?v=<vid> in
// e.g.
// http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
int andIdx = ytUrl.indexOf('&');
if (andIdx >= 0) {
ytUrl = ytUrl.substring(0, andIdx);
}
// Get the HTML response
/* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
/* HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
userAgent);
HttpGet request = new HttpGet(ytUrl);
HttpResponse response = client.execute(request);*/
String html = "";
HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line.replace("\\u0026", "&"));
}
in.close();
html = str.toString();
// Parse the HTML response and extract the streaming URIs
if (html.contains("verify-age-thumb")) {
Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
return null;
}
if (html.contains("das_captcha")) {
Log.e("Downloader", "Captcha found, please try with different IP address.");
return null;
}
Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
// Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
Matcher m = p.matcher(html);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
if (matches.size() != 1) {
Log.e("Downloader", "Found zero or too many stream maps.");
return null;
}
String urls[] = matches.get(0).split(",");
HashMap<String, String> foundArray = new HashMap<String, String>();
for (String ppUrl : urls) {
String url = URLDecoder.decode(ppUrl, "UTF-8");
Log.e("URL","URL : "+url);
Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
Matcher m1 = p1.matcher(url);
String itag = null;
if (m1.find()) {
itag = m1.group(1);
}
Pattern p2 = Pattern.compile("signature=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
} else {
Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
Matcher m23 = p23.matcher(url);
if (m23.find()) {
sig = m23.group(1);
}
}
Pattern p3 = Pattern.compile("url=(.*?)[&]");
Matcher m3 = p3.matcher(ppUrl);
String um = null;
if (m3.find()) {
um = m3.group(1);
}
if (itag != null && sig != null && um != null) {
Log.e("foundArray","Adding Value");
foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
+ "signature=" + sig);
}
}
Log.e("foundArray","Size : "+foundArray.size());
if (foundArray.size() == 0) {
Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
return null;
}
ArrayList<Video> videos = new ArrayList<Video>();
for (String format : typeMap.keySet()) {
Meta meta = typeMap.get(format);
if (foundArray.containsKey(format)) {
Video newVideo = new Video(meta.ext, meta.type,
foundArray.get(format));
videos.add(newVideo);
Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
+ ", type:" + newVideo.type + ", url:" + newVideo.url);
}
}
return videos;
}
private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(webViewActivity.this, "",
"Connecting to YouTube...", true);
}
@Override
protected ArrayList<Video> doInBackground(String... params) {
ArrayList<Video> fVideos = new ArrayList<>();
String url = params[0];
try {
ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
/* Log.e("Downloader","Size of Video : "+videos.size());*/
if (videos != null && !videos.isEmpty()) {
for (Video video : videos)
{
Log.e("Downloader", "ext : " + video.ext);
if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
ext = video.ext.toLowerCase();
fVideos.add(new Video(video.ext,video.type,video.url));
}
}
return fVideos;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
}
Log.e("Downloader", "Couldn't get stream URI for " + url);
return null;
}
@Override
protected void onPostExecute(ArrayList<Video> streamingUrl) {
super.onPostExecute(streamingUrl);
progressDialog.dismiss();
if (streamingUrl != null) {
if (!streamingUrl.isEmpty()) {
//Log.e("Steaming Url", "Value : " + streamingUrl);
for (int i = 0; i < streamingUrl.size(); i++) {
Video fX = streamingUrl.get(i);
Log.e("Founded Video", "URL : " + fX.url);
Log.e("Founded Video", "TYPE : " + fX.type);
Log.e("Founded Video", "EXT : " + fX.ext);
}
//new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
}
}
}
}
public void initTypeMap()
{
typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}
Edit 2:
Some time This Code Not worked proper
Same-origin policy
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1].
url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts // DASH: contains video or audio stream
Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this
url // direct HTTP link to a video
itag // code specifying the quality
s // signature, security measure to counter downloading
Each URL will be encoded so you will need to decode them. Now the tricky part.
YouTube has at least 3 security levels for their videos
unsecured // as expected, you can download these with just the unencoded URL
s // see below
RTMPE // uses "rtmpe://" protocol, no known method for these
The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.
The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as
AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this
function mo(a) {
a = a.split("");
a = lo.rw(a, 1);
a = lo.rw(a, 32);
a = lo.IC(a, 1);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 44);
return a.join("")
}
This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as
http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js
this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header
Access-Control-Allow-Origin: http://www.youtube.com
and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests
Access-Control-Allow-Origin: *
So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.
There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:
from matplotlib.colors import Normalize
class InvertedNormalize(Normalize):
def __call__(self, *args, **kwargs):
return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)
You can then use this with plot_surface
and other Matplotlib plotting functions by doing e.g.
inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)
This will work with any Matplotlib colormap.
A simple way to do this is
compile fileTree(include: ['*.jar'], dir: 'libs')
it will compile all the .jar files in your libs directory in App.
Enabling delayed variable expansion solves you problem, the script produces "hi":
setlocal EnableDelayedExpansion
set var1=A
set var2=B
set AB=hi
set newvar=!%var1%%var2%!
echo %newvar%
You can achieve the same with the below CSS properties:
writing-mode: vertical-rl;
text-orientation: upright;
Easier alternative to above answers
If Object(Model Class/POJO) contains the date in String datatype.
private void sortArray(ArrayList<myObject> arraylist) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
if (reports != null) {
Collections.sort(arraylist, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
try {
return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
}
If Object(Model Class/POJO) contains date in Date datatype
private void sortArray(ArrayList<myObject> arrayList) {
if (arrayList != null) {
Collections.sort(arrayList, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
return o2.getCreated_at().compareTo(o1.getCreated_at()); }
});
} }
The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.
Java is not call by reference it is call by value only
But all variables of object type are actually pointers.
So if you use a Mutable Object you will see the behavior you want
public class XYZ {
public static void main(String[] arg) {
StringBuilder toyNumber = new StringBuilder("5");
play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
private static void play(StringBuilder toyNumber) {
System.out.println("Toy number in play " + toyNumber);
toyNumber.append(" + 1");
System.out.println("Toy number in play after increement " + toyNumber);
}
}
Output of this code:
run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)
You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.
List<Integer> mutableList = new ArrayList<Integer>();
mutableList.add(1);
mutableList.add(2);
mutableList.add(3);
mutableList.add(4);
mutableList.add(5);
System.out.println(mutableList);
Collections.shuffle(mutableList);
System.out.println(mutableList);
Collections.sort(mutableList);
System.out.println(mutableList);
Output of this code:
run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
For general updating table1 specific colom based on Table2 specific colom, below query works perfectly...
UPDATE table 1
SET Col 2 = t2.Col2,
Col 3 = t2.Col3
FROM table1 t1
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1
If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
For update SQLs:
update Table1 set Col1 = Col2 / ISNULL(NULLIF(Col3,0),1)
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');
Your code has two problems:
.IsBestAnswe
does not match what you thoughtaddClass()
, not addclass()
.Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer')
part to add only:
$('.IsBestAnswer').addClass('bestanswer');
You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer
vs. bestanswer
).
You can use the code below:
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'databox') {
alert(this)
}
}, false);
Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml
contains the necessary slf4j dependencies, e.g.:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
For completion I thought I'd add that this issue is solved in Eclipse 4.6 Neon https://www.eclipse.org/downloads/index-developer.php (the current developer version). The icons look a bit sad (low resolution) but at least they are scaled correctly on my 4k screen.
you can do it by following way too ..
create table #test (a int, b char(1))
select * From #test
exec tempdb..sp_columns '#test'
Type in command line :
$ export http_proxy=http://proxy_host:proxy_port
for authenticated proxy,
$ export http_proxy=http://username:password@proxy_host:proxy_port
and then run
$ wget fileurl
for https, just use https_proxy instead of http_proxy. You could also put these lines in your ~/.bashrc file so that you don't need to execute this everytime.
C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap
This best for XML Deserialize
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
return xSerializer.Deserialize(str);
}
}
jQuery.now()
Returns: Number
Description: Return a number representing the current time.
This method does not accept any arguments.
The $.now()
method is a shorthand for the number returned by the expression (new Date).getTime()
.
http://api.jquery.com/jQuery.now/
It's simple to use Javascript:
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(time);
This is working on Flowplayer 6.0.2.
<script>
flowplayer().load({
sources: [
{ type: "video/mp4", src: variable }
]
});
</script>
where variable is a javascript/jquery variable value, The video tag should be something this
<div class="flowplayer">
<video>
<source type="video/mp4" src="" class="videomp4">
</video>
</div>
Hope it helps anyone.
Maybe this trick gives u an idea
Boolean var= new anonymousClass(){
private String myVar; //String for example
@Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
It can also be done as follows:
csv_files = s3.list_objects_v2(s3_bucket_path)
for obj in csv_files['Contents']:
key = obj['Key']
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
There is another library called arrow
really great to make manipulation on python date.
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.
If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).
You could use a lookahead:
re.split(r'[ ](?=[A-Z]+\b)', input)
This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.
Note that the square brackets are only for readability and could as well be omitted.
If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello
as well) it gets even easier:
re.split(r'[ ](?=[A-Z])', input)
Now this splits at every space followed by any upper-case letter.
It can also be due to a duplicate entry in any of the tables that are used.
Open Run in your system.
Type %windir%\System32\cliconfg.exe
Click on ok button then check that the "TCP/IP Network Protocol Default Value Setup" pop-up is open.
Highlight TCP/IP under the Enabled protocols window.
Click the Properties button.
Enter the new port number, then click OK.
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
I just had to play with the divo's ConsoleSpinner
class. Mine is nowhere near as concise, but it just didn't sit well with me that users of that class have to write their own while(true)
loop. I'm shooting for an experience more like this:
static void Main(string[] args)
{
Console.Write("Working....");
ConsoleSpinner spin = new ConsoleSpinner();
spin.Start();
// Do some work...
spin.Stop();
}
And I realized it with the code below. Since I don't want my Start()
method to block, I don't want the user to have to worry about writing a while(spinFlag)
-like loop, and I want to allow multiple spinners at the same time I had to spawn a separate thread to handle the spinning. And that means the code has to be a lot more complicated.
Also, I haven't done that much multi-threading so it's possible (likely even) that I've left a subtle bug or three in there. But it seems to work pretty well so far:
public class ConsoleSpinner : IDisposable
{
public ConsoleSpinner()
{
CursorLeft = Console.CursorLeft;
CursorTop = Console.CursorTop;
}
public ConsoleSpinner(bool start)
: this()
{
if (start) Start();
}
public void Start()
{
// prevent two conflicting Start() calls ot the same instance
lock (instanceLocker)
{
if (!running )
{
running = true;
turner = new Thread(Turn);
turner.Start();
}
}
}
public void StartHere()
{
SetPosition();
Start();
}
public void Stop()
{
lock (instanceLocker)
{
if (!running) return;
running = false;
if (! turner.Join(250))
turner.Abort();
}
}
public void SetPosition()
{
SetPosition(Console.CursorLeft, Console.CursorTop);
}
public void SetPosition(int left, int top)
{
bool wasRunning;
//prevent other start/stops during move
lock (instanceLocker)
{
wasRunning = running;
Stop();
CursorLeft = left;
CursorTop = top;
if (wasRunning) Start();
}
}
public bool IsSpinning { get { return running;} }
/* --- PRIVATE --- */
private int counter=-1;
private Thread turner;
private bool running = false;
private int rate = 100;
private int CursorLeft;
private int CursorTop;
private Object instanceLocker = new Object();
private static Object console = new Object();
private void Turn()
{
while (running)
{
counter++;
// prevent two instances from overlapping cursor position updates
// weird things can still happen if the main ui thread moves the cursor during an update and context switch
lock (console)
{
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
switch (counter)
{
case 0: Console.Write("/"); break;
case 1: Console.Write("-"); break;
case 2: Console.Write("\\"); break;
case 3: Console.Write("|"); counter = -1; break;
}
Console.SetCursorPosition(OldLeft, OldTop);
}
Thread.Sleep(rate);
}
lock (console)
{ // clean up
int OldLeft = Console.CursorLeft;
int OldTop = Console.CursorTop;
Console.SetCursorPosition(CursorLeft, CursorTop);
Console.Write(' ');
Console.SetCursorPosition(OldLeft, OldTop);
}
}
public void Dispose()
{
Stop();
}
}
You can use Tikz/pgfplots for creating animations in beamer. http://www.texample.net/tikz/examples/tag/animations/
This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.
Keep in mind that if you want to keep the white spaces within a string, you may remove them unintentionally using some approaches. If you have this list
['hello world', ' ', '', 'hello'] what you may want ['hello world','hello']
first trim the list to convert any type of white space to empty string:
space_to_empty = [x.strip() for x in _text_list]
then remove empty string from them list
space_clean_list = [x for x in space_to_empty if x]
I would go a step further than just saying "use a docstring". Pick a documentation generation tool, such as pydoc or epydoc (I use epydoc in pyparsing), and use the markup syntax recognized by that tool. Run that tool often while you are doing your development, to identify holes in your documentation. In fact, you might even benefit from writing the docstrings for the members of a class before implementing the class.
Try this, it worked for me.
<button id="btn">Click</button>
<script>
console.log(btn)
let f;
btn.addEventListener('click', f=function(event) {
console.log('Click')
console.log(f)
this.removeEventListener('click',f)
console.log('Event removed')
})
</script>
basename
does remove the directory prefix of a path:
$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example
As I found the default Bootstrap <hr/>
size unsightly, here's some simple HTML and CSS to balance out the element visually:
HTML:
<hr class="half-rule"/>
CSS:
.half-rule {
margin-left: 0;
text-align: left;
width: 50%;
}
To comapre dates of string format (mm-dd-yyyy).
var job_start_date = "10-1-2014"; // Oct 1, 2014
var job_end_date = "11-1-2014"; // Nov 1, 2014
job_start_date = job_start_date.split('-');
job_end_date = job_end_date.split('-');
var new_start_date = new Date(job_start_date[2],job_start_date[0],job_start_date[1]);
var new_end_date = new Date(job_end_date[2],job_end_date[0],job_end_date[1]);
if(new_end_date <= new_start_date) {
// your code
}
Visual Studio Community is same (almost) as professional edition. What differs is that VS community do not have TFS features, and the licensing is different. As stated by @Stefan.
The different versions on VS are compared here - https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs
In case you want to store it to a file, you solve it using bbox_inches="tight"
argument:
plt.savefig('myfile.png', bbox_inches = "tight")
I know this question has been answered, but in case you only want something to trigger when the actual BROWSER is closed, and not just when a pageload occurs, you can use this code:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
In my example, I am clearing local storage and alerting the user with the mouses y coords, only when the browser is closed, this will be ignored on all page loads from within the program.
Type in the command:
netstat -aon | findstr :80
It will show you all processes that use port 80. Notice the pid (process id) in the right column.
If you would like to free the port, go to Task Manager, sort by pid and close those processes.
-a displays all connections and listening ports.
-o displays the owning process ID associated with each connection.
-n displays addresses and port numbers in numerical form.
Type 3, in order to work would have to look like this:
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
'pluginname': function(_options) {
// Put defaults inline, no need for another variable...
var options = $.extend({
'defaults': "go here..."
}, _options);
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.
A delayed response but to give multiple packages using annotation based approach we can use as below:
@ComponentScan({"com.my.package.one","com.my.package.subpackage.two","com.your.package.supersubpackage.two"})
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
To access "Host Manager" you have to configure "admin-gui" user inside the tomcat-users.xml
Just add the below lines[change username & pwd] :
<role rolename="admin-gui"/>
<user username="admin" password="password" roles="admin-gui"/>
Restart tomcat 7 server and you are done.
This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.
<td style="display: block; position: relative;">
</td>
If you are able to wrap your XML in a root element - say then the following is your solution:
DECLARE @PersonsXml XML = '<persons><person><firstName>Jon</firstName><lastName>Johnson</lastName></person>
<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>
<person><firstName>Bob</firstName><lastName>Burns</lastName></person></persons>'
SELECT b.value('(./firstName/text())[1]','nvarchar(max)') as FirstName, b.value('(./lastName/text())[1]','nvarchar(max)') as LastName
FROM @PersonsXml.nodes('/persons/person') AS a(b)
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
Check the spelling, mine was 'com.android.aplication'
Tested with Angular2 RC2
I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps
textarea-component.ts
import {Component} from '@angular/core';
@Component({
selector: 'textarea-comp',
template: `
<textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
<p><button (click)="pushMe()">pushMeToLog</button></p>
`
})
export class TextAreaComponent {
str: string;
pushMe() {
console.log( "TextAreaComponent::str: " + this.str);
}
}
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
From Understanding Weak References, by Ethan Nicholas:
Weak references
A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:
WeakReference weakWidget = new WeakReference(widget);
and then elsewhere in the code you can use
weakWidget.get()
to get the actualWidget
object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) thatweakWidget.get()
suddenly starts returningnull
....
Soft references
A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are
WeakReferences
) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.
SoftReferences
aren't required to behave any differently thanWeakReferences
, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.
And Peter Kessler added in a comment:
The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.
Or ask your database:
$ psql -U postgres -c 'SHOW config_file'
or, if logged in as the ubuntu
user:
$ sudo -u postgres psql -c 'SHOW config_file'
If you don't use conda, just use :
pip install openpyxl
If you use conda, I'd recommend :
conda install -c anaconda openpyxl
instead of simply conda install openpyxl
Because there are issues right now with conda updating (see GitHub Issue #8842) ; this is being fixed and it should work again after the next release (conda 4.7.6)
I thought I had this configured but it turns out I set the URL in the wrong place. I followed the URL provided in the Google error page and added my URL here. Stupid mistake from my part, but easily done. Hope this helps
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
Here are some options without using third party libraries:
// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());
// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);
// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);
See the link for more information about System.Web.Helpers.Json.
Update: Nowadays the easiest way to get the Web.Helpers
is to use the NuGet package.
If you don't care about earlier windows versions you can use the classes of the Windows.Data.Json
namespace:
// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());
From official reference
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.
https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
InnoDB with MySQL 5.5 does not support Full-text indexes.
The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.
You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace
using System.Web;
WindowsIdentity user;
user = HttpContext.Current.Request.LogonUserIdentity;
Some time when we use Environ()
function we may get the Library or property not found error. Use VBA.Environ()
or VBA.Environ$()
to avoid the error.
Humm, what? ssh is not something built in to Windows like in most *nix cases.
You'd probably want to use Putty to begin with. And: http://kb.siteground.com/how_to_generate_an_ssh_key_on_windows_using_putty/
What I am doing is using the Windows 10 magnifier. Not the same as zooming on firefox, but it has been quite useful.
I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:
tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */
They both function in exactly the same way (in the context of HTML tables anyway) as:
tr:not(:first-child)
This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below
@Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);
Background Image from API in swift 4 (with Kingfisher) :
import UIKit
import Kingfisher
extension UIView {
func addBackgroundImage(imgUrl: String, placeHolder: String){
let backgroundImage = UIImageView(frame: self.bounds)
backgroundImage.kf.setImage(with: URL(string: imgUrl), placeholder: UIImage(named: placeHolder))
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.insertSubview(backgroundImage, at: 0)
}
}
Usage:
someview.addBackgroundImage(imgUrl: "yourImgUrl", placeHolder: "placeHolderName")
something like:
p
{
display:inline;
}
in your stylesheet would do it for all p tags.
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
You can simply go for: df.describe() that will provide you with all the relevant details you need, but to find the min, max or average value of a particular column (say 'weights' in your case), use:
df['weights'].mean(): For average value
df['weights'].max(): For maximum value
df['weights'].min(): For minimum value
To remove all array elements irrespective of any given id, use this:
collection.update(
{ },
{ $pull: { 'contact.phone': { number: '+1786543589455' } } }
);
Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)
This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..
We were using middleware for token based encryption - decryption and we encountered same error.
Following was our code in route file:
router.route("/uploadVideoMessage")
.post(
middleware.checkToken,
upload.single("video_file"),
videoMessageController.uploadVideoMessage
);
here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.
router.route("/uploadVideoMessage")
.post(
upload.single("video_file"),
middleware.checkToken,
videoMessageController.uploadVideoMessage
);
this is old but for help :
you can also use the stringReader stream
string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:
moment(myDate).utc().format('MM/DD/YYYY')
Values $_GET
are always strings – that's what GET paramters come as. Therefore, is_int($_GET[...])
is always false.
You can test if a string consists only of digits(i.e. could be interpreted as a number) with is_numeric.
e(document).on('show.bs.modal', function () {
if($winWidth < $(window).width()){
$('body.modal-open,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',$(window).width()-$winWidth)
}
});
e(document).on('hidden.bs.modal', function () {
$('body,.navbar-fixed-top,.navbar-fixed-bottom').css('marginRight',0)
});
Seems it is because modal animation is enabled (fade
in class of the dialog), after calling .modal('show')
, the dialog is not immediately visible, so it can't get focus at this time.
I can think of two ways to solve this problem:
fade
from class, so the dialog is immediately visible after calling .modal('show')
. You can see http://codebins.com/bin/4ldqp7x/4 for demo. (Sorry @keyur, I mistakenly edited and saved as new version of your example)focus()
in shown
event like what @keyur wrote.You can use apache commons IOUtils to iterate through the line and append each line to StringBuilder. And don't forget to close the InputStream
StringBuilder sb = new StringBuilder();
FileInputStream fin=new FileInputStream("textfile.txt");
LineIterator lt=IOUtils.lineIterator(fin, "utf-8");
while(lt.hasNext())
{
sb.append(lt.nextLine());
}
String text = sb.toString();
IOUtils.closeQuitely(fin);
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Explanation:
With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.
For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.
With the latest release of Google Play Services, v7.8, you have access to the new Mobile Vision API. That's probably the most convenient way to implement barcode scanning now, and it also works offline.
From the Android Barcode API:
The Barcode API detects barcodes in real-time, on device, in any orientation. It can also detect multiple barcodes at once.
It reads the following barcode formats:
- 1D barcodes: EAN-13, EAN-8, UPC-A, UPC-E, Code-39, Code-93, Code-128, ITF, Codabar
- 2D barcodes: QR Code, Data Matrix, PDF-417, AZTEC
It automatically parses QR Codes, Data Matrix, PDF-417, and Aztec values, for the following supported formats:
- URL
- Contact information (VCARD, etc.)
- Calendar event
- Phone
- SMS
- ISBN
- WiFi
- Geo-location (latitude and longitude)
- AAMVA driver license/ID
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
System.Collections.Generic.List<t>
is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)
Not every jar file is executable.
Now, you need to import the classes, which are there under the jar, in your java file. For example,
import org.xml.sax.SAXException;
If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.
And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar
file, and include all the required jar
s within that. Then, in order to execute your jar
, like,
java -jar my_program.jar
you should have a META-INF/MANIFEST.MF
file in your jar
. See here, for how-to.
Just adding some extra sorting if needed
=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)
All of the above did not work for me. Cloning the repo was working correctly but I was still getting an unrecognized import
error.
As it stands for Go v1.13, I found in the doc that we should use the GOPRIVATE env variable like so:
$ GOPRIVATE=github.com/ORGANISATION_OR_USER_NAME go get -u github.com/ORGANISATION_OR_USER_NAME/REPO_NAME
You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,
Most of the time you would create a list in groovy rather than an array. You could do it like this:
names = ["lucas", "Fred", "Mary"]
Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:
names = "lucas Fred Mary".split()
iframe is also vulnerable to Cross Frame Scripting:
You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.
You can simply use solution provided by jm-
But if you want to deal with the situation more deeply, you have to understand:
How your example "Binding to each element directly" works for AngularJS 1.0.3:
'f'
into input;ngModelController
changes model for item scope (names array is not changed) => name == 'Samf'
, names == ['Sam', 'Harry', 'Sally']
;$digest
loop is started;ngRepeat
replaces model value from item scope ('Samf'
) by value from unchanged names array ('Sam'
);ngModelController
rerenders input with actual model value ('Sam'
).How your example "Indexing into the array" works:
'f'
into input;ngModelController
changes item in names array
=> `names == ['Samf', 'Harry', 'Sally'];ngRepeat
can't find 'Samf'
in cache;ngRepeat
creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.
As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with
<html>
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var x = $("#foo").html();
alert( typeof(x) );
});
</script>
</head>
<body>
<div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
</body>
</html>
The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.
edit: Don't pass a string as the parameter data to .post() but an object, like
var data = {
id: currid,
html: div_html
};
$.post("http://...", data, ...);
jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().
var data = 'id='+ escape(currid) +'&html='+ escape(div_html);
here's how to do it in kotlin:
view.background.setTint(ContextCompat.getColor(context, textColor))
Well it's a very confusing kind of bug. There could be many reasons:
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object
Here's what I would use:
(?<!\S)stackoverflow(?!\S)
In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.
This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b
approach does.
i improved the function a head to be this :
var minifyImg = function(dataUrl,newWidth,imageType="image/jpeg",resolve,imageArguments=0.7){
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
(new Promise(function(resolve){
image = new Image(); image.src = dataUrl;
log(image);
resolve('Done : ');
})).then((d)=>{
oldWidth = image.width; oldHeight = image.height;
log([oldWidth,oldHeight]);
newHeight = Math.floor(oldHeight / oldWidth * newWidth);
log(d+' '+newHeight);
canvas = document.createElement("canvas");
canvas.width = newWidth; canvas.height = newHeight;
log(canvas);
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, newWidth, newHeight);
//log(ctx);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
resolve(newDataUrl);
});
};
the use of it :
minifyImg(<--DATAURL_HERE-->,<--new width-->,<--type like image/jpeg-->,(data)=>{
console.log(data); // the new DATAURL
});
enjoy ;)
First Talk About
Normal Class - that's mean any class define that's a normally in java it's means you create different type of method properties etc.
Bean - Bean is nothing it's only a object of that particular class using this bean you can access your java class same as object..
and after that talk about last one POJO
POJO - POJO is that class which have no any services it's have only a default constructor and private property and those property for setting a value corresponding setter and getter methods. It's short form of Plain Java Object.
I don't see this answer here, so I figure I'll add it since I'm leaning Python right now and just discovered it. The Python tutorial (Python 2 in this case) gives the following simple and effective example:
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
That is, an empty class object is created, then instantiated, and the fields are added dynamically.
The up-side to this is its really simple. The downside is it isn't particularly self-documenting (the intended members aren't listed anywhere in the class "definition"), and unset fields can cause problems when accessed. Those two problems can be solved by:
class Employee:
def __init__ (self):
self.name = None # or whatever
self.dept = None
self.salary = None
Now at a glance you can at least see what fields the program will be expecting.
Both are prone to typos, john.slarly = 1000
will succeed. Still, it works.
Set is used for setting object references, as opposed to assigning a value.
I don't think $timeout is a good way to focus the element on creation. Here is a method using built-in angular functionality, dug out from the murky depths of the angular docs. Notice how the "link" attribute can be split into "pre" and "post", for pre-link and post-link functions.
Working Example: http://plnkr.co/edit/Fj59GB
// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
return {
link: {
pre: function preLink(scope, element, attr) {
console.debug('prelink called');
// this fails since the element hasn't rendered
//element[0].focus();
},
post: function postLink(scope, element, attr) {
console.debug('postlink called');
// this succeeds since the element has been rendered
element[0].focus();
}
}
}
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />
Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile
Solution in Java and the distribution example (2000 points)
public void getRandomPointInCircle() {
double t = 2 * Math.PI * Math.random();
double r = Math.sqrt(Math.random());
double x = r * Math.cos(t);
double y = r * Math.sin(t);
System.out.println(x);
System.out.println(y);
}
based on previus solution https://stackoverflow.com/a/5838055/5224246 from @sigfpe
You can use the ejb3-persistence.jar that's bundled with hibernate. This jar only includes the javax.persistence package.
I removed old AppleWWDRCA, downloaded and installed AppleWWDRCA, but problem remained. I also, checked my distribution and development certificates from Keychain Access, and see below error;
"This certificate has an invalid issuer."
Then,
This fixed certificate problem.
Since old certificates revoked, existing provisioning profiles become invalid. To fix this;
I hope this helps.
Create a function that addresses all the whitespace possibilites and enable only those that seem appropriate:
SELECT dbo.ShowWhiteSpace(myfield) from mytable
Uncomment only those whitespace cases you want to test for:
CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
DECLARE @ShowWhiteSpace varchar(8000);
SET @ShowWhiteSpace = @str
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9), '[TAB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1), '[SOH]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2), '[STX]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3), '[ETX]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4), '[EOT]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5), '[ENQ]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6), '[ACK]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7), '[BEL]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8), '[BS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
-- SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
RETURN(@ShowWhiteSpace)
END
There are two reasons for this error
1) In the array of import if you imported HttpModule twice
2) If you haven't import:
import { HttpModule, JsonpModule } from '@angular/http';
If you want then run:
npm install @angular/http
If git is not installed, we can try
npm install --save https://github.com/Amitesh/gulp-rev-all/tarball/master
You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.
It has builtin resize functions, but you can provide your own if you want.
If you really want to insert this record, remove the `abuse_id`
field and the corresponding value from the INSERT
statement :
INSERT INTO `abuses` ( `user_id` , `abuser_username` , `comment` , `reg_date` , `auction_id` )
VALUES ( 100020, 'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;
1) Clear your chache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser, lets say safari. How did you import the favicon?
2) How you should add it:
Normal favicon:
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
PNG/GIF favicon:
<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />
3) Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver).
4) Try to rename it from favicon.{whatever}
to {yourfaviconname}.{whatever}
but I would suggest you to still have the normal favicon. This has solved my issue on IE.
5) Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:
<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />
Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp
With the use of Google Guava:
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public String readResource(final String fileName, Charset charset) throws Exception {
try {
return Resources.toString(Resources.getResource(fileName), charset);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
Example:
String fixture = this.readResource("filename.txt", Charsets.UTF_8)
Easy! after your:
<font color=\"black\" face=\"arial\" size=\"4\">
add this one:
<font style="opacity:.6">
you just have to change the ".6" for a decimal number between 1 and 0
I found this to work for me:
iconv -f ISO-8859-14 Agreement.txt -t UTF-8 -o agreement.txt
If you are using React.js, you could do this:
render() {
// ...
<img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
// ... }
Where:
Be careful with this. A -1 evaluates to true although -1 != true and -1 != false. Trust me, I've seen it happen.
so
-1 ? "true side" : "false side"
evaluates to "true side"
Another one, using git log:
git log -1 --format="%H"
It's very similar to the of @outofculture though a bit shorter.
I did not read all of the answers, but I did not find the answer I was looking for.
I use Python and don't want to do find/replace or 'blank operations' each time I want to compile code...
So the best solution for me is that it happens on the fly!
Here is the simple solution I found:
Go to:
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
This is a basic move one repo to new location. I use this sequence all te time. With --bare no source files will be seen.
Open Git Bash.
Create a bare clone of the repository.
git clone --bare https://github.com/exampleuser/old-repository.git
Mirror-push to the new repository.
cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ../
rm -rf old-repository.git
Why mirror? See documentation of git: https://git-scm.com/docs/git-push
--all Push all branches (i.e. refs under refs/heads/); cannot be used with other .
--mirror Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration option remote..mirror is set.
trunc(tran_date) = trunc(sysdate -1)
You can use File.WriteAllBytes
I had the same problem today. I needed to set a flag in a nmake Makefile if the cl compiler version is 15. Here is the hack I came up with:
!IF ([cl /? 2>&1 | findstr /C:"Version 15" > nul] == 0)
FLAG = "cl version 15"
!ENDIF
Note that cl /?
prints the version information to the standard error stream and the help text to the standard output. To be able to check the version with the findstr
command one must first redirect stderr to stdout using 2>&1
.
The above idea can be used to write a Windows batch file that checks if the cl compiler version is <=
a given number. Here is the code of cl_version_LE.bat
:
@echo off
FOR /L %%G IN (10,1,%1) DO cl /? 2>&1 | findstr /C:"Version %%G" > nul && goto FOUND
EXIT /B 0
:FOUND
EXIT /B 1
Now if you want to set a flag in your nmake Makefile if the cl version <=
15, you can use:
!IF [cl_version_LE.bat 15]
FLAG = "cl version <= 15"
!ENDIF
In order to make
http://localhost:8080
work, tomcat has to be started first. You can check server.xml file in conf folder for the port information. You can search if tomcat is installed on your machine. Just go to start and then type tomcat. If it is installed it will give you the directory where it is installed. Then you can select that path and run it from command prompt. Example if tomcat is installed in C:\Programfile\tomcat. You need to set this path in command prompt,go to bin folder and startup. Example: C:\Programfile\tomcat\bin\startup. Else you can also run it by directly going to the path and run startup batch file.
Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.
jQuery to check for checked? Really?
if(!this.checked) {
Don't use a bazooka to do a razor's job.
Based on Kiril V. Lyadvinsky answer, I made a new version. This snippet use template and overloading. With it, you can write vector3 = vector1 + vector2
and vector4 += vector3
. Hope it can help.
template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
std::vector<T> AB;
AB.reserve(A.size() + B.size()); // preallocate memory
AB.insert(AB.end(), A.begin(), A.end()); // add A;
AB.insert(AB.end(), B.begin(), B.end()); // add B;
return AB;
}
template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
A.reserve(A.size() + B.size()); // preallocate memory without erase original data
A.insert(A.end(), B.begin(), B.end()); // add B;
return A; // here A could be named AB
}
You can use both .content and .container to overflow:auto. Means if it's text is exceed automatically scroll will come x-axis and y-axis. (no need to give separete x-axis and y-axis commonly give overflow:auto)
.content {overflow:auto;}
I've found the following function and regex useful for word counts, especially in dealing with single vs. double hyphens, where the former generally should not count as a word break, eg, well-known, hi-fi; whereas double hyphen is a punctuation delimiter that is not bounded by white-space--such as for parenthetical remarks.
txt <- "Don't you think e-mail is one word--and not two!" #10 words
words <- function(txt) {
length(attributes(gregexpr("(\\w|\\w\\-\\w|\\w\\'\\w)+",txt)[[1]])$match.length)
}
words(txt) #10 words
Stringi is a useful package. But it over-counts words in this example due to hyphen.
stringi::stri_count_words(txt) #11 words
Update: This answer has led to the development of ng2-completer
an Angular2 autocomplete component.
This is the list of existing autocomplete components for Angular2:
Credit goes to @dan-cancro for coming up with the idea
Keeping the original answer for those who wish to create their own directive:
To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:
It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.
This is the directive code:
"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";
@Directive({
selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
host: {
"(keyup)": "onKey($event)" // Liten to keyup events on the host component
}
})
export class AutocompleteDirective implements OnInit {
// The search function should be passed as an input
@Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
// The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
@Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();
private term = "";
private listCmp: ComponentRef<AutocompleteList> = undefined;
private refreshTimer: any = undefined;
private searchInProgress = false;
private searchRequired = false;
constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
/**
* On key event is triggered when a key is released on the host component
* the event starts a timer to prevent concurrent requests
*/
public onKey(event: any) {
if (!this.refreshTimer) {
this.refreshTimer = setTimeout(
() => {
if (!this.searchInProgress) {
this.doSearch();
} else {
// If a request is in progress mark that a new search is required
this.searchRequired = true;
}
},
200);
}
this.term = event.target.value;
if (this.term === "" && this.listCmp) {
// clean the list if the search term is empty
this.removeList();
}
}
public ngOnInit() {
// When an item is selected remove the list
this.selected.subscribe(() => {
this.removeList();
});
}
/**
* Call the search function and handle the results
*/
private doSearch() {
this.refreshTimer = undefined;
// if we have a search function and a valid search term call the search
if (this.search && this.term !== "") {
this.searchInProgress = true;
this.search(this.term)
.then((res) => {
this.searchInProgress = false;
// if the term has changed during our search do another search
if (this.searchRequired) {
this.searchRequired = false;
this.doSearch();
} else {
// display the list of results
this.displayList(res);
}
})
.catch(err => {
console.log("search error:", err);
this.removeList();
});
}
}
/**
* Display the list of results
* Dynamically load the list component if it doesn't exist yet and update the suggestions list
*/
private displayList(list: Array<{ text: string, data: any }>) {
if (!this.listCmp) {
this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
.then(cmp => {
// The component is loaded
this.listCmp = cmp;
this.updateList(list);
// Emit the selectd event when the component fires its selected event
(<AutocompleteList>(this.listCmp.instance)).selected
.subscribe(selectedItem => {
this.selected.emit(selectedItem);
});
});
} else {
this.updateList(list);
}
}
/**
* Update the suggestions list in the list component
*/
private updateList(list: Array<{ text: string, data: any }>) {
if (this.listCmp) {
(<AutocompleteList>(this.listCmp.instance)).list = list;
}
}
/**
* remove the list component
*/
private removeList() {
this.searchInProgress = false;
this.searchRequired = false;
if (this.listCmp) {
this.listCmp.destroy();
this.listCmp = undefined;
}
}
}
The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:
"use strict";
import {Component, Output, EventEmitter} from "@angular/core";
@Component({
selector: "autocomplete-list",
template: `<div class="dropdown-menu search-results">
<a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
</div>`, // Use a bootstrap 4 dropdown-menu to display the list
styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList {
// Emit a selected event when an item in the list is selected
@Output() public selected = new EventEmitter();
public list;
/**
* Listen for a click event on the list
*/
public onClick(item: {text: string, data: any}) {
this.selected.emit(item);
}
}
To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:
"use strict";
import {Component} from "@angular/core";
import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";
@Component({
selector: "my-cmp",
directives: [AutocompleteDirective],
template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent {
/**
* generate a search function that returns a Promise that resolves to array of text and optionally additional data
*/
public search() {
return (filter: string): Promise<Array<{ text: string, data: any }>> => {
// do the search
resolve({text: "one item", data: null});
};
}
/**
* handle item selection
*/
public onItemSelected(selected: { text: string, data: any }) {
console.log("selected: ", selected.text);
}
}
Update: code compatible with angular2 rc.1
I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block
because this class contain margin
and display
CSS properties but the .text-center
class only contain the text-align
property
Probably the simplest way is to use the InputBox
method of the Microsoft.VisualBasic.Interaction
class:
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Demographics'
$msg = 'Enter your demographics:'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
If you are supporting API 23 and above, you can now use the titleTextColor attribute to set the Toolbar's title color.
layout/toolbar.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:titleTextColor="@color/colorPrimary"
/>
MyActivity.java
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar)
toolbar.setTitleTextColor(Color.WHITE);
My approach is to store the PID to a file in /tmp, and to find the right process using the -S
option for ssh
. That might be a misuse but works for me.
#!/bin/bash
TARGET_REDIS=${1:-redis.someserver.com}
PROXY="proxy.somewhere.com"
LOCAL_PORT=${2:-6379}
if [ "$1" == "stop" ] ; then
kill `cat /tmp/sshTunel${LOCAL_PORT}-pid`
exit
fi
set -x
ssh -f -i ~/.ssh/aws.pem centos@$PROXY -L $LOCAL_PORT:$TARGET_REDIS:6379 -N -S /tmp/sshTunel$LOCAL_PORT ## AWS DocService dev, DNS alias
# SSH_PID=$! ## Only works with &
SSH_PID=`ps aux | grep sshTunel${LOCAL_PORT} | grep -v grep | awk '{print $2}'`
echo $SSH_PID > /tmp/sshTunel${LOCAL_PORT}-pid
Better approach might be to query for the SSH_PID
right before killing it, since the file might be stale and it would kill a wrong process.
First shift the column:
df['gdp'] = df['gdp'].shift(-1)
Second remove the last row which contains an NaN Cell:
df = df[:-1]
Third reset the index:
df = df.reset_index(drop=True)
The @media query specifically for 'phones' is..
@media (max-width: 480px) { ... }
But, you may want to remove the padding/margin for any smaller screen sizes. By default, Bootstrap adjusts margins/padding to the body, container and navbars at 978px.
Here are some queries that have worked (in most cases) for me:
@media (max-width: 978px) {
.container {
padding:0;
margin:0;
}
body {
padding:0;
}
.navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top {
margin-left: 0;
margin-right: 0;
margin-bottom:0;
}
}
Update for Bootstrap 4
Use the new responsive spacing utils which let you set padding/margins for different screen widths (breakpoints): https://stackoverflow.com/a/43208888/171456
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
Java 8 introduces the Instant.ofEpochSecond
utility method for creating an Instant
from a Unix timestamp, this can then be converted into a ZonedDateTime
and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
Yes you can. You can even test it:
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
console.log(++i);_x000D_
if (i === 5) clearInterval(timer);_x000D_
console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
In this example, this timer clears when i
reaches 5.
Try this :
Create anim folder inside your res folder and copy this four files :
slide_in_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>
slide_out_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:duration="@android:integer/config_longAnimTime" />
slide_in_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />
slide_out_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />
When you click on image view call:
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
When you click on original place call:
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
Main Activity :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, test.class));
}
});
}
}
activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
test.java :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class test extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
btn1 = (Button) findViewById(R.id.btn1);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
startActivity(new Intent(test.this, MainActivity.class));
}
});
}
}
test.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
Hope this helps.
Try this,
return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });
Here i mention you are pass multiple values or model also. That's why here i mention that.
Convert the image to a byte[]
and store that in the database.
Add this column to your model:
public byte[] Content { get; set; }
Then convert your image to a byte array and store that like you would any other data:
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using(var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
public Image ByteArrayToImage(byte[] byteArrayIn)
{
using(var ms = new MemoryStream(byteArrayIn))
{
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
Source: Fastest way to convert Image to Byte array
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
When you want to get the image back, get the byte array from the database and use the ByteArrayToImage
and do what you wish with the Image
This stops working when the byte[]
gets to big. It will work for files under 100Mb
Hi you can do it this way
temp = sp.coo_matrix((data, (row, col)), shape=(3, 59))
temp1 = temp.tocsr()
#Cosine similarity
row_sums = ((temp1.multiply(temp1)).sum(axis=1))
rows_sums_sqrt = np.array(np.sqrt(row_sums))[:,0]
row_indices, col_indices = temp1.nonzero()
temp1.data /= rows_sums_sqrt[row_indices]
temp2 = temp1.transpose()
temp3 = temp1*temp2
You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.
http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters
Rough, untested code follows:
appModule.filter('checked', function() {
return function(input, checked) {
if(!input)return input;
var output = []
for (i in input){
var item = input[i];
if(item.checked == checked)output.push(item);
}
return output
}
});
and the view (i added an "uncheck" button too)
<div id="AddItem">
<h3>Add Item</h3>
<input value="1" type="number" placeholder="1" ng-model="itemAmount">
<input value="" type="text" placeholder="Name of Item" ng-model="itemName">
<br/>
<button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
<h3>Checked Items: {{getTotalCheckedItems()}}</h3>
<h4>Checked:</h4>
<table>
<tr ng-repeat="item in items | checked:true" class="item-checked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<i>this item is checked!</i>
<button ng-click="item.checked = false">uncheck item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
<h3>Unchecked Items: {{getTotalItems()}}</h3>
<h4>Unchecked:</h4>
<table>
<tr ng-repeat="item in items | checked:false" class="item-unchecked">
<td><b>amount:</b> {{item.amount}} -</td>
<td><b>name:</b> {{item.name}} -</td>
<td>
<button ng-click="item.checked = true">check item</button>
</td>
</tr>
</table>
</div>
<!-- end: LIST OF ITEMS -->
Then you dont need the toggle methods etc in your controller
The obvious answer wasn't there in all the responses.
PHP has a neat streaming delimiter parser available made for exactly that purpose.
$fp = fopen("/path/to/the/file", "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
For text:
[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
For cell background
[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
Use
sudo pip install virtualenv
Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password.
That's what I do in Opencv to detect focus quality in a region:
Mat grad;
int scale = 1;
int delta = 0;
int ddepth = CV_8U;
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
/// Gradient X
Sobel(matFromSensor, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
/// Gradient Y
Sobel(matFromSensor, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
convertScaleAbs(grad_y, abs_grad_y);
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Scalar mu, sigma;
cv::meanStdDev(grad, /* mean */ mu, /*stdev*/ sigma);
focusMeasure = mu.val[0] * mu.val[0];
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.
Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.
echo variable >> filepath
works for echoing the contents of a variable to a file,echo.
(the period is not a typo) works for echoing a newline character.I think that these two together should work to accomplish what you need.
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
When you do your #includes in main.c, put the #include reference to the file that contains the referenced function at the top of the include list. e.g. Say this is main.c and your referenced function is in "SSD1306_LCD.h"
#include "SSD1306_LCD.h"
#include "system.h" #include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h> // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h" // This has the 'BYTE' type definition
The above will not generate the "implicit declaration of function" error, but below will-
#include "system.h"
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h> // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h" // This has the 'BYTE' type definition
#include "SSD1306_LCD.h"
Exactly the same #include list, just different order.
Well, it did for me.
Pls check JobScheduler for apis above 26
WakeLock was the best option for this but it is deprecated in api level 26
Pls check this link if you consider api levels above 26
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)
It says
As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).
so as it says cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler
if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED
If it isn't about foreground pls check if an Accessibility service could do
another option is to start an activity from broadcast receiver and finish it after starting the service within onCreate() , since newer android versions doesnot allows starting services from receivers
When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe
You can do it using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
In case if your frameId is dynamic, and you only have one iframe, you can use something like:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
Original Answer:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
vim ~/.bash_profile
export PORT=80
sudo visudo
Defaults env_keep +="PORT"
Now when you run sudo node app.js
it should work as desired.
If you don't support legacy browsers, I'd use flexbox
because it's well supported and will simply solve most of your layout problems.
#table-id td:nth-child(1) {
/* nth-child(1) is the first column, change to fit your needs */
display: flex;
justify-content: center;
}
This centers all content in the first <td>
of every row.
If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.
response.session.access_token
doesn't work in my code. But this works:
response.authResponse.accessToken
FB.login(function(response) { alert(response.authResponse.accessToken);
}, {perms:'read_stream,publish_stream,offline_access'});
I had a similar issue where I was not able to either install a CRX file into Chrome.
It turns out that since I had my Downloads folder set to a network mapped drive, it would not allow Chrome to install any extensions and would either do nothing (drag and drop on Chrome) or ask me to download the extension (if I clicked a link from the Web Store).
Setting the Downloads folder to a local disk directory instead of a network directory allowed extensions to be installed.
Running: 20.0.1132.57 m
Check if port 80 and 443 are blocked. or enter - IP graph.facebook.com and enter it in etc/hosts file
Try this function.
structure of node object:
class Node
{
private:
int data;
Node *next;
public:
Node(int);
~Node();
void setData(int);
int getData();
void setNext(Node*);
Node* getNext();
};
Implementation of the function:
Returning a status value is always a god practice, constants defined here are meant for debugging/logging the application usage.
//constants
static int const SUCCESS = 0;
static int const FAILURE = 1;
static int const NULL_OBJ = 2;
static int const POS_EXCEED = 3;
int addAt(int data, int pos){
Node *tmp = new Node(data);
if (tmp == NULL){
//print for debugging only.
cout << "Object not created. Out of memory maybe" << endl;
return NULL_OBJ;
}
if (pos == 0){
// add at beginning
tmp->setNext(this->head);
this->head = tmp;
return SUCCESS;
}else{
// add element in between or at end
int counter = 1;
Node* currentNode = this->head;
while (counter < pos && currentNode->getNext() != NULL){
currentNode= currentNode->getNext();
counter++;
}
tmp->setNext(currentNode->getNext());
currentNode->setNext(tmp);
return SUCCESS;
}
cout << "Failed due to unknown reason.";
return FAILURE;
}
Assumption here is that, you will call the function after validating the inputs (data and position). Though we can validate the parameters inside the function, it is not a good practice.
Hope this helps.
I recently answered a different question where I discussed why the box model is the way it is.
There are specific reasons for each part of the box model. Padding is meant to extend the background beyond its contents. If you need to shrink the background of the container, you should make the parent container the correct size and give the child element some negative margins. In this case the content is not being padded, it's overflowing.
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
$("input").attr("disabled", true);
as of... I don't know any more.
It's December 2013 and I really have no idea what to tell you.
First it was always .attr()
, then it was always .prop()
, so I came back here updated the answer and made it more accurate.
Then a year later jQuery changed their minds again and I don't even want to keep track of this.
Long story short, as of right now, this is the best answer: "you can use both... but it depends."
You should read this answer instead: https://stackoverflow.com/a/5876747/257493
And their release notes for that change are included here:
Neither .attr() nor .prop() should be used for getting/setting value. Use the .val() method instead (although using .attr("value", "somevalue") will continue to work, as it did before 1.6).
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
Or in other words:
".prop = non-document stuff"
".attr" = document stuff
... ...
May we all learn a lesson here about API stability...
If u want a direct/ quick away, without assing to variables:
{
urArray.map((prop, key) => {
console.log(emp);
return <Picker.Item label={emp.Name} value={emp.id} />;
})
}
Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth
argument as:
git clone --depth=1 [email protected]:organization/your-repo.git
to perform a shallow clone.
Use These two lines to your EditText
android:imeActionLabel="Done"
android:singleLine="true"
or you can achieve it Programmatically by this line.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:
$("#myModal").on("hidden.bs.modal", function () {
// put your default event here
});
You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
I see that this post is old. But in version CI v3 here is the answer:
echo $this->uri->uri_string();
Thanks
Try : java -version , then if you see java 11
try to delete with terminal : cd /Library/Java/JavaVirtualMachines rm -rf openjdk-11.0.1.jdk
if it doesn't try delete manually: 1) click on finder 2) go to folder 3) post /Library/Java/JavaVirtualMachines 4) delete java 11 .
then try java version and you will see : java version "1.8.0_191"
This is C#, but should give you the idea:
public static void Main() {
typeof(Program).GetProperty("GetMe", BindingFlags.NonPublic | BindingFlags.Static);
}
private static int GetMe {
get { return 0; }
}
(you need to OR NonPublic and Static only)
For me, view.window
is null on iOS 14.
extension UIViewController {
var topBarHeight: CGFloat {
var top = self.navigationController?.navigationBar.frame.height ?? 0.0
if #available(iOS 13.0, *) {
top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
top += UIApplication.shared.statusBarFrame.height
}
return top
}
}
In summary;
git init
git status
git add "*"
git commit -m "Comment you want"
git remote add origin https://link
git push -u origin master
I would like to share a source with you so that you learn about Git more easily.
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
Set<T> b = new HashSet<>(Arrays.asList(requiredArray));
var GetWeekDays = function (format) {
var weekDays = {};
var curDate = new Date();
for (var i = 0; i < 7; ++i) {
weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
weekday: format ? format : 'short'
});
curDate.setDate(curDate.getDate() + 1);
}
return weekDays;
};
me.GetMonthNames = function (format) {
var monthNames = {};
var curDate = new Date();
for (var i = 0; i < 12; ++i) {
monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
month: format ? format : 'long'
});
curDate.setMonth(curDate.getMonth() + 1);
}
return monthNames;
};
You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.
@Bean(name="asyncExec")
public Executor asyncExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(10);
executor.setThreadNamePrefix("AsynchThread-");
executor.setAllowCoreThreadTimeOut(true);
executor.setKeepAliveSeconds(10);
executor.initialize();
return executor;
}
Then you can define your REST endpoint as follows
@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{
String response = service.callDelayedService();
return CompletableFuture.completedFuture(response);
}
Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)
The CLSID you describe is for the Microsoft.Office.Interop.Excel.ApplicationClass. This class basically launches excel.exe through InprocServer32. If you don't have it installed then it will return the error message you received above.
What about this (a bit late):
def remove_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s