It is the simplest one I could come up with, so wanted to share here,
#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<”Enter the Temperature in Celsius”<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<”Temperature in Fahrenheit is “<<fah;
//get character
getch();
}
Source: Celsius to Fahrenheit
This example works for any double, not just positive integers and takes into account negative numbers or those less than one. For example, 0.000053 would return 5.
private static int getMostSignificantDigit(double value) {
value = Math.abs(value);
if (value == 0) return 0;
while (value < 1) value *= 10;
char firstChar = String.valueOf(value).charAt(0);
return Integer.parseInt(firstChar + "");
}
To get the first digit, this sticks with String manipulation as it is far easier to read.
Sure, for windows
you can use:
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("C:/path/to/php-win.exe -f C:/path/to/script.php", 0, false);
Note:
If you get a COM
error, add the extension to your php.ini
and restart apache
:
[COM_DOT_NET]
extension=php_com_dotnet.dll
You can get value of id,name or value in this way. class name my_class
var id_value = $('.my_class').$(this).attr('id'); //get id value
var name_value = $('.my_class').$(this).attr('name'); //get name value
var value = $('.my_class').$(this).attr('value'); //get value any input or tag
The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.
When you want to use an alias that has space in between then you can use double quotes to refer to that alias.
For example
(select account_id,count(*) "count of" from orders group by 1)sub
Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.
Now let's write an outer query to display the rows where "count of" is greater than 20.
select "count of" from
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;
You can apply the same case to Common Table expressions also.
If your are using MySQL Latest version following may help to reach your requirement.
select * from products where attribs_json->"$.feature.value[*]" in (1,3)
git checkout
has the --ours
option to check out the version of the file that you had locally (as opposed to --theirs
, which is the version that you pulled in). You can pass .
to git checkout
to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add
, and commit your work once done:
git checkout --ours . # checkout our local version of all files
git add -u # mark all conflicted files as merged
git commit # commit the merge
Note the .
in the git checkout
command. That's very important, and easy to miss. git checkout
has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in .
or a filename in order to get the second behavior from git checkout
.
It's also a good habit to have, when passing in a filename, to offset it with --
, such as git checkout --ours -- <filename>
. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout
command.
I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.
The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.
Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD
is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff
).
Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit
if you need to edit it beforehand (for instance, if you rename function foo
to bar
, and someone else adds new code that calls foo
, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).
The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<
, =======
, and >>>>>>>
) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add
before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD
(your side of the merge), and the version from the remote branch.
In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours
or git checkout --theirs
. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add
, and then you can commit the merge with git commit
.
I tried this tool and it gave me good results.
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
I wrote a short convenience function for posting JSON.
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
For a Timer (System.Windows.Forms.Timer).
The .Stop, then .Start methods worked as a reset.
try this code might help, modify it suit your needs
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];_x000D_
for (let el of arr) {_x000D_
console.log(el);_x000D_
if (el === 5) {_x000D_
break;_x000D_
}_x000D_
}
_x000D_
From the docs:
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.
Need the index in the iteration? You can use Array.entries()
:
for (const [index, el] of arr.entries()) {
if ( index === 5 ) break;
}
Using Apache Commons-Lang's SystemUtils.isJavaVersionAtLeast(JavaVersion)
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)
System.out.println("Java version was 8 or greater!");
You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
"".join(["string1", "string2", "string3"]) // "string1string2string"
" ".join(["hello", "world"]) // "hello world"
DISCLAIMER: I wrote this extension
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
The correct answer is don't do that, use the HTML Agility Pack.
Edited to add:
To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());
There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.
Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.
A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.
This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.
I would check your application servers SSL settings and make sure that the certification is configured correctly.
Other approach for Vanilla JavaScript:
for(var o of document.querySelectorAll('#models > option')) {
o.remove()
}
One additional reason to add final to parameter declarations is that it helps to identify variables that need to be renamed as part of a "Extract Method" refactoring. I have found that adding final to each parameter prior to starting a large method refactoring quickly tells me if there are any issues I need to address before continuing.
However, I generally remove them as superfluous at the end of the refactoring.
You can also use =OFFSET([@column];-1;0)
if you are in a named table.
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
It looks you are almost there. Try:
if(error == true){
// Your application has indicated there's an error
window.setTimeout(function(){
// Move to a new location or you can do something else
window.location.href = "https://www.google.co.in";
}, 5000);
}
Use jQuery DataTables plug-in, it supports fixed header and columns. This example adds fixed column support to the html table "example":
http://datatables.net/extensions/fixedcolumns/
For two fixed columns:
http://www.datatables.net/release-datatables/extensions/FixedColumns/examples/two_columns.html
If youre in .NET I recommend the HTML agility pack, very robust even with malformed HTML.
Then you can use XPath.
You can try git difftool
, it is designed to do this stuff.
First, you need to config diff tool to vimdiff
git config diff.tool vimdiff
Then, when you want to diff, just use git difftool
instead of git diff
. It will work as you expect.
Yes, you can use the shadow spread property of the box-shadow rule:
.myDiv_x000D_
{_x000D_
border: 1px solid #333;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
box-shadow: 10px 0 5px -2px #888;_x000D_
}
_x000D_
<div class="myDiv"></div>
_x000D_
The fourth property there -2px
is the shadow spread, you can use it to change the spread of the shadow, making it appear that the shadow is on one side only.
This also uses the shadow positioning rules 10px
sends it to the right (horizontal offset) and 0px
keeps it under the element (vertical offset.)
5px
is the blur radius :)
To dynamically load recaptcha from a ui-view
I use the following method:
In application.js
:
.directive('script', function($parse, $rootScope, $compile) {
return {
restrict: 'E',
terminal: true,
link: function(scope, element, attr) {
if (attr.ngSrc) {
var domElem = '<script src="'+attr.ngSrc+'" async defer></script>';
$(element).append($compile(domElem)(scope));
}
}
};
});
In myPartial.client.view.html
:
<script type="application/javascript" ng-src="http://www.google.com/recaptcha/api.js?render=explicit&onload=vcRecaptchaApiLoaded"></script>
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
I have to agree with Brad. That was an awful answer. The Android documentation states that TableLayout containers do not display border lines, so sending them to the Android site wont help them a bit. I was able to find a "dirty" solution on droidnova, which involves setting a background color for the TableLayout, then setting a different background color for the TableRow and adding layout_margin to the row. I'm not fond of this solution, but it does work for row borders. I guess you could do the same thing with the items composing each "cell" item but I haven't verified.
An example similar to the one on DroidNova:
<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow android:background="#FFFFFF"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp">
...
</TableRow>
</TableLayout>
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Here is another way:
df['rnd'] = np.random.rand(len(df))
df = df.sort_values(by='rnd', inplace=True).drop('rnd', axis=1)
you can write a hoc for this purpose and write a method call redirect, here is the code:
import React, {useState} from 'react';
import {Redirect} from "react-router-dom";
const RedirectHoc = (WrappedComponent) => () => {
const [routName, setRoutName] = useState("");
const redirect = (to) => {
setRoutName(to);
};
if (routName) {
return <Redirect to={"/" + routName}/>
}
return (
<>
<WrappedComponent redirect={redirect}/>
</>
);
};
export default RedirectHoc;
ApplicationPoolIdentity is actually the best practice to use in IIS7+. It is a dynamically created, unprivileged account. To add file system security for a particular application pool see IIS.net's "Application Pool Identities". The quick version:
If the application pool is named "DefaultAppPool" (just replace this text below if it is named differently)
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.
Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.
-> Locate the root cause in the middle is your job.
Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,
Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order.
If conda install opencv
or conda install -c https://conda.binstar.org/menpo opencv
does not work, you can try to compile from the source.
Download the source from http://opencv.org/downloads.html, follow the install instruction in http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html, (maybe you can jump to the last part directly, 'Building OpenCV from Source Using CMake...), change the cmake
command as following:
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/home/**/env/opencv-2.4.10 -D BUILD_NEW_PYTHON_SUPPORT=ON -D PYTHON_EXECUTABLE=/home/**/env/anaconda/bin/python -D PYTHON_INCLUDE_DIR=/home/**/env/anaconda/include/python2.7 -D PYTHON_LIBRARY=/home/**/env/anaconda/lib/libpython2.7.so -D PYTHON_PACKAGES_PATH=/home/**/env/anaconda/lib/python2.7/site-packages -D PYTHON_NUMPY_INCLUDE_DIRS=/home/**/env/anaconda/lib/python2.7/site-packages/numpy/core/include ..
make -j4
make install
You will find cv2.so in anaconda/lib/python2.7/site-packages
.
Then:
import cv2
print cv2.__version__
It will print out 2.4.10
.
My environment is GCC 4.4.6, Python 2.7 (anaconda), and opencv-2.4.10.
You can use sys.argv
to get the arguments as a list.
If you need to access individual elements, you can use
sys.argv[i]
where i
is index, 0
will give you the python filename being executed. Any index after that are the arguments passed.
Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100
. But OpenCV uses H: 0-179, S: 0-255, V: 0-255
. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255)
.
Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:
cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)
Now run it. I got an output as follows:
Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.
EDIT:
As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2
module, so users can compare the easiness and flexibility of new cv2
module.
import cv2
import numpy as np
img = cv2.imread('sof.jpg')
ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)
It gives the same result as above. But code is much more simpler.
No need to use Linq like this here, because there already exists an extension method to do this for you.
Enumerable.Except<TSource>
http://msdn.microsoft.com/en-us/library/bb336390.aspx
You just need to create your own comparer to compare as needed.
CSS doesn't really allow you to do this on a table level. Generally, I specify cellspacing="3"
when I want to achieve this effect. Obviously not a css solution, so take it for what it's worth.
Give this a try :P
s = '#'.repeat(10)_x000D_
_x000D_
document.body.innerHTML = s
_x000D_
Step 1 : Create file named : my_button_bg.xml
Step 2 : Place this file in res/drawables.xml
Step 3 : Insert below code
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#FFFFFF"
android:endColor="#00FF00"
android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>
Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Text"
android:background="@drawable/my_button_bg"
/>
On new admob version USE this :
//Load your adView before
adView.setAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
Toast.makeText(Your current activity.this, "Ad failed: " + errorCode, Toast.LENGTH_SHORT).show();
}
});
If Ads load on your emulator, meaning that they return test ads, that should mean that there's nothing wrong with your code. Do they load test ads on your phone as well?
If you're able to see test ads on the emulator and test devices, then it usually just means that AdMob (assuming you're using AdMob) is unable to return an Ad due to a lack of Ad inventory. If this is the case, then when looking at the Logcat you should see the line W/Ads: Failed to load ad: 3.
What you should do is plug in an Android phone to your computer, and then in Android Studio click on Logcat, and in the top left you should see some devices to select from. Select your phone if it's listed (it should be). The logcat will now be printing everything your phone is printing. In the filter bar, type in ads to filter out stuff you don't need to see.
Then open your application in your phone, and check the logcat. Make sure your device isn't considered a test device. If you see W/Ads: Failed to load ad: 3 then that should mean that the problem lies with AdMob and not you.
If it doesn't say that and it says something else, then I obviously don't know.
In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).
Another alternative is to use the ufunc.at. This method applies in-place a desired operation at specified indices. We can get the bin position for each datapoint using the searchsorted method. Then we can use at to increment by 1 the position of histogram at the index given by bin_indexes, every time we encounter an index at bin_indexes.
np.random.seed(1)
data = np.random.random(100) * 100
bins = np.linspace(0, 100, 10)
histogram = np.zeros_like(bins)
bin_indexes = np.searchsorted(bins, data)
np.add.at(histogram, bin_indexes, 1)
It you can live with a fixed size, arrays will will be faster and need less memory.
If you need the flexibility of the List interface with adding and removing elements, the question remains which implementation you should choose. Often ArrayList is recommended and used for any case, but also ArrayList has its performance problems if elements at the beginning or in the middle of the list must be removed or inserted.
You therefore may want to have a look at http://java.dzone.com/articles/gaplist-%E2%80%93-lightning-fast-list which introduces GapList. This new list implementation combines the strengths of both ArrayList and LinkedList resulting in very good performance for nearly all operations.
The problem with the accepted answer is that it cannot signal failure. There's strtol
(STRing TO Long) which can. It's part of a larger family: wcstol
(Wide Character String TO Long, e.g. Unicode), strtoull
(TO Unsigned Long Long, 64bits+), wcstoull
, strtof
(TO Float) and wcstof
.
The most likely reason that it's used so much in universities is that the mathematics faculty are used to it, understand it, and know how to incorporate it into their curriculum.
As a bare minimum:
tsconfig:
"lib": [
"es2015"
]
and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
I came here from google so it might be relevant to others:
for yarn
you could use:
yarn --cwd /path/to/your/app run start
Dim originally (in BASIC) stood for Dimension, as it was used to define the dimensions of an array.
(The original implementation of BASIC was Dartmouth BASIC, which descended from FORTRAN, where DIMENSION is spelled out.)
Nowadays, Dim is used to define any variable, not just arrays, so its meaning is not intuitive anymore.
I tried all these solutions on a Grouped Tablix with row spaces and none worked across the entire report. The result was duplicate colored rows and other solutions resulted in alternating columns!
Here is the function I wrote that worked for me using a Column Count:
Private bOddRow As Boolean
Private cellCount as Integer
Function AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String
if cellCount = ColCount Then
bOddRow = Not bOddRow
cellCount = 0
End if
cellCount = cellCount + 1
if bOddRow Then
Return OddColor
Else
Return EvenColor
End If
End Function
For a 7 Column Tablix I use this expression for Row (of Cells) Backcolour:
=Code.AlternateColorByColumnCount("LightGrey","White", 7)
Another example, this uses CSS, I simply put the form in a div with the container class. And specified that input elements contained within are to be 100% of the container width and not have any elements on either side.
.container {_x000D_
width: 500px;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.container input {_x000D_
width: 100%;_x000D_
clear: both;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Example form</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="container">_x000D_
<form>_x000D_
<label>First Name</label>_x000D_
<input type="text" name="first"><br />_x000D_
<label>Last Name</label>_x000D_
<input type="text" name="last"><br />_x000D_
<label>Email</label>_x000D_
<input type="text" name="email"><br />_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Now require-dev
is enabled by default, for local development you can do composer install
and composer update
without the --dev
option.
When you want to deploy to production, you'll need to make sure composer.lock
doesn't have any packages that came from require-dev
.
You can do this with
composer update --no-dev
Once you've tested locally with --no-dev
you can deploy everything to production and install based on the composer.lock
. You need the --no-dev
option again here, otherwise composer will say "The lock file does not contain require-dev information".
composer install --no-dev
Note: Be careful with anything that has the potential to introduce differences between dev and production! I generally try to avoid require-dev wherever possible, as including dev tools isn't a big overhead.
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).
There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory.
You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects).
If you have the freedom to choose the hostname, then you can just add your host to a dynanmic DNS service, like dyndns.org. Then you can rely on the iPad's normal resolution mechanisms to resolve the address.
My solution would be to use filter after the map.
This should support every JS data type.
example:
const notUndefined = anyValue => typeof anyValue !== 'undefined'
const noUndefinedList = someList
.map(// mapping condition)
.filter(notUndefined); // by doing this,
//you can ensure what's returned is not undefined
Using RxJs, you can declare a Subject
in your parent component and pass it as Observable
to child component, child component just need to subscribe to this Observable
.
Parent-Component
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
Parent-HTML
<child [events]="eventsSubject.asObservable()"> </child>
Child-Component
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
var a = A.parentNode.replaceChild(document.createElement("span"), A);
a is the replaced A element.
Try the following configuration:
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the Java code accordingly:
static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");
Do you want output to go to stdout
? If not, change the first line of log4j.properties
to:
log4j.rootLogger=OFF
and get rid of the stdout
lines.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an intent that will start the main activity. */
Intent mainIntent = new Intent(SplashScreen.this,
ConnectedActivity.class);
mainIntent.putExtra("id", "1");
//SplashScreen.this.startActivity(mainIntent);
startActivity(mainIntent);
/* Finish splash activity so user cant go back to it. */
SplashScreen.this.finish();
/* Apply our splash exit (fade out) and main
entry (fade in) animation transitions. */
overridePendingTransition(R.anim.mainfadein,R.anim.splashfadeout);
}
}, SPLASH_DISPLAY_TIME);
}
Go to the Run->Run Configuration-> now
Under C/C++ Application you will see the name of your executable + Debug (if not, click over C/C++ Application a couple of times). Select the name (in this case projectTitle+Debug).
Under this in main Tab -> C/C++ application -> Search your project -> in binaries select your binary titled by your project....
You can create .war file back from your existing folder.
Using this command
cd /to/your/folder/location
jar -cvf my_web_app.war *
The first argument to printf()
is always a string value, known as a format control string. This string may be regular text, such as
printf("Hello, World\n"); // \n indicates a newline character
or
char greeting[] = "Hello, World\n";
printf(greeting);
This string may also contain one or more conversion specifiers; these conversion specifiers indicate that additional arguments have been passed to printf()
, and they specify how to format those arguments for output. For example, I can change the above to
char greeting[] = "Hello, World";
printf("%s\n", greeting);
The "%s" conversion specifier expects a pointer to a 0-terminated string, and formats it as text.
For signed decimal integer output, use either the "%d" or "%i" conversion specifiers, such as
printf("%d\n", addNumber(a,b));
You can mix regular text with conversion specifiers, like so:
printf("The result of addNumber(%d, %d) is %d\n", a, b, addNumber(a,b));
Note that the conversion specifiers in the control string indicate the number and types of additional parameters. If the number or types of additional arguments passed to printf()
don't match the conversion specifiers in the format string then the behavior is undefined. For example:
printf("The result of addNumber(%d, %d) is %d\n", addNumber(a,b));
will result in anything from garbled output to an outright crash.
There are a number of additional flags for conversion specifiers that control field width, precision, padding, justification, and types. Check your handy C reference manual for a complete listing.
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
#grad
{
background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); /*Safari 5.1-6*/
background: -o-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Opera 11.1-12*/
background: -moz-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); /*Fx 3.6-15*/
background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1)); /*Standard*/
}
I found this in w3schools and suited my needs while I was looking for gradient and transparency. I am providing the link to refer to w3schools. Hope this helps if any one is looking for gradient and transparency.
http://www.w3schools.com/css/css3_gradients.asp
Also I tried it in w3schools to change the opacity pasting the link for it check it
http://www.w3schools.com/css/tryit.asp?filename=trycss3_gradient-linear_trans
Hope it helps.
The issue is due to the availability of more than one eclipse versions. I tried removing both installations and started with a clean install and it worked. Also, make sure after the install point to a new workspace.
I had the same problem and later I realised that my app-routing.module.ts was inside a sub folder called app-routing. I moved this file directly under src and now it is working. (Now app-routing file has access to all the components)
if your list has negative numbers, this is how you would normalize it
a = range(-30,31,5)
norm = [(float(i)-min(a))/(max(a)-min(a)) for i in a]
I know it's a bit late, but I just came across this post and wanted to mention that I don't really see way everybody wants to do it in a difficult way... The problem here is just that the book class takes twoside as default, so, as gromgull said, just pass oneside as argument and it's solved.
I modified the code and wrapped view update inside $apply().
link: function (scope, elem, attrs, ngModelCtrl){
var updateModel = function(dateText){
// call $apply to update the model
scope.$apply(function(){
ngModelCtrl.$setViewValue(dateText);
});
};
var options = {
dateFormat: "dd/mm/yy",
// handle jquery date change
onSelect: function(dateText){
updateModel(dateText);
}
};
// jqueryfy the element
elem.datepicker(options);
}
working fiddle - http://jsfiddle.net/hsfid/SrDV2/1/embedded/result/
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.
window.portalData = [_x000D_
{_x000D_
"kpi" : "NDAR",_x000D_
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
},_x000D_
{_x000D_
"kpi" : "NTI",_x000D_
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
},_x000D_
{_x000D_
"kpi" : "BS",_x000D_
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
},_x000D_
{_x000D_
"kpi" : "SISS",_x000D_
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
},_x000D_
{_x000D_
"kpi" : "MID",_x000D_
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_
}_x000D_
];
_x000D_
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
Swift 4
func writeImage(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)
}
@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if (error != nil) {
// Something wrong happened.
print("error occurred: \(String(describing: error))")
} else {
// Everything is alright.
print("saved success!")
}
}
This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver
try {
String Query = "INSERT INTO `stock`(`stock`, `min_stock`,
`id_stock`) VALUES ("
+ "\"" + p.get_Stock().getStock() + "\", "
+ "\"" + p.get_Stock().getStockMinimo() + "\","
+ "" + "null" + ")";
Statement st = miConexion.createStatement();
st.executeUpdate(Query);
java.sql.ResultSet rs;
rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");
rs.next(); //para posicionar el puntero en la primer fila
ultimo_id = rs.getInt("LAST_INSERT_ID()");
} catch (SqlException ex) { ex.printTrace;}
If you don't want to install full mysql, we can fix this by just installing mysqlclient
brew install mysqlclient
Once cmd is completed it will ask to add below line to ~/.bash_profile
:
echo 'export PATH="/usr/local/opt/mysql-client/bin:$PATH"' >> ~/.bash_profile
Close terminal and start new terminal and proceed with pip install mysqlclient
the problem might be that networkservice has no read rights
salution:
rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply
I know this question is old, but in case it helps anyone make sure the SQL Server Browser is running in the Services MSC. I installed SQL Server Express 2008 R2 and the SQL Server Browser Service was set to Disabled.
In the CSS write:
.exampleclass {
background:#000000;
opacity: 10; /* you can always adjust this */
}
Assuming you've got access to a standard Unix shell and/or cygwin environment:
tr -s ' ' '\n' < yourfile | sort | uniq -d -c
^--space char
Basically: convert all space characters to linebreaks, then sort the tranlsated output and feed that to uniq and count duplicate lines.
If the strings you want to join are in List of Objects, then you can do something like this too:
var studentNames = string.Join(", ", students.Select(x => x.name));
SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0
When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.
While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.
Reference SO post for comparative view.
Don't use @@ERROR
, use BEGIN TRY/BEGIN CATCH
instead. See this article: Exception handling and nested transactions for a sample procedure:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
end catch
end
This is the consistent cross-browser way I found:
var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];
var svgCalculateSize = function (el) {
var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
bounds = {
width: 0,
height: 0
};
heightComponents.forEach(function (css) {
bounds.height += parseFloat(gCS[css]);
});
widthComponents.forEach(function (css) {
bounds.width += parseFloat(gCS[css]);
});
return bounds;
};
HTML5 spec:
http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :
The checked content attribute is a boolean attribute
http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Conclusion:
The following are valid, equivalent and true:
<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />
The following are invalid:
<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />
The absence of the attribute is the only valid syntax for false:
<input type="text" />
Recommendation
If you care about writing valid XHTML, use disabled="disabled"
, since <input disabled>
is invalid and other alternatives are less readable. Else, just use <input disabled>
as it is shorter.
Why not ?
Just modify your Main-Class
to receive arguments and act upon the argument.
public class wiki2txt {
public static void main(String[] args) {
String fileName = args[0];
// Use FileInputStream, BufferedReader etc here.
}
}
Specify the full path in the commandline.
java -jar wiki2txt /home/bla/enwiki-....xml
I cannot replicate the results discussed here.
I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.
Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the +=
assignment wasn't asking the FPU to add memory garbage interpreted as a double.
I played around with various schemes, such as putting the assignment of b[j]
, d[j]
to InitToZero[j]
inside the loops, and also with using += b[j] = 1
and += d[j] = 1
, and I got fairly consistent results.
As you might expect, initializing b
and d
inside the loop using InitToZero[j]
gave the combined approach an advantage, as they were done back-to-back before the assignments to a
and c
, but still within 10%. Go figure.
Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.
PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.
// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>
#define dbl double
#define MAX_ARRAY_SZ 262145 //16777216 // AKA (2^24)
#define STEP_SZ 1024 // 65536 // AKA (2^16)
int _tmain(int argc, _TCHAR* argv[]) {
long i, j, ArraySz = 0, LoopKnt = 1024;
time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;
a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
// Initialize array to 1.0 second.
for(j = 0; j< MAX_ARRAY_SZ; j++) {
InitToOnes[j] = 1.0;
}
// Increase size of arrays and time
for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
// Outside the timing loop, initialize
// b and d arrays to 1.0 sec for consistent += performance.
memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));
start = clock();
for(i = LoopKnt; i; i--) {
for(j = ArraySz; j; j--) {
a[j] += b[j];
c[j] += d[j];
}
}
Cumulative_Combined += (clock()-start);
printf("\n %6i miliseconds for combined array sizes %i and %i loops",
(int)(clock()-start), ArraySz, LoopKnt);
start = clock();
for(i = LoopKnt; i; i--) {
for(j = ArraySz; j; j--) {
a[j] += b[j];
}
for(j = ArraySz; j; j--) {
c[j] += d[j];
}
}
Cumulative_Separate += (clock()-start);
printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
(int)(clock()-start), ArraySz, LoopKnt);
}
printf("\n Cumulative combined array processing took %10.3f seconds",
(dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
printf("\n Cumulative seperate array processing took %10.3f seconds",
(dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
getchar();
free(a); free(b); free(c); free(d); free(InitToOnes);
return 0;
}
I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=
, but I am not sure why.
A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.
You can also set DirectoryIndex in apache's httpd.conf file.
CentOS keeps this file in /etc/httpd/conf/httpd.conf
Debian: /etc/apache2/apache2.conf
Open the file in your text editor and find the line starting with DirectoryIndex
To load landing.html as a default (but index.html if that's not found) change this line to read:
DirectoryIndex landing.html index.html
.bbg {
/* The image used */
background-image: url('...');
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<!doctype html>
<html class="h-100">
.
.
.
<body class="bbg">
</body>
.
.
.
</html>
After button click event complete your any task...last line copy and past it...Is's Working Fine...C# in Asp.Net
Page.Header.Controls.Add(new LiteralControl(string.Format(@" <META http-equiv='REFRESH' content=3.1;url={0}> ", Request.Url.AbsoluteUri)));
run this query before creating or altering table.
SET @@global.innodb_large_prefix = 1;
this will set max key length to 3072 bytes
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
I think you want to print the name of the person or both the name and email :
const renObjData = this.props.data.map(function(data, idx) {
return <p key={idx}>{data.name}</p>;
});
or :
const renObjData = this.props.data.map(function(data, idx) {
return ([
<p key={idx}>{data.name}</p>,
<p key={idx}>{data.email}</p>,
]);
});
git config --get-regexp "branch\.$current_branch\.remote"
will give you the name of the remote that is being tracked
git config --get-regexp "branch\.$current_branch\.merge"
will give you the name of the remote branch that's being tracked.
You'll need to replace $current_branch with the name of your current branch. You can get that dynamically with git rev-parse --abbrev-ref HEAD
The following mini-script combines those things. Stick it in a file named git-tracking
, make it executable, and make sure it's in your path.
then you can say
$ git tracking
<current_branch_name>-><remote_repo_name>/<remote_branch_name>
note that the remote branch name can be different from your local branch name (although it usually isn't). For example:
$git tracking
xxx_xls_xslx_thing -> origin/totally_bogus
as you can see in the code the key to this is extracting the data from the git config. I just use sed to clear out the extraneous data.
#!/bin/sh
current_branch=$(git rev-parse --abbrev-ref HEAD)
remote=$(git config --get-regexp "branch\.$current_branch\.remote" | sed -e "s/^.* //")
remote_branch=$(git config --get-regexp "branch\.$current_branch\.merge" | \
sed -e "s/^.* //" -e "s/refs\/.*\///")
echo "$current_branch -> $remote/$remote_branch"
If you could get the data as a generic tuple when you read it in or retrieved it, it would be a lot easier; then you would just have to write a Sort function that compares the desired column of the tuple, and you have a single dimension array of tuples.
I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine
rm -rf app/cache/*
rm -rf app/logs/*
The plain javascript code sample which answers your question literally:
return location.search.indexOf('q=')>=0;
The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:
var queryString=location.search;
var params=queryString.substring(1).split('&');
for(var i=0; i<params.length; i++){
var pair=params[i].split('=');
if(decodeURIComponent(pair[0])=='q' && pair[1])
return true;
}
return false;
You can do like this
DELETE FROM table WHERE id NOT IN ( 2 )
OR
DELETE FROM table WHERE id <> 2
As @Frank Schmitt noted, you might want to be careful about the NULL values too. If you want to delete everything which is not 2
(including the NULLs) then add OR id IS NULL
to the WHERE clause.
Take a look at realpath
which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:
CONTAININGDIR=$(realpath ${FILEPATH%/*})
to do what it sounds like you're trying to do.
Some of the answers I've seen explain how to make the contents of a cell invisible, but not how to hide the entire column, which is what I wanted to do.
If you have AutoGenerateColumns = "false"
and are actually using BoundField
for the column you want to hide, Bala's answer is slick. But if you are using TemplateField
for the column, you can handle the DataBound
event and do something like this:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
This may not be what the OP was looking for, but it's the solution I was looking for when I found myself asking the same question.
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");
You're also not going to get the output you're hoping for as long as you append to listoflists only inside the if-clause.
Try something like this instead:
import copy
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((copy.copy(list), copy.copy(list[0])))
print(listoflists)
Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent()
. Example:
list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
I think this is because you are using client software and not the server.
mysql
is client mysqld
is the serverTry:
sudo service mysqld start
To check that service is running use: ps -ef | grep mysql | grep -v grep
.
Uninstalling:
sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean
Re-Installing:
sudo apt-get update
sudo apt-get install mysql-server
Backup entire folder before doing this:
sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade
This will keep the right aspect ratio.
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
You could just write a little script that would try to import all the modules and tell you which ones are failing and which ones are working:
import pip
if __name__ == '__main__':
for package in pip.get_installed_distributions():
pack_string = str(package).split(" ")[0]
try:
if __import__(pack_string.lower()):
print(pack_string + " loaded successfully")
except Exception as e:
print(pack_string + " failed with error code: {}".format(e))
Output:
zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...
Word of warning this will try to import everything so you'll see things like PyYAML failed with error code: No module named pyyaml
because the actual import name is just yaml. So as long as you know your imports this should do the trick for you.
Don’t add the .table
class to your <table>
tag. From the Bootstrap docs on tables:
For basic styling—light padding and only horizontal dividers—add the base class
.table
to any<table>
. It may seem super redundant, but given the widespread use of tables for other plugins like calendars and date pickers, we've opted to isolate our custom table styles.
There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:
?var foo;
?var myString1 = String(foo); // "undefined" as a string
var myString2 = foo + ''; // "undefined" as a string
var myString3 = foo.toString(); // throws an exception
In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".
Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.
The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)
License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.
For a string of length 1 you can simply perform isdigit()
or isalpha()
If your string length is greater than 1, you can make a function something like..
def isinteger(a):
try:
int(a)
return True
except ValueError:
return False
You can also compile it from source like this
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install
Find detailed instructions here http://howtonode.org/how-to-install-nodejs
My answer is similar to this one on ServerFault.com.
If you want to be more conservative than granting "all privileges", you might want to try something more like these.
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;
The use of public
there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.
To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.
You will not notice this requirement when first using Postgres. By default every database has a first schema named public
. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.
GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;
Excerpt from the Postgres doc:
For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.
For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.
These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.
You could use PHP's dirname function.
<?php echo dirname(__DIR__); ?>
.
That will give you the name of the parent directory of __DIR__
, which stores the current directory.
During migration from Ubuntu 12.04 to 14.04 I stumbled over this as well and wanted to share that as of Ubuntu 14.04 LTS the IMAP extension seems no longer to be loaded per default.
Check to verify if the extension is installed:
dpkg -l | grep php5-imap
should give a response like this:
ii php5-imap 5.4.6-0ubuntu5 amd64 IMAP module for php5
if not, install it.
To actually enable the extension
cd /etc/php5/apache2/conf.d
ln -s ../../mods-available/imap.ini 20-imap.ini
service apache2 restart
should fix it for apache. For CLI do the same in /etc/php5/cli/conf.d
In my case I received a message like this: See this picture
I just commented the snipped code below in the project file (.csproj) and the problem was fixed.
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
First and foremost make sure the correct provisioning profile is selected for the configuration that you have selected before building if you have manually set the provisioning profile. If you have set automatic as your provisioning profile make sure the correct provisioning profile is being picked up by Xcode while building.
Try using the "%h"
modifier:
scanf("%hu", &length);
^
ISO/IEC 9899:201x - 7.21.6.1-7
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.
file = open('Failed.py', 'w')
file.write('whatever')
file.close()
Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:
with open('Failed.py', 'w') as file:
file.write('whatever')
You could use a bit of jQuery:
$('input:radio').click(function(){
$('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});
You'd need to make sure your checked radio buttons have the correct class on page load as well.
The @BeforeClass
and @AfterClass
annotated methods will be run exactly once during your test run - at the very beginning and end of the test as a whole, before anything else is run. In fact, they're run before the test class is even constructed, which is why they must be declared static
.
The @Before
and @After
methods will be run before and after every test case, so will probably be run multiple times during a test run.
So let's assume you had three tests in your class, the order of method calls would be:
setUpBeforeClass()
(Test class first instance constructed and the following methods called on it)
setUp()
test1()
tearDown()
(Test class second instance constructed and the following methods called on it)
setUp()
test2()
tearDown()
(Test class third instance constructed and the following methods called on it)
setUp()
test3()
tearDown()
tearDownAfterClass()
every 3 posts?
if($counter % 3 == 0){
echo IMAGE;
}
Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.
Define the following tag on the top of your web page:
<!DOCTYPE html>
settings.xml
is not required (and thus not autocreated in ~/.m2 folder) unless you want to change the default settings.
Standalone maven and the maven in eclipse will use the same local repository (~/.m2 folder). This means if some artifacts/dependencies are downloaded by standalone maven, it will not be again downloaded by maven in eclipse.
Based on the version of Eclipse that you use, you may have different maven version in eclipse compared to the standalone. It should not matter in most cases.
Welcome to the wonderful world of Angular !!
I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you
There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.
First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.
So, you'll need to add a few lines to your web.config file:
<configuration>
...
<system.webServer>
<httpErrors errorMode="Detailed"/>
<validation validateIntegratedModeConfiguration="false"/>
<!-- We need the following 6 lines, to let AngularJS call our REST web services -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
...
</configuration>
Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:
// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
Once you have these fixes in place, actually calling a RESTful API is really straightforward.
function YourAngularController($scope, $http)
{
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
//
// Do something with the data !
//
});
}
You can find a really clear walkthrough of these steps on this webpage:
Good luck !
Mike
For Ubuntu users, an answer can be found here. I also quote it:
The most probable cause, is that you have not installed the appropriate dependencies. Your Ubuntu system has to have some packages installed regarding conversion of LaTeX and XeTeX files, in order to save your notebook as PDF. You can install them by:
sudo apt-get install texlive texlive-xetex texlive-generic-extra texlive-generic-recommended pandoc
Also,
nbconvert
is another dependency that is usually automatically installed with jupyter. But you can install it just to be sure, while having your virtual environment activated:pip install -U nbconvert
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').
For me the issue was that I had "Optimize code" enabled in the Build tab of my project's settings.
Put this code in a file called MY_Exceptions.php in application/core folder:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
* Class dealing with errors as exceptions
*/
class MY_Exceptions extends CI_Exceptions
{
/**
* Force exception throwing on erros
*/
public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
set_status_header($status_code);
$message = implode(" / ", (!is_array($message)) ? array($message) : $message);
throw new CiError($message);
}
}
/**
* Captured error from Code Igniter
*/
class CiError extends Exception
{
}
It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:
$db['default']['db_debug'] = true;
Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.
Update:
You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.
RexExp
instances have a lastIndex property already (if they are global) and so what I'm doing is copying the regular expression, modifying it slightly to suit our purposes, exec
-ing it on the string and looking at the lastIndex
. This will inevitably be faster than looping on the string. (You have enough examples of how to put this onto the string prototype, right?)
function reIndexOf(reIn, str, startIndex) {
var re = new RegExp(reIn.source, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));
re.lastIndex = startIndex || 0;
var res = re.exec(str);
if(!res) return -1;
return re.lastIndex - res[0].length;
};
function reLastIndexOf(reIn, str, startIndex) {
var src = /\$$/.test(reIn.source) && !/\\\$$/.test(reIn.source) ? reIn.source : reIn.source + '(?![\\S\\s]*' + reIn.source + ')';
var re = new RegExp(src, 'g' + (reIn.ignoreCase ? 'i' : '') + (reIn.multiLine ? 'm' : ''));
re.lastIndex = startIndex || 0;
var res = re.exec(str);
if(!res) return -1;
return re.lastIndex - res[0].length;
};
reIndexOf(/[abc]/, "tommy can eat"); // Returns 6
reIndexOf(/[abc]/, "tommy can eat", 8); // Returns 11
reLastIndexOf(/[abc]/, "tommy can eat"); // Returns 11
You could also prototype the functions onto the RegExp object:
RegExp.prototype.indexOf = function(str, startIndex) {
var re = new RegExp(this.source, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));
re.lastIndex = startIndex || 0;
var res = re.exec(str);
if(!res) return -1;
return re.lastIndex - res[0].length;
};
RegExp.prototype.lastIndexOf = function(str, startIndex) {
var src = /\$$/.test(this.source) && !/\\\$$/.test(this.source) ? this.source : this.source + '(?![\\S\\s]*' + this.source + ')';
var re = new RegExp(src, 'g' + (this.ignoreCase ? 'i' : '') + (this.multiLine ? 'm' : ''));
re.lastIndex = startIndex || 0;
var res = re.exec(str);
if(!res) return -1;
return re.lastIndex - res[0].length;
};
/[abc]/.indexOf("tommy can eat"); // Returns 6
/[abc]/.indexOf("tommy can eat", 8); // Returns 11
/[abc]/.lastIndexOf("tommy can eat"); // Returns 11
A quick explanation of how I am modifying the RegExp
: For indexOf
I just have to ensure that the global flag is set. For lastIndexOf
of I am using a negative look-ahead to find the last occurrence unless the RegExp
was already matching at the end of the string.
I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.
Look at these two excerpts:
I uploaded my website to my domain under the public folder.
and
This error can be caused by a virtual directory not being configured as an application in IIS.
It's pretty clear to me that you did exactly what you said you did, and no more, i.e. you transfered the files to the web server, but nothing else. You need to configure that public folder as a virtual directory in IIS as the error is telling you, or it's just not going to work.
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
I'm not sure @cmbuckley answer is showing the full picture. What I read is:
Unless the cookie's attributes indicate otherwise, the cookie is returned only to the origin server (and not, for example, to any subdomains), and it expires at the end of the current session (as defined by the user agent). User agents ignore unrecognized cookie.
Also
8.6. Weak Integrity
Cookies do not provide integrity guarantees for sibling domains (and
their subdomains). For example, consider foo.example.com and
bar.example.com. The foo.example.com server can set a cookie with a
Domain attribute of "example.com" (possibly overwriting an existing
"example.com" cookie set by bar.example.com), and the user agent will
include that cookie in HTTP requests to bar.example.com. In the
worst case, bar.example.com will be unable to distinguish this cookie
from a cookie it set itself. The foo.example.com server might be
able to leverage this ability to mount an attack against
bar.example.com.
To me that means you can protect cookies from being read by subdomain/domain but cannot prevent writing cookies to the other domains. So somebody may rewrite your site cookies by controlling another subdomain visited by the same browser. Which might not be a big concern.
Awesome cookies test site provided by @cmbuckley /for those that missed it in his answer like me; worth scrolling up and upvoting/:
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^
means beginning of string and $
means end of string, and [0-9a-z]+
means one or more of character from 0
to 9
OR from a
to z
.
More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")
My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
How could you do that? You need a variable or field of type T where you can store the object after the cast, but how can you have such a variable or field if you know T only at runtime? So, no, it's not possible.
Type type = GetSomeType();
Object @object = GetSomeObject();
??? xyz = @object.CastTo(type); // How would you declare the variable?
xyz.??? // What methods, properties, or fields are valid here?
Vanilla JS implementation:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
Edit 2: Release 1.15.2 of the body parser module introduces raw mode, which returns the body as a Buffer. By default, it also automatically handles deflate and gzip decompression. Example usage:
var bodyParser = require('body-parser');
app.use(bodyParser.raw(options));
app.get(path, function(req, res) {
// req.body is a Buffer object
});
By default, the options
object has the following default options:
var options = {
inflate: true,
limit: '100kb',
type: 'application/octet-stream'
};
If you want your raw parser to parse other MIME types other than application/octet-stream
, you will need to change it here. It will also support wildcard matching such as */*
or */application
.
Note: The following answer is for versions before Express 4, where middleware was still bundled with the framework. The modern equivalent is the body-parser module, which must be installed separately.
The rawBody
property in Express was once available, but removed since version 1.5.1. To get the raw request body, you have to put in some middleware before using the bodyParser. You can also read a GitHub discussion about it here.
app.use(function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
next();
});
});
app.use(express.bodyParser());
That middleware will read from the actual data stream, and store it in the rawBody
property of the request. You can then access the raw body like this:
app.post('/', function(req, res) {
// do something with req.rawBody
// use req.body for the parsed body
});
Edit: It seems that this method and bodyParser refuse to coexist, because one will consume the request stream before the other, leading to whichever one is second to never fire end
, thus never calling next()
, and hanging your application.
The simplest solution would most likely be to modify the source of bodyParser, which you would find on line 57 of Connect's JSON parser. This is what the modified version would look like.
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function() {
req.rawBody = buf;
var first = buf.trim()[0];
...
});
You would find the file at this location:
/node_modules/express/node_modules/connect/lib/middleware/json.js
.
Posting modified function for own reference. This example inserts a selected item from <select>
object and puts the caret between the tags:
//Inserts a choicebox selected element into target by id
function insertTag(choicebox,id) {
var ta=document.getElementById(id)
ta.focus()
var ss=ta.selectionStart
var se=ta.selectionEnd
ta.value=ta.value.substring(0,ss)+'<'+choicebox.value+'>'+'</'+choicebox.value+'>'+ta.value.substring(se,ta.value.length)
ta.setSelectionRange(ss+choicebox.value.length+2,ss+choicebox.value.length+2)
}
You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
You can use the forName
method of Class
:
Class cls = Class.forName(clsName);
Object obj = cls.newInstance();
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
No one of the previous answers (which all are correct) was suited to my situation: I don't use the async
parameter in jQuery.ajax()
and I don't include a script tag as part of the content that was being returned like:
<div>
SOME CONTENT HERE
</div>
<script src="/scripts/script.js"></script>
My situation is that I am calling two AJAX requests consecutively with the aim to update two divs at the same time:
function f1() {
$.ajax(...); // XMLHTTP request to url_1 and append result to div_1
}
function f2() {
$.ajax(...); // XMLHTTP request to url_2 and append result to div_2
}
function anchor_f1(){
$('a.anchor1').click(function(){
f1();
})
}
function anchor_f2(){
$('a.anchor2').click(function(){
f2();
});
}
// the listener of anchor 3 the source of problem
function anchor_problem(){
$('a.anchor3').click(function(){
f1();
f2();
});
}
anchor_f1();
anchor_f2();
anchor_problem();
When I click on a.anchor3
, it raises the warning flag.I resolved the issue by replacing f2 invoking by click()
function:
function anchor_problem(){
$('a.anchor_problem').click(function(){
f1();
$('a.anchor_f2').click();
});
}
Probably this information will help. I was on Ubuntu 18.04 and when I tried to install Krita, using the ppa method, I got this error:
This application failed to start because it could not find or load the Qt platform plugin "xcb" in "".
Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.
Reinstalling the application may fix this problem.
Aborted
I tried all the solutions that I found in this thread and other webs without any success.
Finally, I found a post where the author mention that is possible to activate the debugging tool of qt5 using this simple command:
export QT_DEBUG_PLUGINS=1
After adding this command I run again krita I got the same error, however this time I knew the cause of that error.
libxcb-xinerama.so.0: cannot open shared object file: No such file or directory.
This error prevents to the "xcb" to load properly. So, the solution will be install the `libxcb-xinerama.so.0" right? However, when I run the command:
sudo apt install libxcb-xinerama
The lib was already installed. Now what Teo? Well, then I used an old trick :) Yeah, that one --reinstall
sudo apt install --reinstall libxcb-xinerama
TLDR: This last command solved my problem.
String someString = "" + c;
char c = someString.charAt(0);
You need to make a class library and not a Console Application. The console application is translated into an .exe
whereas the class library will then be compiled into a dll
which you can reference in your windows project.
What the if
says:
Whether I'm true or not, always check other conditions too.
What the else if
says:
Only check other conditions if i wasn't true.
Recommend to use LINQPad related nuget
package, then you can use exceptionInstance.Dump()
.
LINQPad.Runtime
LINQPad
Sample code:
using System;
using LINQPad;
namespace csharp_Dump_test
{
public class Program
{
public static void Main()
{
try
{
dosome();
}
catch (Exception ex)
{
ex.Dump();
}
}
private static void dosome()
{
throw new Exception("Unable.");
}
}
}
LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.
Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.
SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';
However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:
SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';
gets internally converted to something like:
SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
FROM "THEUSER" . "MYTABLE" "ALIAS"
WHERE "ALIAS" . "THISCOL" = 'That Value';
On this page, the Arduino sketch defines a couple of Structs (plus a couple of methods) which are then called in the setup loop and main loop. Simple enough to interpret, even for a barely-literate programmer like me.
A simple way is just...
Number(42).toString(2);
// "101010"
Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.
$(".jq_fileUploader").change(function () {
var fileSize = this.files[0];
var sizeInMb = fileSize.size/1024;
var sizeLimit= 1024*10;
if (sizeInMb > sizeLimit) {
}
else {
}
});
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.
With Android 8.0 using Custom Fonts in Application became easy with downloadable fonts
.
We can add fonts directly to the res/font/ folder
in the project folder, and in doing so, the fonts become automatically available in Android Studio.
Now set fontFamily
attribute to list of fonts or click on more and select font of your choice. This will add tools:fontFamily="@font/your_font_file"
line to your TextView.
This will Automatically generate few files.
1. In values folder it will create fonts_certs.xml
.
2. In Manifest it will add this lines:
<meta-data
android:name="preloaded_fonts"
android:resource="@array/preloaded_fonts" />
3.
preloaded_fonts.xml
<resources>
<array name="preloaded_fonts" translatable="false">
<item>@font/open_sans_regular</item>
<item>@font/open_sans_semibold</item>
</array>
</resources>
There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.
Ipaper::geom_boxplot2 is just what you want.
# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)
I'm also having the exact same problem with both /usr/local/bin and /etc/sudoers on OSX Snow lepard.Even when i logged in as admin and tried to change the permissions via the terminal, it still says "Operation not permitted". And i did the following to get the permission of these folders.
From the terminal, I accessed /etc/sudoers file and using pico editor i added the following code: username ALL=(ALL) ALL Replace "username" with your MAC OS account name
I'm not sure how much of your "slowness" will be due to the loop you're doing to find entries with particular attribute values, but you can remove this loop by being more specific with your filter. Try this page for some guidance ... Search Filter Syntax
<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>
You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):
For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:
{{true?true:false}}
It is also interesting to compare the file of the current working revision with the same file of another revision.
You can do as follows:
$ svn diff -r34 file
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid
The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb")
. Returning a promise from an onFulfilled()
handler kicks off promise resolution. That's how promise chaining works.
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
this
is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.
super
allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.
For those who are using <select multiple>
(combobox; no dropdown), this worked for me:
<select size=1 disabled multiple>
<option hidden selected></option>
<option>My Option</option>
</select>
_x000D_
I used Joseph Johnson created AndroidBug5497Workaround class but getting black space between softkeyboard and the view. I referred this link Greg Ennis. After doing some changes to the above this is my final working code.
public class SignUpActivity extends Activity {
private RelativeLayout rlRootView; // this is my root layout
private View rootView;
private ViewGroup contentContainer;
private ViewTreeObserver viewTreeObserver;
private ViewTreeObserver.OnGlobalLayoutListener listener;
private Rect contentAreaOfWindowBounds = new Rect();
private FrameLayout.LayoutParams rootViewLayout;
private int usableHeightPrevious = 0;
private View mDecorView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mDecorView = getWindow().getDecorView();
contentContainer =
(ViewGroup) this.findViewById(android.R.id.content);
listener = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
};
rootView = contentContainer.getChildAt(0);
rootViewLayout = (FrameLayout.LayoutParams)
rootView.getLayoutParams();
rlRootView = (RelativeLayout) findViewById(R.id.rlRootView);
rlRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = rlRootView.getRootView().getHeight() - rlRootView.getHeight();
if (heightDiff > Util.dpToPx(SignUpActivity.this, 200)) {
// if more than 200 dp, it's probably a keyboard...
// Logger.info("Soft Key Board ", "Key board is open");
} else {
Logger.info("Soft Key Board ", "Key board is CLOSED");
hideSystemUI();
}
}
});
}
// This snippet hides the system bars.
protected void hideSystemUI() {
// Set the IMMERSIVE flag.
// Set the content to appear under the system bars so that the
content
// doesn't resize when the system bars hide and show.
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
@Override
protected void onPause() {
super.onPause();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnGlobalLayoutListener(listener);
}
}
@Override
protected void onResume() {
super.onResume();
if (viewTreeObserver == null || !viewTreeObserver.isAlive()) {
viewTreeObserver = rootView.getViewTreeObserver();
}
viewTreeObserver.addOnGlobalLayoutListener(listener);
}
@Override
protected void onDestroy() {
super.onDestroy();
rootView = null;
contentContainer = null;
viewTreeObserver = null;
}
private void possiblyResizeChildOfContent() {
contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
int usableHeightNow = contentAreaOfWindowBounds.height();
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow;
rootView.layout(contentAreaOfWindowBounds.left,
contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
rootView.requestLayout();
usableHeightPrevious = usableHeightNow;
} else {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
}
}
Most modern browsers have a console in their developer tools, useful for this sort of debugging.
console.log(myvar);
Then you will get a nicely mapped out interface of the object/whatever in the console.
Check out the console
documentation for more details.
I too had a similar problem, some images were very light and some dark, so the arrows didn't always show up clearly so I took a more simplistic approach.
In the modal-body section I just removed the following lines:
<!-- Left and right controls -->
<a class="carousel-control-prev" href="#id" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#id" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
and inserted the following into the modal-header section
<!-- Left and right controls -->
<a href="#gamespandp" data-slide="prev" class="btn btn-outline-secondary btn-sm">❮</a>
<a href="#gamespandp" data-slide="next" class="btn btn-outline-secondary btn-sm">❯</a>
The indicators can now be clearly seen, no adding extra icons or messing with style sheets, although you could style them however you wanted!
See this demo image:
[
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
<?php
$time = '21:32:32';
$seconds = 0;
$parts = explode(':', $time);
if (count($parts) > 2) {
$seconds += $parts[0] * 3600;
}
$seconds += $parts[1] * 60;
$seconds += $parts[2];
JSONArray
has a constructor which takes a String
source (presumed to be an array).
So something like this
JSONArray array = new JSONArray(yourJSONArrayAsString);
For UTF 8 Conversion and Currency Symbol Export Use this:
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
window.location.href = uri + base64(format(template, ctx))
}
})()
i had the same problem with my jar the solution
Manifest-Version: 1.0
Sealed: true
Class-Path: . lib/jarX1.jar lib/jarX2.jar lib/jarX3.jar
Main-Class: com.MainClass
select export all outpout folders for checked project
This worked for me :)
You would use the Console class
char[] password = console.readPassword("Enter password");
Arrays.fill(password, ' ');
By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.
If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained
solution one: Change the version of apache tomcat (latest one is preferred) (manual process).
solution two: Install latest eclipse IDE and configure the apache tomcat server (internally automatic process i,e eclipse handles the configuration part).
After successful procedure of automatic process, manual process shall be working good.
I am using Visual Studio Code 1.38.1 on windows 10 machine.
Tried the below steps:
exit()
PS C:\Users\username> Cls
PS C:\Users\username>python
Please use the below mentioned URL to encrypt string using AES excryption with
key and IV values.
java.io.NotSerializableException
can occur when you serialize an inner class instance because:
serializing such an inner class instance will result in serialization of its associated outer class instance as well
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged
Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108
to
rcode = pip.main(['install', '-r', req_path, '--quiet'])
do
rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´
I ended up leaving the common properties from the SELECT queries and making a second SELECT query later on in the page. I used a php IF command to call for different scripts depending on the first SELECT query, the scripts contained the second SELECT query.
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
I am assuming that if you are running a 64 bit system with a 32 bit database and trying to run a 64 bit console, the following packages need to be installed on the machine.
Note: The order seems to matter - so if you have anything installed already, uninstall and follow the steps above.
This add-in claims to have the functionality that I believe you seek:
I had a similar problem and for my AspNetCore 3.1 application the other answers to this question were not working. I found that configuring a named HttpClient in my Startup.cs
and using header propagation of the Cookie header worked perfectly. It also avoids all the concerns about proper disposition of your handler and client. Note if propagation of the request cookies is not what you need (sorry Op) you can set your own cookies when configuring the client factory.
IServiceCollection
services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
options.Headers.Add("Cookie");
});
IApplicationBuilder
builder.UseHeaderPropagation();
IHttpClientFactory
into your controller or middleware.using var client = clientFactory.CreateClient("MyNamedClient");
I prefer to use java.util.Scanner
:
try {
Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.next());
}
scanner.close();
String result = sb.toString();
} catch (IOException e) {}
I solved this issue by offing all of advantage features of my graphics card in its settings(Nvidaa type). It started to throw such hanging error less a lot. But finally I found a simplier way: In avd manager you need to put less resolution for the avd. Say, 400x800. Then I reenabled graphics card features again and now it runs all ok. (I suspect my graphics card or cpu are weaker than needed. )