Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
Before importing just make sure you have max_allowed_pack value set some thing large else you will get an error: Error 2006 MySQL server gone away.
Then try the command: mysql -u root -p database_name < file.sql
Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.
see there: https://download.mono-project.com/archive/4.3.2/windows-installer/
Just check for it before you pass to your function. So you would pass:
thing.foo ? thing.foo.bar : undefined
Here is a little BASH function you can add to your .bashrc or .profile on a UNIX based system. Once added and the shell is either restarted or the file is reloaded via a call to source ~/.profile
or source ~/.bashrc
.
function gitToBare() {
if [ -d ".git" ]; then
DIR="`pwd`"
mv .git ..
rm -fr *
mv ../.git .
mv .git/* .
rmdir .git
git config --bool core.bare true
cd ..
mv "${DIR}" "${DIR}.git"
printf "[\x1b[32mSUCCESS\x1b[0m] Git repository converted to "
printf "bare and renamed to\n ${DIR}.git\n"
cd "${DIR}.git"
else
printf "[\x1b[31mFAILURE\x1b[0m] Cannot find a .git directory\n"
fi
}
Once called within a directory containing a .git directory, it will make the appropriate changes to convert the repository. If there is no .git directory present when called, a FAILURE message will appear and no file system changes will happen.
Maybe you are asking for:
Character.toChars(65) // returns ['A']
More info: Character.toChars(int codePoint)
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
I had the same issue recently and ended up creating a NuGet package for this.
This implements a standard heap-based priority queue. It also has all the usual niceties of the BCL collections: ICollection<T>
and IReadOnlyCollection<T>
implementation, custom IComparer<T>
support, ability to specify an initial capacity, and a DebuggerTypeProxy
to make the collection easier to work with in the debugger.
There is also an Inline version of the package which just installs a single .cs file into your project (useful if you want to avoid taking externally-visible dependencies).
More information is available on the github page.
The MOD
keyword only exists in the DAX
language (tabular dimensional queries), not TSQL
Use %
instead.
Ref: Modulo
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
You can view which modules (compiled in) are available via terminal through php -m
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):
During my form/model load :
$.ajax({
type: "POST",
...
success: function (data) {
selectCountries(fixedEncodeURI(data.countries));
}
Call to select data for Select2:
var countrySelect = $('.select_country');
function selectCountries(countries)
{
if (countries) {
$.ajax({
type: 'GET',
url: "/regions/getCountries/",
data: $.param({ 'idsSelected': countries }, true),
}).then(function (data) {
// create the option and append to Select2
$.each(data, function (index, value) {
var option = new Option(value.text, value.id, true, true);
countrySelect.append(option).trigger('change');
console.log(option);
});
// manually trigger the `select2:select` event
countrySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
}
and if you may be having issues with encoding you may change as your requirement:
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");
}
Removing workbench.xmi under workspace/.metadata/.plugins/org.eclipse.e4.workbench/ worked for me. It did not remove the existing projects.
The best way is:
for (vector<my_class>::reverse_iterator i = my_vector.rbegin();
i != my_vector.rend(); ++i ) {
}
rbegin()
/rend()
were especially designed for that purpose. (And yes, incrementing a reverse_interator
moves it backward.)
Now, in theory, your method (using begin()
/end()
& --i
) would work, std::vector
's iterator being bidirectional, but remember, end()
isn't the last element — it's one beyond the last element, so you'd have to decrement first, and you are done when you reach begin()
— but you still have to do your processing.
vector<my_class>::iterator i = my_vector.end();
while (i != my_vector.begin())
{
--i;
/*do stuff */
}
UPDATE: I was apparently too aggressive in re-writing the for()
loop into a while()
loop. (The important part is that the --i
is at the beginning.)
I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle
file as following:
rootProject.name='YourNewName'
This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.
If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....
$output = '';
foreach ($list as $row) {
$output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}
Or from a list of objects...
foreach ($list as $obj) {
$output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}
Then you can output the string as desired.
The Oracle JDeveloper 11g built-in viewer is in my view superior to the one available for Eclipse (which, in addition to other unfavourable comparison points I could only get to install for Indigo but not for Juno). If I am not mistaken Oracle makes the JDeveloper available for free (only requires registration at the OTN).
No. We cannot alter the constraint, only thing we can do is drop and recreate it
ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]
Foreign Key Constraint
Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade
Primary Key constraint
Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)
Without the need of a method:
// html element, will display'active' class if showMobile is true
//clicking on the elment will toggle showMobileMenu to true and false alternatively
<div id="mobile-toggle"
:class="{ active: showMobileMenu }"
@click="showMobileMenu = !showMobileMenu">
</div>
//in your vue.js app
data: {
showMobileMenu: false
}
You can combine multiple selectors with a comma:
$('#Create .myClass,#Edit .myClass').plugin({options here});
Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.
To drop all columns with values 0 in any row:
new_df = df[df.loc[:]!=0].dropna()
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
The answer given by minrk (included for completeness) is good, but there is another way that I like even more.
You can also render an entire cell as LaTeX
by typing %%latex
as the first line in a text cell. This is usefull if you
minrk's answer:
IPython notebook uses MathJax to render LaTeX inside html/markdown. Just put your LaTeX math inside
$$
.$$c = \sqrt{a^2 + b^2}$$
Or you can display LaTeX / Math output from Python, as seen towards the end of the notebook tour:
from IPython.display import display, Math, Latex display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
Addition to @jwize's answer
Because angular.element(document).injector()
was giving error injector is not defined
So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.
function compileAngularElement( elSelector) {
var elSelector = (typeof elSelector == 'string') ? elSelector : null ;
// The new element to be added
if (elSelector != null ) {
var $div = $( elSelector );
// The parent of the new element
var $target = $("[ng-app]");
angular.element($target).injector().invoke(['$compile', function ($compile) {
var $scope = angular.element($target).scope();
$compile($div)($scope);
// Finally, refresh the watch expressions in the new element
$scope.$apply();
}]);
}
}
use it by passing just new element's selector. like this
compileAngularElement( '.user' ) ;
You need to convert the string to date using the to_date()
function
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');
OR
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');
This will work only if OrderDate
is stored in Date format
. If it is Varchar
you should apply to_date()
func on that column also like
SELECT * FROM OrderArchive
WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');
Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)
//using statements
using System;
using System.ComponentModel.DataAnnotations; //needed for Display annotation
using System.ComponentModel; //needed for DisplayName annotation
public class Whatever
{
//Property
[Display(Name ="Release Date")]
public DateTime ReleaseDate { get; set; }
}
//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)
I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__
method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__
method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
".
Thus whenever you define a function with the shorthand def funcname(parameters):
you are really just creating an object with a method __call__
and the shorthand for __call__
is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
Source code of CSS/JS we usually minified/compress. Now if we want to debug those minified files then we have to add following line at the end of minified file
/*# sourceMappingURL=bootstrap.min.css.map */
This tells compiler where is source file actually mapped.
In the case of JS its make sense
but in the case of CSS, its actually debugging of SCSS.
To Remove Warning: remove /*# sourceMappingURL=bootstrap.min.css.map */ from the end of minified file
, .
The best way to align a div in center both horizontally and vertically will be
HTML
<div></div>
CSS:
div {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blue;
}
In Python 3.7 a new keyword argument capture_output
was introduced for subprocess.run
. Enabling the short and simple:
import subprocess
p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
assert p.stdout == 'hello world!\n'
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
This worked like charm:
pip3 install git+https://github.com/deepak1725/fabric8-analytics-worker.git@develop
Where :
develop: Branch
fabric8-analytics-worker.git : Repo
deepak1725: user
You can use the following command:
git checkout HEAD -- my-file.txt
... which will update both the working copy of my-file.txt
and its state in the index with that from HEAD.
--
basically means: treat every argument after this point as a file name. More details in this answer. Thanks to VonC for pointing this out.
I had the same problem. I had changes in the remote and it was still showing "Already up to date". Recloning the repository fixed the problem for me.
NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy
, you can compute this with the ppf
method of the scipy.stats.norm
object. The acronym ppf
stands for percent point function, which is another name for the quantile function.
In [20]: from scipy.stats import norm
In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722
Check that it is the inverse of the CDF:
In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996
By default, norm.ppf
uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc
and scale
arguments, respectively.
In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945
If you look at the source code for scipy.stats.norm
, you'll find that the ppf
method ultimately calls scipy.special.ndtri
. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:
In [43]: from scipy.special import ndtri
In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722
lets put it in this way:
actually Modulus operator does the same division but it does not care about the answer , it DOES CARE ABOUT reminder for example if you divide 7 to 5 ,
so , lets me take you through a simple example:
think 5 is a block, then for example we going to have 3 blocks in 15 (WITH Nothing Left) , but when that loginc comes to this kinda numbers {1,3,5,7,9,11,...} , here is where the Modulus comes out , so take that logic that i said before and apply it for 7 , so the answer gonna be that we have 1 block of 5 in 7 => with 2 reminds in our hand! that is the modulus!!!
but you were asking about 5 % 7 , right ?
so take the logic that i said , how many 7 blocks do we have in 5 ???? 0
so the modulus returns 0...
that's it ...
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim
directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
You can use opendir and readdir to read directory entries and unlink to delete them.
That is the parent folder of bin which contains tomcat.exe file:
CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'
CATALINA_BASE
is the same as CATALINA_HOME
.
You can get to SIZES
by means of self.SIZES
(in an instance method) or cls.SIZES
(in a class method).
In any case, you will have to be explicit about where to find SIZES
. An alternative is to put SIZES
in the module containing the classes, but then you need to define all classes in a single module.
If you want just A-Z:
randomAZ(n: number): string {
return Array(n)
.fill(null)
.map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
.map(a => String.fromCharCode(a))
.join('')
}
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
You can take keys or values per index:
int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be < =_dict.Count - 1
This worked for me, converts to nested JSON to easy to read YAML
string JSONDeserialized {get; set;}
public int indentLevel;
private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
{
bool bSuccess = false;
indentLevel++;
foreach (string strKey in dict.Keys)
{
string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
JSONDeserialized+="\r\n" + strOutput;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
JSONDeserialized += strOutput + ",";
}
else if (oChild is Dictionary<string, object>)
{
JSONDictionarytoYAML((Dictionary<string, object>)oChild);
JSONDeserialized += "\r\n";
}
}
}
else
{
strOutput = o.ToString();
JSONDeserialized += strOutput;
}
}
indentLevel--;
return bSuccess;
}
usage
Dictionary<string, object> JSONDic = new Dictionary<string, object>();
JavaScriptSerializer js = new JavaScriptSerializer();
try {
JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
JSONDeserialized = "";
indentLevel = 0;
DisplayDictionary(JSONDic);
return JSONDeserialized;
}
catch (Exception)
{
return "Could not parse input JSON string";
}
How about the below solution? It worked for me. Try this:
.modal .modal-body {
max-height: 420px;
overflow-y: auto;
}
Details:
overflow-y: auto;
or overflow: auto;
from .modal class (important)max-height: 400px;
from .modal
class (important)max-height: 400px;
to .modal .modal-body (or what ever, can be 420px
or less, but would not go more than 450px
)overflow-y: auto;
to .modal .modal-body
Done, only body will scroll.
Word Break will mimic some of the intent
input[type=text] {
word-wrap: break-word;
word-break: break-all;
height: 80px;
}
_x000D_
<input type="text" value="The quick brown fox jumped over the lazy dog" />
_x000D_
As a workaround, this solution lost its effectiveness on some browsers. Please check the demo: http://cssdesk.com/dbCSQ
Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case
So
var result = text.split(' ').join('')
operates faster than
var result = text.replace(/\s+/g, '')
On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.
On the other hand, \s+
handles wider variety of space characters. Among with \n
and \t
, it also matches \u00a0
character, and that is what
is turned in, when getting text using textDomNode.nodeValue
.
So I think that conclusion in here can be made as follows: if you only need to replace spaces ' '
, use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
Nothing as useful as this: Common Data Structure Operations:
For me turning on and off the setting on
iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard
proved to fix the issue on simulators.
This works for me:
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {
//...
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
});
//...
}
//...
}
If you only need to detect the presence of duplicates (instead of listing them, which is what the OP wanted), just convert them into both a List and Set, then compare the sizes:
List<Integer> list = ...;
Set<Integer> set = new HashSet<>(list);
if (list.size() != set.size()) {
// duplicates detected
}
I like this approach because it has less places for mistakes.
I have done with easy way:
Please check screen shot for the same.
CustomProgressBarActivity.java:
public class CustomProgressBarActivity extends AppCompatActivity {
private TextView txtProgress;
private ProgressBar progressBar;
private int pStatus = 0;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_progressbar);
txtProgress = (TextView) findViewById(R.id.txtProgress);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
new Thread(new Runnable() {
@Override
public void run() {
while (pStatus <= 100) {
handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(pStatus);
txtProgress.setText(pStatus + " %");
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
}
}
activity_custom_progressbar.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.skholingua.android.custom_progressbar_circular.MainActivity" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:indeterminate="false"
android:max="100"
android:progress="0"
android:progressDrawable="@drawable/custom_progressbar_drawable"
android:secondaryProgress="0" />
<TextView
android:id="@+id/txtProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/progressBar"
android:layout_centerInParent="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</RelativeLayout>
custom_progressbar_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-90"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270" >
<shape
android:shape="ring"
android:useLevel="false" >
<gradient
android:centerY="0.5"
android:endColor="#FA5858"
android:startColor="#0099CC"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Hope this will help you.
I got it working with this code.
using iTextSharp.text;
using iTextSharp.text.pdf;
public FileStreamResult pdf()
{
MemoryStream workStream = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, workStream).CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
document.Add(new Paragraph(DateTime.Now.ToString()));
document.Close();
byte[] byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return new FileStreamResult(workStream, "application/pdf");
}
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
Some handy quick functions (if you're not using Boost):
template<typename T>
std::string ToString(const T& v)
{
std::ostringstream ss;
ss << v;
return ss.str();
}
template<typename T>
T FromString(const std::string& str)
{
std::istringstream ss(str);
T ret;
ss >> ret;
return ret;
}
Example:
int i = FromString<int>(s);
std::string str = ToString(i);
Works for any streamable types (floats etc). You'll need to #include <sstream>
and possibly also #include <string>
.
select sequence_name, (xpath('/row/last_value/text()', xml_count))[1]::text::int as last_value
from (
select sequence_schema,
sequence_name,
query_to_xml(format('select last_value from %I.%I', sequence_schema, sequence_name), false, true, '') as xml_count
from information_schema.sequences
where sequence_schema = 'public'
) new_table order by last_value desc;
You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:
rsq <- function (x, y) cor(x, y) ^ 2
Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared
).
Basically we fit a linear regression of y
over x
, and compute the ratio of regression sum of squares to total sum of squares.
lemma 1: a regression y ~ x
is equivalent to y - mean(y) ~ x - mean(x)
lemma 2: beta = cov(x, y) / var(x)
lemma 3: R.square = cor(x, y) ^ 2
R squared between two arbitrary vectors x
and y
(of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a
and y + b
are identical for any constant shift a
and b
. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:
I agree with 42-'s comment:
The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.
R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.
Here is very extreme example:
preds <- 1:4/4
actual <- 1:4
The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds
is a good prediction on actual
??
Thanks for your comments 1, 2 and your answer of details.
You probably misunderstood the procedure. Given two vectors x
and y
, we first fit a regression line y ~ x
then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.
As you demonstrated, this is just one way for computing R squared:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25
But there is another:
regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75
Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).
preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375
I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.
This gives almost what you need:
git log --stat --oneline
Commit id + short one line still remains, followed by list of changed files by that commit.
I had an old Excel database with "human-readable" dates, like 2010.03.28 20:12:30 Theese dates were in UTC+1 (CET) and needed to convert it to epoch time.
I used the =(A4-DATE(1970;1;1))*86400-3600 formula to convert the dates to epoch time from the A column to B column values. Check your timezone offset and make a math with it. 1 hour is 3600 seconds.
The only thing why i write here an anwser, you can see that this topic is more than 5 years old is that i use the new Excel versions and also red posts in this topic, but they're incorrect. The DATE(1970;1;1). Here the 1970 and the January needs to be separated with ; and not with ,
If you're also experiencing this issue, hope it helps you. Have a nice day :)
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.
Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:
And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.
This can happen if any part of your highlighted method or property is attempting to access a property or method with the incorrect type.
Here is a troubleshooting checklist:
enumerated()
)A Strategy
For example, lets say you are running compactMap
on an array of custom Types. In the closure you are passing to the compactMap
method, you initialize and return another custom struct. When you get this error, it is difficult to tell which part of your code is offending.
By this point, you may come to a realization, such as, instead of the property you thought you wanted to assign actually had a property on it that had the actual value you wanted to pass.
The new way to do it is to use enabledBorder
like this:
new TextField(
decoration: new InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Colors.grey, width: 0.0),
),
focusedBorder: ...
border: ...
),
)
@David Titarenco nailed it here, but let me at least clean it up a bit to make it look nice, and show both min()
and max()
together to make copying and pasting from here easier. :)
Update 25 Apr. 2020: I've also added a Section 3 to show how this would be done with C++ templates too, as a valuable comparison for those learning both C and C++, or transitioning from one to the other. I've done my best to be thorough and factual and correct to make this answer a canonical reference I can come back to again and again, and I hope you find it as useful as I do.
This technique is commonly used, well-respected by those who know how to use it properly, the "de facto" way of doing things, and fine to use if used properly, but buggy (think: double-evaluation side effect) if you ever pass expressions including variable assignment in to compare:
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
This technique avoids the above "double-evaluation" side effects and bugs, and is therefore considered the superior, safer, and "more modern" GCC C way to do this. Expect it to work with both the gcc and clang compilers, since clang is, by design, gcc-compatible (see the clang note at the bottom of this answer).
BUT: DO watch out for "variable shadowing" effects still, as statement expressions are apparently inlined and therefore do NOT have their own local variable scope!
#define max(a,b) \
({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; \
})
#define min(a,b) \
({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; \
})
Note that in gcc statement expressions, the last expression in the code block is what is "returned" from the expression, as though it was returned from a function. GCC's documentation says it this way:
The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)
C++ Note: if using C++, templates are probably recommended for this type of construct instead, but I personally dislike templates and would probably use one of the above constructs in C++ anyway, as I frequently use and prefer C styles in embedded C++ as well.
This section added 25 Apr. 2020:
I've been doing a ton of C++ the past few months, and the pressure to prefer templates over macros, where able, in the C++ community is quite strong. As a result, I've been getting better at using templates, and want to put in the C++ template versions here for completeness and to make this a more canonical and thorough answer.
Here's what basic function template versions of max()
and min()
might look like in C++:
template <typename T>
T max(T a, T b)
{
return a > b ? a : b;
}
template <typename T>
T min(T a, T b)
{
return a < b ? a : b;
}
Do additional reading about C++ templates here: Wikipedia: Template (C++).
However, both max()
and min()
are already part of the C++ standard library, in the <algorithm>
header (#include <algorithm>
). In the C++ standard library they are defined slightly differently than I have them above. The default prototypes for std::max<>()
and std::min<>()
, for instance, in C++14, looking at their prototypes in the cplusplus.com links just above, are:
template <class T>
constexpr const T& max(const T& a, const T& b);
template <class T>
constexpr const T& min(const T& a, const T& b);
Note that the keyword typename
is an alias to class
(so their usage is identical whether you say <typename T>
or <class T>
), since it was later acknowledged after the invention of C++ templates, that the template type might be a regular type (int
, float
, etc.) instead of only a class type.
Here you can see that both of the input types, as well as the return type, are const T&
, which means "constant reference to type T
". This means the input parameters and return value are passed by reference instead of passed by value. This is like passing by pointers, and is more efficient for large types, such as class objects. The constexpr
part of the function modifies the function itself and indicates that the function must be capable of being evaluated at compile-time (at least if provided constexpr
input parameters), but if it cannot be evaluated at compile-time, then it defaults back to a run-time evaluation, like any other normal function.
The compile-time aspect of a constexpr
C++ function makes it kind-of C-macro-like, in that if compile-time evaluation is possible for a constexpr
function, it will be done at compile-time, same as a MIN()
or MAX()
macro substitution could possibly be fully evaluated at compile-time in C or C++ too. For additional references for this C++ template info, see below.
Clang note from Wikipedia:
[Clang] is designed to act as a drop-in replacement for the GNU Compiler Collection (GCC), supporting most of its compilation flags and unofficial language extensions.
It works for me thank you. I had this issue when I installed .Net Framework 4.7.1, somehow DbProviderFactories
settings under System.Data
in machine config got wiped-out. It started working after adding the necessary configuration settings as shown below DataProviderFactories
<system.data>
<DbProviderFactories>
<add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
Try this
$("[id*='type']").click(
function () {
var isCheckboxChecked = this.checked;
$("[id*='type']").attr('checked', false);
this.checked = isCheckboxChecked;
});
To make it even more generic you can also find checkboxes by the common class implemented on them.
Modified...
It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.
Perhaps you could try ([^ ]+) .*
, which should give you everything to the first blank in your first group.
Check the domain's web server for http://www.<domain>.com
configuration for X-Frame-Options
It is a security feature designed to prevent clickJacking attacks,
Technically the evil has an iframe
with the source to the victim page.
<html>
<iframe src='victim_domain.com'/>
<input id="username" type="text" style="display: none;"/>
<input id="password" type="text" style="display: none;"/>
<script>
//some JS code that click jacking the user username and input from inside the iframe...
<script/>
<html>
If you want to prevent web server request to be rendered within an iframe
add the x-frame-options
X-Frame-Options DENY
The options are:
This is IIS config example:
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
If the web server activated the security feature it may cause a client-side SecurityError as it should.
To revert a migration:
python manage.py migrate <APP_NAME> <MIGRATION_NUMBER_PREFIX>
MIGRATION_NUMBER_PREFIX
is the number prefix of the migration you want to revert to, for instance 0001
to go to 0001_initial.py
migration. then you can delete that migration.
You can use
zero
as your migration number to revert all migrations of an app.
For Leaflet, I'm using
map.setView(markersLayer.getBounds().getCenter());
You can use a jQuery plugin (breedjs) that provides sort, filter and pagination:
HTML:
<table>
<thead>
<tr>
<th sort='name'>Name</th>
<th>Phone</th>
<th sort='city'>City</th>
<th>Speciality</th>
</tr>
</thead>
<tbody>
<tr b-scope="people" b-loop="person in people">
<td b-sort="name">{{person.name}}</td>
<td>{{person.phone}}</td>
<td b-sort="city">{{person.city}}</td>
<td>{{person.speciality}}</td>
</tr>
</tbody>
</table>
JS:
$(function(){
var data = {
people: [
{name: 'c', phone: 123, city: 'b', speciality: 'a'},
{name: 'b', phone: 345, city: 'a', speciality: 'c'},
{name: 'a', phone: 234, city: 'c', speciality: 'b'},
]
};
breed.run({
scope: 'people',
input: data
});
$("th[sort]").click(function(){
breed.sort({
scope: 'people',
selector: $(this).attr('sort')
});
});
});
I don't remember the specific source, but I am using:
/* Number of Cards by Row based on Viewport */
@media (min-width: 576px) {
.card-deck .card {
min-width: 50.1%; /* 1 Column */
margin-bottom: 12px;
}
}
@media (min-width: 768px) {
.card-deck .card {
min-width: 33.4%; /* 2 Columns */
}
}
@media (min-width: 1200px) {
.card-deck .card {
min-width: 25.1%; /* 3 Columns */
}
}
You may want to tinker with the specific values to fit your needs.
This function will rename an array key, keeping its position, by combining with index searching.
function renameArrKey($arr, $oldKey, $newKey){
if(!isset($arr[$oldKey])) return $arr; // Failsafe
$keys = array_keys($arr);
$keys[array_search($oldKey, $keys)] = $newKey;
$newArr = array_combine($keys, $arr);
return $newArr;
}
Usage:
$arr = renameArrKey($arr, 'old_key', 'new_key');
I prefer Serializable
= no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable
does not matter.
I would also always provide a helper method for a Fragment
or Activity
, this way you always know, what data has to be passed. Here an example for your ListMusicFragment
:
private static final String EXTRA_MUSIC_LIST = "music_list";
public static ListMusicFragment createInstance(List<Music> music) {
ListMusicFragment fragment = new ListMusicFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(EXTRA_MUSIC_LIST, music);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(...) {
...
Bundle bundle = intent.getArguments();
List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
...
}
Sorry to dig an old grave here, but why not just do this?
<div class="form-group">
</div>
It will add a space the height of a normal form element.
It seems about 1 line on a form is roughly 50px (47px on my element I just inspected). This is a horizontal form, with label on left 2col and input on right 10col. So your pixels may vary.
Since mine is basically 50px, I would create a spacer of 50px tall with no margins or padding;
.spacer { margin:0; padding:0; height:50px; }
<div class="spacer"></div>
This is an initialization list. It'll initialize the members before the constructor body is run. Consider
class Foo {
public:
string str;
Foo(string &p)
{
str = p;
};
};
vs
class Foo {
public:
string str;
Foo(string &p): str(p) {};
};
In the first example, str will be initialized by its no-argument constructor
string();
before the body of the Foo constructor. Inside the foo constructor, the
string& operator=( const string& s );
will be called on 'str' as you do str = p;
Wheras in the second example, str will be initialized directly by calling its constructor
string( const string& s );
with 'p' as an argument.
Using pathlib you can get the folder in which the current file is located. __file__
is the pathname of the file from which the module was loaded.
Ref: docs
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
Doc ref: link
If you start the scripts you are executing through cron with:
#!/bin/bash -l
They should pick up your ~/.bash_profile
environment variables
Just wanted to point out something about the solution said above several times:
git config credential.helper store
You can use any command that requires a password after this. You don't have to push. (you can also pull for instance) After that, you won't need to type in your username / password again.
You can also do this by running a single line.
git merge aq master
This is equivalent to
git checkout aq
git merge master
I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: color 0.3s linear;
-webkit-transition: color 0.3s linear;
-moz-transition: color 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the above code!
Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.
CSS
.fancy-link {
color: #333333;
text-decoration: none;
transition: all 0.3s linear;
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
}
.fancy-link:hover {
color: #F44336;
padding-left: 10px;
}
HTML
<a class="fancy-link" href="#">My Link</a>
And here is a JSFIDDLE for the "all" example!
try this:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
and ensure that in php.ini allow_url_fopen is enable
Use PowerShell to do anything smarter for a DOS prompt. Here, I've shown how to batch rename all the files and directories in the current directory that contain spaces by replacing them with _
underscores.
Dir |
Rename-Item -NewName { $_.Name -replace " ","_" }
EDIT :
Optionally, the Where-Object
command can be used to filter out ineligible objects for the successive cmdlet (command-let). The following are some examples to illustrate the flexibility it can afford you:
To skip any document files
Dir |
Where-Object { $_.Name -notmatch "\.(doc|xls|ppt)x?$" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
To process only directories (pre-3.0 version)
Dir |
Where-Object { $_.Mode -match "^d" } |
Rename-Item -NewName { $_.Name -replace " ","_" }
PowerShell v3.0 introduced new Dir
flags. You can also use Dir -Directory
there.
To skip any files already containing an underscore (or some other character)
Dir |
Where-Object { -not $_.Name.Contains("_") } |
Rename-Item -NewName { $_.Name -replace " ","_" }
You should be able to do something like this in your respond_to
block:
respond_to do |format|
format.json
render :partial => "users/show.json"
end
which will render the template in app/views/users/_show.json.erb
.
Here is just another option you couold apply for ASP NET MVC.
Normally you shoud use BaseController
class for each Controller
class.
So inside of it's constructor method do following.
public class BaseController : Controller
{
public BaseController()
{
// get the previous url and store it with view model
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
}
}
And now in ANY view you can do like
<button class="btn btn-success mr-auto" onclick=" window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>
Enjoy!
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:
$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);
echo '<code>';
echo '<pre>';
echo $a;
echo '</pre>';
echo '</code>';
Best way to pass data from child to parent component
child component
handleLanguageCode=()=>(langValue) {
this.props.sendDatatoParent(langValue)
}
Parent
<Parent sendDatatoParent={ data => this.setState({item: data}) } />;
Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080
npm set https-proxy http://username:password@companyProxy:8080
npm config set strict-ssl false -g
NOTES: No special characters in password except @ allowed.
I wrote mine based off of @user261922's post above, slightly modified so you can select all, tab and can handle multiple "number only" fields on the same page.
var prevKey = -1, prevControl = '';
$(document).ready(function () {
$(".OnlyNumbers").keydown(function (event) {
if (!(event.keyCode == 8 // backspace
|| event.keyCode == 9 // tab
|| event.keyCode == 17 // ctrl
|| event.keyCode == 46 // delete
|| (event.keyCode >= 35 && event.keyCode <= 40) // arrow keys/home/end
|| (event.keyCode >= 48 && event.keyCode <= 57) // numbers on keyboard
|| (event.keyCode >= 96 && event.keyCode <= 105) // number on keypad
|| (event.keyCode == 65 && prevKey == 17 && prevControl == event.currentTarget.id)) // ctrl + a, on same control
) {
event.preventDefault(); // Prevent character input
}
else {
prevKey = event.keyCode;
prevControl = event.currentTarget.id;
}
});
});
The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.
try
/usr/lib/mongodb/mongod.exe --dbpath c:data\db
--dbpath (should be followed by the path of your db)
Here is my solution for mac users I think it work for window also:
First go to your Android Studio toolbar
Build > Make Project (while you guys are online let it to download the files) and then
Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then
Run your app that is done it will launch your emulator and configure it then run it!
That is it!!! Happy Coding guys!!!!!!!
In the head section of your html place your custom.css below bootstrap.css.
<link href="bootstrap.min.css" rel="stylesheet">
<link href="custom.css" rel="stylesheet">
Then in custom.css you have to use the exact same selector for the element you want to override. In the case of legend
it just stays legend
in your custom.css because bootstrap hasn't got any selectors more specific.
legend {
display: inline;
width: auto;
padding: 0;
margin: 0;
font-size: medium;
line-height: normal;
color: #000000;
border: 0;
border-bottom: none;
}
But in case of h1
for example you have to take care of the more specific selectors like .jumbotron h1
because
h1 {
line-height: 2;
color: #f00;
}
will not override
.jumbotron h1,
.jumbotron .h1 {
line-height: 1;
color: inherit;
}
Here is a helpfull explantion of specificity of css selectors which you need to understand to know exactly which style rules will apply to an element. http://css-tricks.com/specifics-on-css-specificity/
Everything else is just a matter of copy/paste and edit styles.
As far as I'm aware, you can't declare custom fonts in xml or themes. I usually just make custom classes extending textview that set their own font on instantiation and use those in my layout xml files.
ie:
public class Museo500TextView extends TextView {
public Museo500TextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "path/to/font.ttf"));
}
}
and
<my.package.views.Museo900TextView
android:id="@+id/dialog_error_text_header"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="12sp" />
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
It will replace all new line with break
str = str.replace(/\n/g, '<br>')
If you want to replace all new line with single break line
str = str.replace(/\n*\n/g, '<br>')
Read more about Regex : https://dl.icewarp.com/online_help/203030104.htm this will help you everytime.
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);
You can use the php curl module to make calls to http://liveoutput.com/. This works great in an secure, corporate environment where certain restrictions in the php.ini exists that restrict usage of file_put_contents
.
You can inherit @Input, @Output, @ViewChild, etc. Look at the sample:
@Component({
template: ''
})
export class BaseComponent {
@Input() someInput: any = 'something';
@Output() someOutput: EventEmitter<void> = new EventEmitter<void>();
}
@Component({
selector: 'app-derived',
template: '<div (click)="someOutput.emit()">{{someInput}}</div>',
providers: [
{ provide: BaseComponent, useExisting: DerivedComponent }
]
})
export class DerivedComponent {
}
Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:
With Notepad++, you can show end-of-line characters. It shows CR and LF, instead of "\r" and "\n", but it gets the point across. However, it will still insert the line breaks. But you do get to see the line-ending characters.
To use Notepad++ for this, open the View menu, open the Show Symbols slide out, and select either "Show all characters" or "Show end-of-line characters".
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
The decision to use 1st January 1753 (1753-01-01
) as the minimum date value for a datetime in SQL Server goes back to its Sybase origins.
The significance of the date itself though can be attributed to this man.
Philip Stanhope, 4th Earl of Chesterfield. Who steered the Calendar (New Style) Act 1750 through the British Parliament. This legislated for the adoption of the Gregorian calendar for Britain and its then colonies.
There were some missing days (internet archive link) in the British calendar in 1752 when the adjustment was finally made from the Julian calendar. September 3, 1752 to September 13, 1752 were lost.
Kalen Delaney explained the choice this way
So, with 12 days lost, how can you compute dates? For example, how can you compute the number of days between October 12, 1492, and July 4, 1776? Do you include those missing 12 days? To avoid having to solve this problem, the original Sybase SQL Server developers decided not to allow dates before 1753. You can store earlier dates by using character fields, but you can't use any datetime functions with the earlier dates that you store in character fields.
The choice of 1753 does seem somewhat anglocentric however as many catholic countries in Europe had been using the calendar for 170 years before the British implementation (originally delayed due to opposition by the church). Conversely many countries did not reform their calendars until much later, 1918 in Russia. Indeed the October Revolution of 1917 started on 7 November under the Gregorian calendar.
Both datetime
and the new datetime2
datatype mentioned in Joe's answer do not attempt to account for these local differences and simply use the Gregorian Calendar.
So with the greater range of datetime2
SELECT CONVERT(VARCHAR, DATEADD(DAY,-5,CAST('1752-09-13' AS DATETIME2)),100)
Returns
Sep 8 1752 12:00AM
One final point with the datetime2
data type is that it uses the proleptic Gregorian calendar projected backwards to well before it was actually invented so is of limited use in dealing with historic dates.
This contrasts with other Software implementations such as the Java Gregorian Calendar class which defaults to following the Julian Calendar for dates until October 4, 1582 then jumping to October 15, 1582 in the new Gregorian calendar. It correctly handles the Julian model of leap year before that date and the Gregorian model after that date. The cutover date may be changed by the caller by calling setGregorianChange()
.
A fairly entertaining article discussing some more peculiarities with the adoption of the calendar can be found here.
That syntax is a way of accessing a class member. PHP does not have pointers, but it does have references.
The syntax that you're quoting is basically the same as accessing a member from a pointer to a class in C++ (whereas dot notation is used when it isn't a pointer.)
No such function exists or is possible to write.
The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
The comment left by tiho on Mar 27 '14 at 17:21 deserves to be its own answer:
In order to avoid platform-specific code, use timeit.default_timer()
Instead of using this
DB_HOST=localhost
DB_DATABASE=wdcollect
DB_USERNAME=root
DB_PASSWORD=
USE this
DB_HOST=localhost
DB_DATABASE=wdcollect
DB_USERNAME=root
DB_PASSWORD=''
A bit late to the party but might be valuable to someone with this error..
I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.
The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.
CURRENT_DATE
and CURRENT_TIMESTAMP
return the current date and time in the session time zone.
SYSDATE
and SYSTIMESTAMP
return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS*
and CURRENT_*
functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
My solution is to use ggplot2
. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))
Then use ggplot2
to plot it
library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()
This is saying plot the data in df
, and separate the points by class
.
The plot generated is
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Write a:hover::before
instead of a::before:hover
: example.
We use JavaCSV, it works pretty well
How about
for (int k = 0; k < 10; k = k + 2) {
if (k == 2) {
break;
}
System.out.println(k);
}
The other way is a labelled loop
myloop: for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break myloop;
}
System.out.println(i + " " + j);
}
}
For an even better explanation you can check here
I had such a problem and the answer, although frustrating to find, was solved by doing a search on the offending page for the ".." in the error message. I am using Visual Studio Express and the solution was changing "../../Images/" to "~/Images/" . Hopefully this will help someone.
Following query helped me. Instead of using LIKE
, you can use ~*
.
select id, name from hosts where name ~* 'julia|lena|jack';
you can do this:
<div class="picture1"> </div>
and put this into your css file:
div.picture1 {
width:100px; /*width of your image*/
height:100px; /*height of your image*/
background-image:url('yourimage.file');
margin:0; /* If you want no margin */
padding:0; /*if your want to padding */
}
otherwise, just use them as plain
There are several ways to do this, below are two options:
Option 1 - Right click on the database you want to copy
Choose 'Tasks' > 'Generate scripts'
'Select specific database objects'
Check 'Tables'
Mark 'Save to new query window'
Click 'Advanced'
Set 'Types of data to script' to 'Schema and data'
Next, Next
You can now run the generated query on the new database.
Option 2
Right click on the database you want to copy
'Tasks' > 'Export Data'
Next, Next
Choose the database to copy the tables to
Mark 'Copy data from one or more tables or views'
Choose the tables you want to copy
Finish
Surprised a solution using flexbox hasn't been posted yet.
Here's my solution using display: flex
and a basic use of :after
(thanks to Luggage) to maintain the alignment even with the scrollbar padding the tbody
a bit. This has been verified in Chrome 45, Firefox 39, and MS Edge. It can be modified with prefixed properties to work in IE11, and further in IE10 with a CSS hack and the 2012 flexbox syntax.
Note the table width can be modified; this even works at 100%
width.
The only caveat is that all table cells must have the same width. Below is a clearly contrived example, but this works fine when cell contents vary (table cells all have the same width and word wrapping on, forcing flexbox to keep them the same width regardless of content). Here is an example where cell contents are different.
Just apply the .scroll
class to a table you want scrollable, and make sure it has a thead
:
.scroll {_x000D_
border: 0;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll tr {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.scroll td {_x000D_
padding: 3px;_x000D_
flex: 1 auto;_x000D_
border: 1px solid #aaa;_x000D_
width: 1px;_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.scroll thead tr:after {_x000D_
content: '';_x000D_
overflow-y: scroll;_x000D_
visibility: hidden;_x000D_
height: 0;_x000D_
}_x000D_
_x000D_
.scroll thead th {_x000D_
flex: 1 auto;_x000D_
display: block;_x000D_
border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.scroll tbody {_x000D_
display: block;_x000D_
width: 100%;_x000D_
overflow-y: auto;_x000D_
height: 200px;_x000D_
}
_x000D_
<table class="scroll" width="400px">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Header</th>_x000D_
<th>Header</th>_x000D_
<th>Header</th>_x000D_
<th>Header</th>_x000D_
<th>Header</th>_x000D_
<th>Header</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
<td>Data</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Go to File->Other Settings->Preferences for New Projects->Build, Execution, Deployment->Build Tools->Gradle->Uncheck Offline work option.
Rather than changing ${user}
in eclipse, it is advisable to introduce
-Duser.name=Whateverpleaseyou
in eclipse.ini
which is present in your eclipse folder.
Try this:
declare @procName varchar(500)
declare cur cursor
for SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(p.schema_id) + '].[' + p.NAME + ']'
FROM sys.procedures p
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
exec( @procName )
fetch next from cur into @procName
end
close cur
deallocate cur
checkout
can be use for many case :
1st case : switch between branch in local repository
For instance :
git checkout exists_branch_to_switch
You can also create new branch and switch out in throught this case with -b
git checkout -b new_branch_to_switch
2nd case : restore file from x rev
git checkout rev file_to_restore
...
First I would like to thank Rose who was willing to help us, but your answer could solve the problem on a computer, but in others there was what was done could not always connect gets error 720. After much searching and contact the Microsoft support we can solve. In Device Manager, on the View menu, select to show hidden devices. Made it look for a remote Miniport IP or network monitor that is with warning of problems with the driver icon. In its properties in the details tab check the Key property of the driver. Look for this key in Regedit on Local Machine, make a backup of that key and delete it. Restart your windows. Reopen your device manager and select the miniport that had deleted the record. Activate the option to update the driver and look for the option driver on the computer manually and then use the option to locate the driver from the list available on the computer on the next screen uncheck show compatible hardware. Then you must select the Microsoft Vendor and the driver WAN Miniport the type that is changing, IP or IPV6 L2TP Network Monitor. After upgrading restart the computer.
I know it's a bit laborious but that was the only way that worked on all computers.
Okay. Answer for self hosted wordpress installations - you'll have to find the file yourself. For my WordPres site I use nginx with php7.3-fpm.
Running php -i | grep ini
from console gives me several lines including:
Loaded Configuration File => /etc/php/7.3/cli/php.ini
. This is ini configuration when running php
command from command line, a.k.a. cli.
Then looking around I see there is also a file: /etc/php/7.3/fpm/php.ini
I use FPM service so that is it! I edit it and THEN reload the service to apply my changes using: service php7.3-fpm reload
.
That was it. Now I can upload bigger files to my WordPress. Good luck
The question was raised years ago, with the older version it was a little hard to get...but now this question has a very easy answer.
<div class="btn btn-outline-primary btn-block">Button text here</div>
This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:
SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' -- filter out system tables for diagramming
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
s.Name, t.Name
If you want to separate table space from index space, you need to use AND i.index_id IN (0,1)
for the table space (index_id = 0
is the heap space, index_id = 1
is the size of the clustered index = data pages) and AND i.index_id > 1
for the index-only space
The method you're using to read the http body response returns a byte slice:
func ReadAll(r io.Reader) ([]byte, error)
You can convert []byte
to a string by using
body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH
but it still didn't go.
I checked with python -version
and go to know that it was still taking the anaconda path.
I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH
.
Issue Solved!
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."
To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.
-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading Reflector, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED.
Your code would read:
if (ex.Number == -2)
{
//handle timeout
}
Code to demonstrate failure:
try
{
SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
sql.Open();
SqlCommand cmd = sql.CreateCommand();
cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
cmd.ExecuteNonQuery(); // This line will timeout.
cmd.Dispose();
sql.Close();
}
catch (SqlException ex)
{
if (ex.Number == -2) {
Console.WriteLine ("Timeout occurred");
}
}
here is what worked for me:
Just try decreasing the length of the path. i.e :: Rename all folders that lead to such a file to smallest possible names. Say one letter names. Go on renaming upwards in the folder hierarchy. By this u effectively reduce the path length. Now finally try deleting the file straight away.
I believe the best solution for this, is what I use, and that is a natural css border:
border-right:1px solid;
You might need to take care of padding like:
padding-left: 5px;
padding-right: 5px;
Finally, if you don't want the last li to have that seperating border, give it's last-child "none" in "border-right" like this:
li:last-child{
border-right:none;
}
Good luck :)
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
About the window.location.hash
property:
Return the anchor part of a URL.
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Just apply scroll behaviour to all elements with this one-line code:
*{
scroll-behavior: smooth !important;
}
_x000D_
If you are getting errors even after downloading the newest SDK and Android Studio, here is what I did:
I hope it helps someone so that he won't suffer like I did for these couple of days.
I realize that this isn't exactly what you're asking, but just in case:
When you want to load an actual Java properties file, you'll need to accomodate its encoding. The Java docs indicate that the encoding is ISO 8859-1, which contains some escape sequences that you might not correctly interpret. For instance look at this SO answer to see what's necessary to turn UTF-8 into ISO 8859-1 (and vice versa)
When we needed to do this, we found an open-source PropertyFile.cs and made a few changes to support the escape sequences. This class is a good one for read/write scenarios. You'll need the supporting PropertyFileIterator.cs class as well.
Even if you're not loading true Java properties, make sure that your prop file can express all the characters you need to save (UTF-8 at least)
that is called hint in android use android:hint="Enter Name"
public class Network {
Context context;
public Network(Context context){
this.context = context;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.
ul {_x000D_
display: flex;_x000D_
flex-direction: column-reverse;_x000D_
}_x000D_
_x000D_
/* Apply desired style to all matching elements. */_x000D_
ul > li.list {_x000D_
background-color: #888;_x000D_
}_x000D_
_x000D_
/* Using a more specific selector, "unstyle" elements which are not the first. */_x000D_
ul > li.list ~ li.list {_x000D_
background-color: inherit;_x000D_
}
_x000D_
<ul>_x000D_
<li class="list">0</li>_x000D_
<li>1</li>_x000D_
<li class="list">2</li>_x000D_
</ul>_x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li class="list">1</li>_x000D_
<li class="list">2</li>_x000D_
<li>3</li>_x000D_
</ul>
_x000D_
Double check your manifest, your first activity should have tag
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
inside of activity tag.
If that doesn't work, look for target build, which located in the left of run button (green-colored play button), it should be targeting "app" folder, not a particular activity. if it doesn't targeting "app", just click it and choose "app" from drop down list.
Hope it helps!
In my case this is how I got the information:
find where apache logs are located, and go there, in my case:
cd /var/log/apache2
find in which log openssl information can be found:
grep -i apache.*openssl *_log
e.g. error_log ...
to get fresh information, restart apache, e.g.
rcapache2 restart # or service apache2 restart
check for last entries in the log, e.g.
/var/log/apache2 # tail error_log
[Thu Jun 09 07:42:24 2016] [notice] Apache/... (Linux/...) mod_ssl/2.2.22 OpenSSL/1.0.1t ...
I just got this AndroidX error again after I fixed it a year ago. I am using Flutter.
I was able to make releases using Flutter 1.7.8+hotfix.4, then recently I updated Flutter to version 1.17.4 and then I could not compile a release build any more. Debug builds worked just fine.
TLDR:
This time it was a package using another package that was not updated proper for AndroidX
Make sure to update your packages! :)
Error message: Important part
[+1099 ms] > Task :package_info:verifyReleaseResources FAILED
[ +10 ms] FAILURE: Build failed with an exception.
[ +10 ms] * What went wrong:
[ +29 ms] Execution failed for task ':package_info:verifyReleaseResources'.
[ +3 ms] java.util.concurrent.ExecutionException:com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
[ +7 ms] ...\build\package_info\intermediates\res\merged\release\values\values.xml:171:error: resource android:attr/fontVariationSettings not found.
[ +2 ms] ...\build\package_info\intermediates\res\merged\release\values\values.xml:172:error: resource android:attr/ttcIndex not found.
[ +1 ms] error: failed linking references.
Error message: Distraction
FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'barcode_scan'. > SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.
"fontVariationSettings not found". is an AndroidX error, which requires you to use compileSdkVersion 28, but I already had that, so I suspect something was implemented between my two Flutter versions to be more restrictive.
So I had to go hunting and updated packages and found that. "package_info: ^0.3.2" needed to be "package_info: ^0.4.0" to make it work. To make it "more" future proof write it like this:
package_info: '>=0.4.0 <2.0.0'
After updating packages my code base compiles for release again. Hope it helps.
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
should work.
Include.NON_EMPTY
indicates that property is serialized if its value is not null and not empty.
Include.NON_NULL
indicates that property is serialized if its value is not null.
To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.
Markup:
<canvas id="myCanvas" width="300" height="150"></canvas>
Script (with few different options):
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values
ctx.fillText('Hello World!', 150, 50); // text and position
</script>
Check out the MDN documentation and this JSFiddle example.
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);
addEventListener
lets you set multiple handlers, but isn't supported in IE8 or lower.
IE does have attachEvent
, but it's not exactly the same.
Could be two things. First,
This code is deprecated:
Model.find(:all, :order => ...)
should be:
Model.order(...).all
Find is no longer supported with the :all, :order, and many other options.
Second, you might have had a default_scope that was enforcing some ordering before you called find
on Show
.
Hours of digging around on the internet led me to a few useful articles that explain the issue:
I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.
If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.
All development is done using your choice of C#, Boo, or a dialect of JavaScript.
Most of the example code in the documentation is in JavaScript; if you poke around the official forums and wiki you'll see a pretty even mix of C# and Javascript. Very few people seem to use Boo, but it's just as good; pick the language you already know or are the happiest learning.
Unity takes your C#/JS/Boo code and compiles it to run on iOS, Android, PC, Mac, XBox, PS3, Wii, or web plugin. Depending on the platform that might end up being Objective C or something else, but that's completely transparent to you. There's really no benefit to knowing Objective C; you can't program in it.
Update 2019/31/01
Starting from Unity 2017.2 "UnityScript" (Unity's version of JavaScript, but not identical to) took its first step towards complete deprecation by removing the option to add a "JavaScript" file from the UI. Though JS files could still be used, support for it will completely be dropped in later versions.
This also means that Boo will become unusable as its compiler is actually built as a layer on top of UnityScript and will thus be removed as well.
This means that in the future only C# will have native support.
unity has released a full article on the deprecation of UnityScript and Boo back in August 2017.
This work around will fix the issue found by @Cletus.
function submitForm(form) {
//get the form element's document to create the input control with
//(this way will work across windows in IE8)
var button = form.ownerDocument.createElement('input');
//make sure it can't be seen/disrupts layout (even momentarily)
button.style.display = 'none';
//make it such that it will invoke submit if clicked
button.type = 'submit';
//append it and click it
form.appendChild(button).click();
//if it was prevented, make sure we don't get a build up of buttons
form.removeChild(button);
}
Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!
Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.
The first thing to do is to install the dependencies.
sudo apt-get build-dep python-psycopg2
After that go inside your virtualenv and use
pip install psycopg2-binary
These two commands should solve the problem.
Try this Toggle Buttons
test_activity.xml
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="100px"
android:layout_height="50px"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>
Test.java
public class Test extends Activity {
private ToggleButton togglebutton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}
public void toggleclick(View v){
if(togglebutton.isChecked())
Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
}
}
You are right. If you want to delete the User and all associated objects -> destroy_all
However, if you just want to delete the User without suppressing all associated objects -> delete_all
According to this post : Rails :dependent => :destroy VS :dependent => :delete_all
destroy
/ destroy_all
: The associated objects are destroyed alongside this object by calling their destroy methoddelete
/ delete_all
: All associated objects are destroyed immediately without calling their :destroy methodI have created LoadMoreRecyclerView using Abdulaziz Noor Answer
LoadMoreRecyclerView
public class LoadMoreRecyclerView extends RecyclerView {
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
//WrapperLinearLayout is for handling crash in RecyclerView
private WrapperLinearLayout mLayoutManager;
private Context mContext;
private OnLoadMoreListener onLoadMoreListener;
public LoadMoreRecyclerView(Context context) {
super(context);
mContext = context;
init();
}
public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
private void init(){
mLayoutManager = new WrapperLinearLayout(mContext,LinearLayoutManager.VERTICAL,false);
this.setLayoutManager(mLayoutManager);
this.setItemAnimator(new DefaultItemAnimator());
this.setHasFixedSize(true);
}
@Override
public void onScrolled(int dx, int dy) {
super.onScrolled(dx, dy);
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading)
{
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
loading = false;
Log.v("...", "Call Load More !");
if(onLoadMoreListener != null){
onLoadMoreListener.onLoadMore();
}
//Do pagination.. i.e. fetch new data
}
}
}
}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
}
public void onLoadMoreCompleted(){
loading = true;
}
public void setMoreLoading(boolean moreLoading){
loading = moreLoading;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
}
WrapperLinearLayout
public class WrapperLinearLayout extends LinearLayoutManager
{
public WrapperLinearLayout(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e("probe", "meet a IOOBE in RecyclerView");
}
}
}
//Add it in xml like
<your.package.LoadMoreRecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</your.package.LoadMoreRecyclerView>
OnCreate or onViewCreated
mLoadMoreRecyclerView = (LoadMoreRecyclerView) view.findViewById(R.id.recycler_view);
mLoadMoreRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
callYourService(StartIndex);
}
});
callYourService
private void callYourService(){
//callyour Service and get response in any List
List<AnyModelClass> newDataFromServer = getDataFromServerService();
//Enable Load More
mLoadMoreRecyclerView.onLoadMoreCompleted();
if(newDataFromServer != null && newDataFromServer.size() > 0){
StartIndex += newDataFromServer.size();
if (newDataFromServer.size() < Integer.valueOf(MAX_ROWS)) {
//StopLoading..
mLoadMoreRecyclerView.setMoreLoading(false);
}
}
else{
mLoadMoreRecyclerView.setMoreLoading(false);
mAdapter.notifyDataSetChanged();
}
}
Conditional comment is a comment starts with <!--[if IE]>
which couldn't be read by any browser except IE.
from 2011 Conditional comment isn't supported starting form IE 10 as announced by Microsoft in that time https://msdn.microsoft.com/en-us/library/hh801214(v=vs.85).aspx
The only option to use the Conditional comments is to request IE to run your site as IE 9 which supports the Conditional comments.
you can write your own css and/or js files for ie only and other browsers won't load or execute it.
this code snippet shows how to make IE 10 or 11 run ie-only.css and ie-only.js which contains custom codes to solve IE compatibility issues.
<html>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
<!--[if IE]>
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
<link rel="stylesheet" type="text/css" href='/css/ie-only.css' />
<script src="/js/ie-only.js"></script>
<![endif]-->
</html>
From Blogging Developer:
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.
Note: You can also try out the Key Event Tester (available on the above-mentioned site) to understand this concept.
try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<div name="name" id="name">here</div>
</body>
</html>
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
Try: if(parseInt(order)>0){....
Try this code :)
Its an fully transparent hexa code - "#00000000"
Using the FileUtils.deleteDirectory() method can help to simplify the process of deleting directory and everything below it recursively.
Check this question
$ git pull <remote> <branch> # fetches the code and merges it into
# your working directory
$ git fetch <remote> <branch> # fetches the code but does not merge
# it into your working directory
$ git pull --tag <remote> <branch> # same as above but fetch tags as well
$ git fetch --tag <remote> <branch> # you get the idea
That pretty much covers every case for getting the latest copy of the code from the remote repository.
Swing has no idea what the preferred, minimum and maximum sizes of the GoBoard should be as you have no components inside of it for it to calculate based on, so it picks a (probably wrong) default. Since you are doing custom drawing here, you should implement these methods
Dimension getPreferredSize()
Dimension getMinumumSize()
Dimension getMaximumSize()
or conversely, call the setters for these methods.
Also, to use your new namespaced class you can also do
var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()
First simple rule: never use the String(String)
constructor, it is absolutely useless (*).
So arr.add("ss")
is just fine.
With 3
it's slightly different: 3
is an int
literal, which is not an object. Only objects can be put into a List
. So the int
will need to be converted into an Integer
object. In most cases that will be done automagically for you (that process is called autoboxing). It effectively does the same thing as Integer.valueOf(3)
which can (and will) avoid creating a new Integer
instance in some cases.
So actually writing arr.add(3)
is usually a better idea than using arr.add(new Integer(3))
, because it can avoid creating a new Integer
object and instead reuse and existing one.
Disclaimer: I am focusing on the difference between the second and third code blocks here and pretty much ignoring the generics part. For more information on the generics, please check out the other answers.
(*) there are some obscure corner cases where it is useful, but once you approach those you'll know never to take absolute statements as absolutes ;-)
Sometimes above solutions doesn't work in macbook to get username n password.
IDK why?, here i got another solution.
$ git credential-osxkeychain get
host=github.com
protocol=https
this will revert username and password
A small improvement from the accepted answer is to do the null check and also get full object.
public class DateComparator {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
employees.add(new Employee(4, "name4", null));
employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
System.out.println(employees);
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
System.out.println(format.format(maxDate));
//Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
System.out.println(" minDatedEmployee : " + minDatedEmployee);
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); // minus number would decrement the days
return cal.getTime();
}
}
You would get below results :
[Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]
minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]
Update : What if list itself is empty ?
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
System.out.println(format.format(maxDate));
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Add the icon to the project resources and rename to icon.
Open the designer of the form you want to add the icon to.
Append the InitializeComponent function.
Add this line in the top:
this.Icon = PROJECTNAME.Properties.Resources.icon;
repeat step 4 for any forms in your project you want to update
You can either use the iterator directly like you mentioned, or else keep a second collection and add each item you want to remove to the new collection, then removeAll at the end. This allows you to keep using the type-safety of the for-each loop at the cost of increased memory use and cpu time (shouldn't be a huge problem unless you have really, really big lists or a really old computer)
public static void main(String[] args)
{
Collection<Integer> l = new ArrayList<Integer>();
Collection<Integer> itemsToRemove = new ArrayList<>();
for (int i=0; i < 10; i++) {
l.add(Integer.of(4));
l.add(Integer.of(5));
l.add(Integer.of(6));
}
for (Integer i : l)
{
if (i.intValue() == 5) {
itemsToRemove.add(i);
}
}
l.removeAll(itemsToRemove);
System.out.println(l);
}
I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge
today:function(){
var today = new Date();
var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
var y = today.getFullYear();
var x = String(y+"-"+m+"-"+d);
return x;
}
Use this as an example:
docker create --name new_ubuntu -it -p 8080:8080 -p 15672:15672 -p 5432:5432 ubuntu:latest bash
look what you've created(and copy its CONTAINER ID xxxxx):
docker ps -a
now write the miracle maker word(start):
docker start xxxxx
good luck
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
This code segment for your Model
function getCount($tblName){
$query = $this->db->get($tblName);
$rowCount = $query->num_rows();
return $rowCount;
}
This is for controlr
public function index() {
$data['employeeCount']= $this->CMS_model->getCount("employee");
$this->load->view("hrdept/main",$data);
}
This is for view
<div class="count">
<?php echo $employeeCount; ?>
</div>
This code is used in my project and is working properly.
If you want to view all the commits that changed a file, in all the branches, use this:
git log --follow --all <filepath>
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
Just for clarification: setRequestProperty("User-Agent", "Mozilla ...")
now works just fine and doesn't append java/xx
at the end! At least with Java 1.6.30 and newer.
I listened on my machine with netcat(a port listener):
$ nc -l -p 8080
It simply listens on the port, so you see anything which gets requested, like raw http-headers.
And got the following http-headers without setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
And WITH setRequestProperty:
GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
As you can see the user agent was properly set.
Full example:
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class TestUrlOpener {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/foobar");
URLConnection hc = url.openConnection();
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
System.out.println(hc.getContentType());
}
}
The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.
Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.
For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
For more info, see https://www.firebase.com/docs/transactions.html
UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.
If you want to count upvotes for example, you should create a structure similar to this one:
{
"posts" : {
"-JRHTHaIs-jNPLXOQivY" : {
"upvotes_count":5,
"upvotes" : {
"userX" : true,
"userY" : true,
"userZ" : true,
...
}
}
}
}
And then write a javascript function to increase the upvotes_count
when there is a new write to the upvotes
node.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});
You can read the Documentation to know how to Get Started with Cloud Functions.
Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js
The firebase docs have changed so instead of event
we now have change
and context
.
The given example throws an error complaining that event.data
is undefined. This pattern seems to work better:
exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
const data = change.after.val();
const count = Object.keys(data).length;
return change.after.ref.child('_count').set(count);
});
```
This query will return details about foreign keys in a table, it supports multiple column keys.
SELECT *
FROM
(
SELECT
T1.constraint_name ConstraintName,
T2.COLUMN_NAME ColumnName,
T3.TABLE_NAME RefTableName,
T3.COLUMN_NAME RefColumnName,
T1.MATCH_OPTION MatchOption,
T1.UPDATE_RULE UpdateRule,
T1.DELETE_RULE DeleteRule
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2
ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3
ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME
AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
WHERE A.ConstraintName = 'table_name'
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
Try These
Call Functions With Dynamic Names, like this:
let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()
with parameters:
let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()
Run Dynamic Code:
let some_code = "alert('hahaha');";
(new Function(some_code))()
try yo write document.getElementById('id').style.visibility="hidden";
SELECT name,COUNT(*) as count
FROM tablename
GROUP BY name
ORDER BY count DESC;
If you have access to the server then you can use
select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null
For full details see port number of SQL Server
The arguments that you provide to a bashscript will appear in the variables $1
and $2
and $3
where the number refers to the argument. $0
is the command itself.
The arguments are seperated by spaces, so if you would provide the -from
and -to
in the command, they will end up in these variables too, so for this:
./ocrscript.sh -from /home/kristoffer/test.png -to /home/kristoffer/test.txt
You'll get:
$0 # ocrscript.sh
$1 # -from
$2 # /home/kristoffer/test.png
$3 # -to
$4 # /home/kristoffer/test.txt
It might be easier to omit the -from
and the -to
, like:
ocrscript.sh /home/kristoffer/test.png /home/kristoffer/test.txt
Then you'll have:
$1 # /home/kristoffer/test.png
$2 # /home/kristoffer/test.txt
The downside is that you'll have to supply it in the right order. There are libraries that can make it easier to parse named arguments on the command line, but usually for simple shell scripts you should just use the easy way, if it's no problem.
Then you can do:
/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1
The double quotes around the $1
and the $2
are not always necessary but are adviced, because some strings won't work if you don't put them between double quotes.
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
I had the same issue and eventually chose to use a Rectangle element:
<Rectangle HorizontalAlignment="Stretch" Fill="Blue" Height="4"/>
In my opinion it's somewhat easier to modify/shape than a separator.
Of course the Separator
is a very easy and neat solution for simple separations :)